From d11ae61464c76ba0573ebebe24cd9acfbd60af5a Mon Sep 17 00:00:00 2001 From: Steve Zhang Date: Thu, 19 Feb 2026 14:41:19 -0500 Subject: [PATCH 01/27] extension works for MCP Bridge, phase 1 finsihed --- .../page-2026-02-19T12-08-58-172Z.png | Bin 0 -> 99400 bytes .../page-2026-02-19T12-09-50-744Z.png | Bin 0 -> 109193 bytes .../page-2026-02-19T12-49-02-980Z.png | Bin 0 -> 56027 bytes .../page-2026-02-19T12-53-41-800Z.png | Bin 0 -> 46737 bytes BACKLOG.md | 8 +- CLAUDE.md | 46 +- PLAN.md | 97 +- README.md | 270 +-- architecture-diagram.png | Bin 25258 -> 56509 bytes architecture-sequence.md | 78 + extension-architecture.png | Bin 0 -> 47114 bytes package-lock.json | 212 +- package.json | 8 +- packages/cli/bin/playwright-repl.mjs | 8 +- packages/cli/src/repl.mjs | 19 +- packages/cli/test/repl-helpers.test.mjs | 12 +- packages/core/package.json | 3 +- packages/core/src/engine.mjs | 87 +- packages/core/src/extension-server.mjs | 154 ++ packages/core/src/index.mjs | 1 + packages/core/src/resolve.mjs | 4 +- packages/core/test/extension-server.test.mjs | 359 ++++ packages/extension/background.js | 184 ++ packages/extension/content/recorder.js | 187 ++ packages/extension/devtools.html | 9 + packages/extension/devtools.js | 5 + packages/extension/icons/icon128.png | Bin 0 -> 742 bytes packages/extension/icons/icon16.png | Bin 0 -> 113 bytes packages/extension/icons/icon48.png | Bin 0 -> 266 bytes packages/extension/lib/converter.js | 132 ++ packages/extension/lib/relayConnection.js | 112 ++ packages/extension/manifest.json | 23 + packages/extension/package.json | 12 +- packages/extension/panel/panel.css | 690 +++++++ packages/extension/panel/panel.html | 68 + packages/extension/panel/panel.js | 1047 ++++++++++ packages/extension/test/background.test.js | 371 ++++ packages/extension/test/converter.test.js | 289 +++ packages/extension/test/devtools.test.js | 14 + packages/extension/test/panel.test.js | 1725 +++++++++++++++++ packages/extension/test/recorder.test.js | 534 +++++ packages/extension/test/setup.js | 4 + packages/extension/vitest.config.js | 13 + 43 files changed, 6596 insertions(+), 189 deletions(-) create mode 100644 .playwright-mcp/page-2026-02-19T12-08-58-172Z.png create mode 100644 .playwright-mcp/page-2026-02-19T12-09-50-744Z.png create mode 100644 .playwright-mcp/page-2026-02-19T12-49-02-980Z.png create mode 100644 .playwright-mcp/page-2026-02-19T12-53-41-800Z.png create mode 100644 architecture-sequence.md create mode 100644 extension-architecture.png create mode 100644 packages/core/src/extension-server.mjs create mode 100644 packages/core/test/extension-server.test.mjs create mode 100644 packages/extension/background.js create mode 100644 packages/extension/content/recorder.js create mode 100644 packages/extension/devtools.html create mode 100644 packages/extension/devtools.js create mode 100644 packages/extension/icons/icon128.png create mode 100644 packages/extension/icons/icon16.png create mode 100644 packages/extension/icons/icon48.png create mode 100644 packages/extension/lib/converter.js create mode 100644 packages/extension/lib/relayConnection.js create mode 100644 packages/extension/manifest.json create mode 100644 packages/extension/panel/panel.css create mode 100644 packages/extension/panel/panel.html create mode 100644 packages/extension/panel/panel.js create mode 100644 packages/extension/test/background.test.js create mode 100644 packages/extension/test/converter.test.js create mode 100644 packages/extension/test/devtools.test.js create mode 100644 packages/extension/test/panel.test.js create mode 100644 packages/extension/test/recorder.test.js create mode 100644 packages/extension/test/setup.js create mode 100644 packages/extension/vitest.config.js diff --git a/.playwright-mcp/page-2026-02-19T12-08-58-172Z.png b/.playwright-mcp/page-2026-02-19T12-08-58-172Z.png new file mode 100644 index 0000000000000000000000000000000000000000..62e71f917864b42224a951d6aaee7979d7706ded GIT binary patch literal 99400 zcmeFZWmH_>_AN++2oiz^5AH67LlWHG-JRf2SO@`v2X~i3f)oyg1$TFMcZWjW$-Vb? z|J`GBe|+yt_xV(#WbbqKUVE*%=9;U5739QGk?@fa5D-u$B}9}E5D>=^5T4J!c@Dgj z{uuES0pUG@q{t@~_tb+$#ME&!lGi5_o=2}1R*#PC+I53$SU!B|nlbQyTMm6@OyJq= zh4Ko;jjE0h#clhSzf%Hu`AIi3maDhA>FTA=@?ubR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%w_NAW G{eJ)tyDz)| literal 0 HcmV?d00001 diff --git a/.playwright-mcp/page-2026-02-19T12-53-41-800Z.png b/.playwright-mcp/page-2026-02-19T12-53-41-800Z.png new file mode 100644 index 0000000000000000000000000000000000000000..7fa348cfdf5492ae56bc45e3712af962e9d6eccf GIT binary patch literal 46737 zcmc$_WmH_j_a#a~0>Kl41PBn^A-Dxdg1bZT1b2cvBoH732<{GzH0}-!!QEXtxYKx} z-E+xr=B@RAYu0>tvu550Rg2Um;v6$;986j_N68Xjo}%NY6un@IHIc}GOgao?FSuuy>=})$#FibWefLewN3?!cxp^;Ci@tWB$_|_<6tdd>Huo)*#CS{Gf0) zc*D#7dQAPh_pC&>mRU>;Ix=E^cXhI1gwQTbeFQYpbN}1^2!9|7kHe_#?s_}3woQ@; z6}ZpG#=^oPB9cxvG&tDocQ54sSb`h4{khq&#lvxDjH)!6lao_9Q*;yU#lQX!h5YUW zFf41Nm( z%)of4QXaKNdG8a$sfL!AmN}JYIKd%QBZD z9Ln8F5@*kya%GCyrHU&M)+FY@pjD#cT~xzq@m@?<8M-WDUf# zOc$MCTKVPtdi0;i1z8oxC+kRsT{;s?u!dT(`NcpyvueV}fAeSlrlUQ#7um|nm{k%o zH8xeIv%E&nP-;of!m__LoEk|XQly$2+}zxpno5S$`)4Vk0q5<&j(Y7c--x|w#;~vB z3LidnBy(G^8@BWz>okkCR#sM)III#g-5-q#TyG|czkFEcx4najPxF6p(H6-lD?=Rb zd(O5;nI_-)M=KL45sof5yVrgsSv%bvOioT-%G!iIK05P5ZfuBw*LLT*KOd%OYE*Wo z-E59+t`B_d_ICG4gd3h4-n%nC^xWY;8ZN=`;>8PeT#BLo5v@Y+>8Wzq&f&7>LXC2f z2IuMTWCo;&cdb^$+Pk&5v@}+Mj2{A^{?L2tvW|ErzV zLUKx1%e#>+Q88c>p?rQ07Un#DKG_+9CzdH9yt~v$ub7HW!UeLL%r9>_9hfejEz@sp zao!#|gJdEv7xQrR^|4tY6)Mr0$O+3all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kS>a)e;K&c~qLDpSDb~kI z97ssMIfLkm9E${V*M&vvV|1B9TkYC1YcwO5t->qb&<5ff0%%6j<*yov*M(0EKK1fh zH=2fr$`*}iu8T`5*EPZ_%Vk2;CWRxCDlc(|bpth147=OjJUM1H3umhJ@N-F(FzkAk z1Z=Q1Yi6&My|Hm98@~SG$SaI=z55koL+Q-D-K>a5N5i-7sRVvGm66rL%zF-{@u_{| z7dpPb*!lb#$CV1pHR_X*|2c{J(KL>zfYgpdSpqWw{x;_lHgjG67Ji&Vi^rQsL$+@^ zZ@oca{kqAWz`}wMD*Z|l2VP(>{lMKH@B-&%H@|~Loca0PY=g=1.59.0-alpha` (browser engine) -- **Monorepo**: npm workspaces (`packages/core`, `packages/cli`) +- **Dependencies**: `minimist` (command parsing), `playwright@>=1.59.0-alpha` (browser engine), `ws` (WebSocket server for extension mode) +- **Monorepo**: npm workspaces (`packages/core`, `packages/cli`, `packages/extension`) - **Testing**: vitest - **Key insight**: `playwright@1.59.0-alpha` includes `lib/mcp/browser/` (BrowserServerBackend, contextFactory). The stable `playwright@1.58` does NOT. Once 1.59 goes stable, the alpha pin can be removed. diff --git a/PLAN.md b/PLAN.md index 683add5..81cadfd 100644 --- a/PLAN.md +++ b/PLAN.md @@ -211,27 +211,92 @@ click "Sign In" ## Phase 8: Extension Server + Extension Rewrite -**Goal**: `playwright-repl --extension` starts a WebSocket server. Extension connects as thin CDP relay. +**Goal**: `playwright-repl --extension` starts a WebSocket server. Chrome extension connects as a thin CDP relay. All 35+ commands handled by server-side Playwright — extension drops from 800 lines to ~150. -### New file: `packages/core/src/extension-server.mjs` (~150 lines) +**Status**: In progress -WebSocket server that: -1. Starts CDP relay (reuse `CDPRelayServer` from Playwright) -2. Accepts extension WebSocket connection for CDP forwarding -3. Accepts command WebSocket connection from panel -4. Routes commands → `Engine.run()` → results back to panel +### Architecture -### Extension `background.js` rewrite (~150 lines, replaces 800) +``` +┌─────────────────────────────────────────────────────────┐ +│ Chrome Extension (DevTools Panel) │ +│ │ +│ panel.js ──sendMessage──► background.js │ +│ ▲ │ ▲ │ +│ │ port.postMessage │ │ chrome.debugger │ +│ │ (results, recording) │ │ (CDP to tab) │ +│ │ │ │ +└───────────────────────────────┼──┼──────────────────────┘ + WebSocket │ │ + ▼ │ +┌───────────────────────────────────────────────────────────┐ +│ Node.js Server (playwright-repl --extension) │ +│ │ +│ ExtensionServer │ +│ ├── /extension WS ← background.js connects here │ +│ ├── HTTP /json/* ← Playwright CDP discovery │ +│ └── /devtools/* ← Playwright CDP WebSocket │ +│ │ +│ Engine (BrowserServerBackend) │ +│ └── connectOverCDP → local proxy → relay → extension │ +└───────────────────────────────────────────────────────────┘ +``` + +### Three Connection Modes + +| Mode | Flag | Browser Source | Use Case | +|------|------|---------------|----------| +| **Launch** | `--headed` (default) | Launches new Chromium via Playwright | General automation | +| **Connect** | `--connect [port]` | Existing Chrome with `--remote-debugging-port` | Debug running app | +| **Extension** | `--extension [--port N]` | User's normal Chrome via extension CDP relay | DevTools panel REPL | + +### New file: `packages/core/src/extension-server.mjs` (~300 lines) + +`ExtensionServer` class — HTTP + WebSocket server: + +1. **CDP discovery** — `GET /json/version`, `GET /json` so Playwright can discover the relayed browser +2. **CDP relay** — WebSocket `/devtools/browser/{id}` accepts Playwright connection, forwards CDP to extension via `/extension` WebSocket +3. **Target domain** — handles `setDiscoverTargets`, `attachToTarget`, `detachFromTarget` to present the extension's tab as a Playwright target +4. **Command channel** — receives commands from panel (via background.js relay), routes through `Engine.run()`, returns results + +### Extension rewrite: `packages/extension/background.js` (~150 lines, replaces 800) Two roles: -1. **CDP relay client**: connect to server's relay WebSocket, forward `chrome.debugger` commands -2. **Command proxy**: receive commands from panel, forward to server's command WebSocket +1. **CDP relay**: connect to server WebSocket, bridge `chrome.debugger.sendCommand()` ↔ CDP messages +2. **Command proxy**: receive commands from panel via `chrome.runtime.onMessage`, forward to server, return results + +Recording stays extension-side for Phase 8 (inject recorder.js, listen for `__pw:` events, forward to panel). + +### Copied from `playwright-repl-extension` repo + +- `panel/panel.html`, `panel/panel.css`, `panel/panel.js` (DevTools panel UI) +- `content/recorder.js` (event recorder injected into pages) +- `lib/converter.js` (.pw → Playwright test export) +- `devtools.html`, `devtools.js`, `manifest.json`, `icons/` + +### Deleted (replaced by server-side Playwright) + +- `lib/commands.js`, `lib/locators.js`, `lib/page-scripts.js`, `lib/formatter.js` + +### Modify: `packages/core/src/engine.mjs` (+30 lines) + +Extension mode in `start()`: +- Create `ExtensionServer`, start on `opts.port || 3000` +- Wait for extension to connect +- Set `cdpEndpoint` to local proxy +- Update `close()` to shut down ExtensionServer + +### Modify: `packages/cli/bin/playwright-repl.mjs` (+5 lines) + +- Add `--port` string option (default: 3000) +- Pass `port` to `startRepl(opts)` ### Verify ```bash -node packages/cli/bin/playwright-repl.mjs --extension --port 9876 -# Extension auto-connects, commands work in DevTools panel -# Recording still works +node packages/cli/bin/playwright-repl.mjs --extension --port 3000 +# Load unpacked extension from packages/extension/ +# Open website → DevTools → Playwright REPL panel +# snapshot, click e5, run-code, recording all work ``` --- @@ -248,9 +313,9 @@ node packages/cli/bin/playwright-repl.mjs --extension --port 9876 ## Phase Dependencies ``` -Phase 5 (Monorepo) → Phase 6 (Engine) → Phase 7 (Connect) - → Phase 8 (Extension) - → Phase 9 (Cleanup) +Phase 5 (Monorepo) ✓ → Phase 6 (Engine) ✓ → Phase 7 (Connect) ✓ + → Phase 8 (Extension) ← current + → Phase 9 (Cleanup) ``` Phases 7 and 8 are independent of each other. Phase 9 after all modes are verified. diff --git a/README.md b/README.md index 5fe0bf6..71001f5 100644 --- a/README.md +++ b/README.md @@ -2,20 +2,61 @@ ![playwright-repl](cover-image.png) -Interactive REPL for Playwright browser automation — keyword-driven testing from your terminal. +Interactive browser automation powered by Playwright — use it from your **terminal** or as a **Chrome DevTools panel**. -Inspired by [playwright-cli](https://github.com/anthropics/playwright-cli), reusing its command vocabulary and Playwright's browser tools. Where playwright-cli is designed for AI agents (one command per process), playwright-repl is designed for **humans** — a persistent session with recording, replay, and instant feedback. +Two frontends, one engine: the CLI gives you a terminal REPL with recording and replay; the Chrome extension gives you a DevTools panel with a script editor and visual recorder. Both run the same 35+ Playwright commands through a shared Engine — no command duplication. ## Why? -**playwright-repl** runs Playwright's browser tools in-process. Type a command, see the result instantly. Record your session, replay it later — no code, no tokens, no setup. +**playwright-repl** runs Playwright's browser tools in-process. Type a command, see the result instantly. No code, no tokens, no setup. + +- **CLI** — terminal REPL with recording, replay, piping, and 50+ aliases +- **Extension** — Chrome DevTools panel with script editor, recorder, and light/dark themes +- **Same commands everywhere** — `click`, `fill`, `snapshot`, `verify-text` work identically in both Key features: -- **Text locators** — use `click "Submit"` or `fill "Email" "test@example.com"` instead of element refs. Auto-resolves via getByText, getByLabel, getByPlaceholder, and getByRole with fallback chains -- **Element refs** — also supports ref-based commands (`click e5`, `fill e7 "hello"`) from `snapshot` output -- **Assertions** — `verify-text`, `verify-element`, `verify-value`, `verify-list` for inline validation -- **Record & replay** — capture sessions as `.pw` files and replay them headlessly or step-by-step -- **Connect mode** — attach to an existing Chrome instance via `--connect [port]` +- **Text locators** — `click "Submit"` or `fill "Email" "test@example.com"` instead of element refs +- **Element refs** — `click e5`, `fill e7 "hello"` from `snapshot` output +- **Assertions** — `verify-text`, `verify-element`, `verify-value`, `verify-list` +- **Record & replay** — capture sessions as `.pw` files (CLI) or record interactions visually (extension) +- **Three connection modes** — launch a new browser, connect to existing Chrome, or use the extension relay + +## Architecture + +![How It Works](architecture-diagram.png) + +Both CLI and Extension are frontends to the Engine. Neither directly accesses Chrome. + +### Three Connection Modes + +| Mode | Flag | Browser Source | Use Case | +|------|------|---------------|----------| +| **Launch** | `--headed` (default) | Launches new Chromium via Playwright | General automation | +| **Connect** | `--connect [port]` | Existing Chrome with `--remote-debugging-port` | Debug running app | +| **Extension** | `--extension [--port N]` | User's normal Chrome via extension CDP relay | DevTools panel REPL | + +### Extension Mode Detail + +![Extension Mode](extension-architecture.png) + +The extension is a thin CDP relay — it bridges `chrome.debugger` access from the user's browser to the Node.js server, which runs the full Engine with all 35+ Playwright commands. + +## Quick Start — CLI + +```bash +# Install +npm install -g playwright-repl +npx playwright install # browser binaries (if needed) + +# Start the REPL (launches browser automatically) +playwright-repl + +# With a visible browser +playwright-repl --headed + +# Connect to existing Chrome +playwright-repl --connect 9222 +``` ``` pw> goto https://demo.playwright.dev/todomvc/ @@ -27,23 +68,22 @@ pw> check "Buy groceries" pw> verify-text "1 item left" ``` -Record it, replay it later: +## Quick Start — Extension ```bash -pw> .record smoke-test -⏺ Recording to smoke-test.pw +# 1. Start the extension server +playwright-repl --extension -pw> goto https://demo.playwright.dev/todomvc/ -pw> fill "What needs to be done?" "Buy groceries" -pw> press Enter -pw> verify-text "1 item left" -pw> .save -✓ Saved 4 commands to smoke-test.pw +# 2. Load the extension +# chrome://extensions → Enable Developer Mode → Load unpacked → packages/extension/ -# Replay any time -$ playwright-repl --replay smoke-test.pw +# 3. Open any website → DevTools (F12) → "Playwright REPL" panel + +# 4. Type commands in the panel — same syntax as CLI ``` +The extension panel includes a script editor, visual recorder, and export to Playwright tests. + ## Install ```bash @@ -57,43 +97,6 @@ git clone https://github.com/stevez/playwright-repl.git cd playwright-repl && npm install && npm link ``` -## Quick Start - -```bash -# Start the REPL (launches browser automatically) -playwright-repl - -# With a visible browser -playwright-repl --headed - -# With a specific browser -playwright-repl --headed --browser firefox - -# Connect to existing Chrome (must be launched with --remote-debugging-port) -playwright-repl --connect 9222 -``` - -Once inside the REPL, use either **text locators** or **element refs**: - -``` -pw> goto https://demo.playwright.dev/todomvc/ - -# Text locators — no snapshot needed -pw> fill "What needs to be done?" "Buy groceries" -pw> press Enter -pw> check "Buy groceries" -pw> verify-text "0 items left" - -# Or use element refs from snapshot -pw> snapshot -- textbox "What needs to be done?" [ref=e8] -- listitem "Buy groceries" [ref=e21] - -pw> click e21 # click by ref -pw> screenshot # take a screenshot -pw> close # close browser -``` - ## Usage ```bash @@ -115,6 +118,10 @@ echo -e "goto https://example.com\nsnapshot" | playwright-repl # Connect to existing Chrome via CDP playwright-repl --connect # default port 9222 playwright-repl --connect 9333 # custom port + +# Extension mode +playwright-repl --extension # default port 3000 +playwright-repl --extension --port 4000 # custom port ``` ### CLI Options @@ -126,6 +133,8 @@ playwright-repl --connect 9333 # custom port | `--persistent` | Use persistent browser profile | | `--profile

` | Persistent profile directory | | `--connect [port]` | Connect to existing Chrome via CDP (default: `9222`) | +| `--extension` | Start WebSocket server for Chrome extension | +| `--port ` | Extension server port (default: `3000`) | | `--config ` | Path to config file | | `--replay ` | Replay a `.pw` session file | | `--record ` | Start REPL with recording to file | @@ -135,6 +144,8 @@ playwright-repl --connect 9333 # custom port ## Commands +All commands work in both CLI and extension. In the CLI, type directly at the `pw>` prompt. In the extension, type in the REPL input or use the script editor. + ### Navigation | Command | Alias | Description | @@ -236,6 +247,8 @@ playwright-repl --connect 9333 # custom port | `close` | `q` | Close the browser | | `config-print` | — | Print browser config | +## CLI Features + ### REPL Meta-Commands | Command | Description | @@ -251,11 +264,11 @@ playwright-repl --connect 9333 # custom port | `.replay ` | Replay a recorded session | | `.exit` | Exit REPL (also Ctrl+D) | -## Session Recording & Replay +### Session Recording & Replay Record your browser interactions and replay them later — great for regression tests, onboarding demos, or sharing reproducible flows. -### Record +#### Record ```bash # From CLI @@ -272,7 +285,7 @@ pw> .save ✓ Saved 4 commands to my-test.pw ``` -### Replay +#### Replay ```bash # Full speed @@ -285,7 +298,7 @@ playwright-repl --replay my-test.pw --step --headed pw> .replay my-test.pw ``` -### File Format +#### File Format `.pw` files are plain text — human-readable, diffable, version-controllable: @@ -300,7 +313,7 @@ verify-text "Buy groceries" verify-text "1 item left" ``` -### Recording Controls +#### Recording Controls | Command | Description | |---------|-------------| @@ -309,37 +322,11 @@ verify-text "1 item left" | `.save` | Stop and save to file | | `.discard` | Discard without saving | -## Examples - -All examples use the [TodoMVC demo](https://demo.playwright.dev/todomvc/) and can be run directly: - -| File | Description | -|------|-------------| -| [01-add-todos.pw](packages/cli/examples/01-add-todos.pw) | Add todos and verify with assertions | -| [02-complete-and-filter.pw](packages/cli/examples/02-complete-and-filter.pw) | Complete todos, use filters | -| [03-record-session.pw](packages/cli/examples/03-record-session.pw) | Record a test session | -| [04-replay-session.pw](packages/cli/examples/04-replay-session.pw) | Replay with step-through | -| [05-ci-pipe.pw](packages/cli/examples/05-ci-pipe.pw) | CI smoke test | -| [06-edit-todo.pw](packages/cli/examples/06-edit-todo.pw) | Double-click to edit a todo | - -Try one: - -```bash -# Run an example with a visible browser -playwright-repl --replay packages/cli/examples/01-add-todos.pw --headed - -# Step through an example interactively -playwright-repl --replay packages/cli/examples/04-replay-session.pw --step --headed - -# Run as a CI smoke test (headless, silent) -playwright-repl --replay packages/cli/examples/05-ci-pipe.pw --silent -``` - -## eval & run-code +### eval & run-code Two ways to run custom code from the REPL: -### eval — Browser Context +#### eval — Browser Context Runs JavaScript inside the browser page (via `page.evaluate`). Use browser globals like `document`, `window`, `location`: @@ -354,7 +341,7 @@ pw> eval document.querySelectorAll('a').length 42 ``` -### run-code — Playwright API +#### run-code — Playwright API Runs code with full access to the Playwright `page` object. The REPL auto-wraps your code — just write the body: @@ -366,9 +353,6 @@ pw> run-code page.url() pw> run-code page.locator('h1').textContent() → async (page) => { return await page.locator('h1').textContent() } "Installation" - -pw> run-code await page.locator('.nav a').allTextContents() -→ async (page) => { await page.locator('.nav a').allTextContents() } ``` For multiple statements, use semicolons: @@ -377,41 +361,43 @@ For multiple statements, use semicolons: pw> run-code const u = await page.url(); const t = await page.title(); return {u, t} ``` -Full function expressions also work: +## Extension Features -``` -pw> run-code async (page) => { await page.waitForSelector('.loaded'); return await page.title(); } -``` +### DevTools Panel -## Architecture +The extension adds a "Playwright REPL" tab in Chrome DevTools with: -The REPL runs Playwright's `BrowserServerBackend` in-process via an `Engine` class. No daemon, no socket — commands execute directly. +- **REPL input** — type commands at the bottom, results appear in the console pane +- **Script editor** — write multi-line `.pw` scripts with line numbers, run all or step through +- **Visual recorder** — click Record, interact with the page, recorded commands appear automatically +- **Export** — convert `.pw` commands to Playwright TypeScript test code +- **Light/dark themes** — matches your DevTools theme -![Architecture](architecture-diagram.png) +### Recording in Extension -### How It Works +Click the Record button in the toolbar, then interact with the page normally. The recorder captures: -![Command Flow](flow-diagram.png) +- **Clicks** — with text locators and context (e.g., `click "Delete" "Buy groceries"`) +- **Form input** — debounced fill commands (e.g., `fill "Email" "test@example.com"`) +- **Selections** — dropdown changes (e.g., `select "Country" "United States"`) +- **Checkboxes** — check/uncheck with label context +- **Key presses** — Enter, Tab, Escape -### Monorepo Structure +### Export to Playwright + +The extension can export `.pw` commands to Playwright TypeScript: ``` -packages/ -├── core/ # Engine + shared utilities -│ └── src/ -│ ├── engine.mjs # Wraps BrowserServerBackend in-process -│ ├── parser.mjs # Command parsing and alias resolution -│ ├── page-scripts.mjs # Text locator and assertion helpers -│ └── ... -└── cli/ # Terminal REPL - └── src/ - ├── repl.mjs # Interactive readline loop - └── recorder.mjs # Session recording/replay +# .pw commands → Playwright TypeScript +goto https://example.com → await page.goto("https://example.com"); +click "Submit" → await page.getByText("Submit").click(); +fill "Email" "test@example.com" → await page.getByLabel("Email").fill("test@example.com"); +verify-text "Success" → await expect(page.getByText("Success")).toBeVisible(); ``` ### Connect Mode -To control an existing Chrome instance: +To control an existing Chrome instance from the CLI: ```bash # Start Chrome with debugging port @@ -421,6 +407,60 @@ chrome --remote-debugging-port=9222 playwright-repl --connect 9222 ``` +## Examples + +All examples use the [TodoMVC demo](https://demo.playwright.dev/todomvc/) and can be run directly: + +| File | Description | +|------|-------------| +| [01-add-todos.pw](packages/cli/examples/01-add-todos.pw) | Add todos and verify with assertions | +| [02-complete-and-filter.pw](packages/cli/examples/02-complete-and-filter.pw) | Complete todos, use filters | +| [03-record-session.pw](packages/cli/examples/03-record-session.pw) | Record a test session | +| [04-replay-session.pw](packages/cli/examples/04-replay-session.pw) | Replay with step-through | +| [05-ci-pipe.pw](packages/cli/examples/05-ci-pipe.pw) | CI smoke test | +| [06-edit-todo.pw](packages/cli/examples/06-edit-todo.pw) | Double-click to edit a todo | + +Try one: + +```bash +# Run an example with a visible browser +playwright-repl --replay packages/cli/examples/01-add-todos.pw --headed + +# Step through an example interactively +playwright-repl --replay packages/cli/examples/04-replay-session.pw --step --headed + +# Run as a CI smoke test (headless, silent) +playwright-repl --replay packages/cli/examples/05-ci-pipe.pw --silent +``` + +## Monorepo Structure + +``` +packages/ +├── core/ # Engine + shared utilities +│ └── src/ +│ ├── engine.mjs # Wraps BrowserServerBackend in-process +│ ├── extension-server.mjs # WebSocket server for extension CDP relay +│ ├── parser.mjs # Command parsing and alias resolution +│ ├── page-scripts.mjs # Text locator and assertion helpers +│ └── ... +├── cli/ # Terminal REPL +│ └── src/ +│ ├── repl.mjs # Interactive readline loop +│ └── recorder.mjs # Session recording/replay +└── extension/ # Chrome DevTools panel extension + ├── manifest.json # Manifest V3 config + ├── background.js # Thin CDP relay + command proxy + ├── panel/ # DevTools panel UI + │ ├── panel.html + │ ├── panel.js + │ └── panel.css + ├── content/ + │ └── recorder.js # Event recorder injected into pages + └── lib/ + └── converter.js # .pw → Playwright test export +``` + ## Requirements - **Node.js** >= 18 diff --git a/architecture-diagram.png b/architecture-diagram.png index fe4497f09fdaeb0952c98d80efdbe92281e74f7b..4c20fbadd25b5af8ada849f536f9e4a152d522e2 100644 GIT binary patch literal 56509 zcmeFYg;N}F@IJVN1PPWvfZ!nsZoyrGySux)`;uS*0>Pcd-Q6L$v$(ta;rYJ9g@s{u{006*{k`z@201*Gee~2ir;4NE& z$8!L{JAjnvcU8~ylT|cN+4&{p^Lchrlx|r{&hIk$s6){~S@Aizjni2P+fAbN=`9I7 zgms05Vn@_&Hdbo79U#kmt2dL%@t?mMVaF)~6|KITcpgyuV z5C8#VVVTQfCiZ*?0HFk700uxoQ(o1Qpjz*uHd~4N+Vul+Cho@`gw=k%wI!#%jp7-x zb~o@CzhTn|7G1Rr0N`2k@0F=iKBP>)B9>MASj@OB2-+g^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0s=XI!IwH!yO2Tii;%%0fiwk4Oz1+*o!~UNPms$j(FK#4lct)I zHx}u)OL&=XTdE!+S~>(pwmgueVJ|kz9v30MzvWoYLCwIp>!Tkv{#YeSq~3PqHu~sw zmyZRipq`={>$~zHGo{WrZ>51-05yipl6_-hqycr1?;RHsT0|1!hfB#3I3EjTL-%G$F*8SP$ z<=lhCJ>WDW2BpILZWJc)#{cLv(YIxO9z2~?L0>Cm?*#sM!HR>Tb%6Qlv4OFKHmZ*C z4PBrrxVp9LMrA5E7&33R{KfQHi*n3K2{g0niS<9Ii4-r&j}hlkHvvt;1wvc2#$ z<(hWoi=(1wlm_;2uM-372o>37=4tBTdvVVzI=8F?+7|XcF-Qf;nFp73fN}7L2(viP ziY{9Z7w5H?Qw?r;0bM0_|4s~6sVV3*=o;^=C^{ZrxTUM}NobO#IrG5~TSNbt0NXx9 zXctoAfyXo;lN90!GuYpZ^82M;NDkm;(6YkFqX-JS9q$~P+V;gDyq|1F-)H>gxuYLR zFY}Q9K>hz^iSn;Xng8qSQ1@s|&;5M_{k|eP4%mOU2o?ZsMmPJ-z0mqMH1g6aQneCh Gq5lTk%74B9 diff --git a/architecture-sequence.md b/architecture-sequence.md new file mode 100644 index 0000000..91c65cb --- /dev/null +++ b/architecture-sequence.md @@ -0,0 +1,78 @@ +# Architecture Reference + +## 1. Regular Playwright MCP + +Playwright launches its own browser. Direct CDP connection. + +```mermaid +sequenceDiagram + participant LLM as LLM (Claude, etc.) + participant MCP as Playwright MCP Server + participant PW as Playwright + participant BR as Browser (launched) + + LLM->>MCP: tool call: browser_click({ref:"e5"}) + MCP->>PW: execute tool + PW->>BR: CDP: Input.dispatchMouseEvent + BR-->>PW: done + PW-->>MCP: result + MCP-->>LLM: "Clicked" +``` + +Playwright owns the browser — talks to it directly via CDP WebSocket. + +## 2. Playwright MCP with MCP Bridge Extension + +Playwright can't launch the user's browser. Needs the bridge extension to relay CDP. + +```mermaid +sequenceDiagram + participant LLM as LLM (Claude, etc.) + participant MCP as Playwright MCP Server + participant PW as Playwright + participant RELAY as CDPRelayServer + participant BRIDGE as MCP Bridge Extension + participant TAB as User's Browser Tab + + BRIDGE->>RELAY: WebSocket connect /extension + PW->>RELAY: WebSocket connect /devtools/browser/{uuid} + + LLM->>MCP: tool call: browser_click({ref:"e5"}) + MCP->>PW: execute tool + PW->>RELAY: CDP: Input.dispatchMouseEvent + RELAY->>BRIDGE: forwardCDPCommand + BRIDGE->>TAB: chrome.debugger.sendCommand + TAB-->>BRIDGE: done + BRIDGE-->>RELAY: result + RELAY-->>PW: result + PW-->>MCP: result + MCP-->>LLM: "Clicked" +``` + +Same CDP messages, but relayed through the bridge because Playwright has no direct connection to the user's browser. + +## 3. Our Extension (playwright-repl --extension) + +Same as diagram 2, but our background.js replaces the MCP Bridge, and the user types commands instead of an LLM. + +```mermaid +sequenceDiagram + participant BG as background.js + participant CS as CommandServer + participant ENG as Engine + participant PW as Playwright + participant TAB as Browser Tab + + BG->>CS: POST /run "click e5" + CS->>ENG: engine.run() + ENG->>PW: callTool("browser_click") + PW->>CS: CDP: dispatchMouseEvent + CS->>BG: forwardCDPCommand + BG->>TAB: chrome.debugger.sendCommand + TAB-->>BG: done + BG-->>CS: result + CS-->>PW: result + PW-->>ENG: "Clicked" + ENG-->>CS: {text:"Clicked"} + CS-->>BG: HTTP 200 +``` diff --git a/extension-architecture.png b/extension-architecture.png new file mode 100644 index 0000000000000000000000000000000000000000..fbff4353352e7752193f9b3b59c6adc78f1827cc GIT binary patch literal 47114 zcmeFZG1$oPY8y;EDM^2|&XaL;oi+zXQnrNio3Fk$)2KGJ&!5%&+>#JnTlw)z23cMVnHncODjzdtMBI zkHI>()9*kfXu8L*ecKdlwg(r!2X!IBzH*;G6Z1EKfa>-m!E#mzboZ{i;MA`)X7%tn?HzpPfd8c5WXT zge5d@i)Nk)&-jF?lv?Xnv(V%uMp|%sx2=MJ>4LQ|_&WJU3q$d2rI5TbE(d4%8&QKD z;DhM>=v0vT>Dxl)nK=B04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pNxFk1!P;PyRitLr<4wanm#KVipTkCjYm&#>O|CmS8J`Rpq9O`V>?-3R?+4O=`kUo z9>+UQx2&-ZX&|IkF2W4?A-`MElU=4_qZN-nj&iRv?rFZx>nFygqPS8$OG^|WLjqod`bb?^JKL~F7^v9Y80qD5^G z6Y^{a=ri5D4t-MHQLyH{KIGf_THwg>`2%d(oBjjA6j7Ox*V^qq~#;|Wrd(R z7kmOO8abOv43zO!G2u9lj7aP$i-~=t^wEI`#f2Xh(H9#Q@l@$e$k{DgTiN)6g!(%F zyDhS+rxfHKeOPI}xF_e4o~Zg>N5}fzLT1R>n*b47Iy&k}8h{#Pke}z;;X`HOH-0&^ zvOd2Gxi3kXl2T0)i6{NQSHpE|#7_;xILF2_W)P?O>Z6LwC@vQE9v$3R0@M3xmZr-} zOnrDYzT|Dqb>gQyiLveWkiRq~d()toraPbKa&#Fs(`4Iee8eFT!W%;IIrxKt9kXgR zV6t;lui1rEem++tXG2R>0ko*LS*+v0iIekG{hriybMF!y2sunZhYg7fZ%Nun(lO zyZB1ZB$Rgo)qC>S@4Zj`Yn+aOoRd>kc{yuieTT9RR`nJ|5TlDJDe#5OA4iaXFs43Lb%cyq{=D#}7)pMp=;(5TMqt^_i++U|4D>m67WPgX{L6 zH7)F0@-Sgw@RZPN;g+`#>ejc9?x4C?o$g`er~-0qEQ!n~8y}y3fiZh1b+bRcb};0mlqD;~KYsZSqi!c8 literal 0 HcmV?d00001 diff --git a/package-lock.json b/package-lock.json index c8b34da..333fff4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,10 @@ "workspaces": [ "packages/*" ], + "dependencies": { + "playwright": "^1.59.0-alpha-1771104257000", + "playwright-core": "^1.58.2" + }, "devDependencies": { "@vitest/coverage-v8": "^4.0.18", "vitest": "^4.0.18" @@ -919,6 +923,17 @@ "assertion-error": "^2.0.1" } }, + "node_modules/@types/chrome": { + "version": "0.0.114", + "resolved": "https://registry.npmjs.org/@types/chrome/-/chrome-0.0.114.tgz", + "integrity": "sha512-i7qRr74IrxHtbnrZSKUuP5Uvd5EOKwlwJq/yp7+yTPihOXnPhNQO4Z5bqb1XTnrjdbUKEJicaVVbhcgtRijmLA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/filesystem": "*", + "@types/har-format": "*" + } + }, "node_modules/@types/deep-eql": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", @@ -933,6 +948,57 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/filesystem": { + "version": "0.0.36", + "resolved": "https://registry.npmjs.org/@types/filesystem/-/filesystem-0.0.36.tgz", + "integrity": "sha512-vPDXOZuannb9FZdxgHnqSwAG/jvdGM8Wq+6N4D/d80z+D4HWH+bItqsZaVRQykAn6WEVeEkLm2oQigyHtgb0RA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/filewriter": "*" + } + }, + "node_modules/@types/filewriter": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/@types/filewriter/-/filewriter-0.0.33.tgz", + "integrity": "sha512-xFU8ZXTw4gd358lb2jw25nxY9QAgqn2+bKKjKOYfNCzN4DKCFetK7sPtrlpg66Ywe3vWY9FNxprZawAh9wfJ3g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/har-format": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@types/har-format/-/har-format-1.2.16.tgz", + "integrity": "sha512-fluxdy7ryD3MV6h8pTfTYpy/xQzCFC7m89nOH9y94cNqJ1mDIDPut7MnRHI3F6qRmh/cT2fUjG1MLdCNb4hE9A==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "25.2.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.2.3.tgz", + "integrity": "sha512-m0jEgYlYz+mDJZ2+F4v8D1AyQb+QzsNqRuI7xg1VQX/KlKS0qT9r1Mo16yo5F/MtifXFgaofIFsdFMox2SxIbQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/@types/whatwg-mimetype": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz", + "integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.18.1", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", + "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@vitest/coverage-v8": { "version": "4.0.18", "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.0.18.tgz", @@ -1107,6 +1173,19 @@ "node": ">=18" } }, + "node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/es-module-lexer": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", @@ -1208,6 +1287,24 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/happy-dom": { + "version": "20.6.2", + "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.6.2.tgz", + "integrity": "sha512-Xk/Y0cuq9ngN/my8uvK4gKoyDl6sBKkIl8A/hJ0IabZVH7E5SJLHNE7uKRPVmSrQbhJaLIHTEcvTct4GgNtsRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": ">=20.0.0", + "@types/whatwg-mimetype": "^3.0.2", + "@types/ws": "^8.18.1", + "entities": "^7.0.1", + "whatwg-mimetype": "^3.0.0", + "ws": "^8.18.3" + }, + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", @@ -1376,12 +1473,12 @@ } }, "node_modules/playwright": { - "version": "1.59.0-alpha-2026-02-09", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.59.0-alpha-2026-02-09.tgz", - "integrity": "sha512-yyOXu0vpIfNnBG6M0JkUDkxDyvZUDieqoXMxNoNbcVV+DROrJB1oDmkgTNojkxXhpsAHwG56TH2tE/Rqju86sA==", + "version": "1.59.0-alpha-1771104257000", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.59.0-alpha-1771104257000.tgz", + "integrity": "sha512-6SCMMMJaDRsSqiKVLmb2nhtLES7iTYawTWWrQK6UdIGNzXi8lka4sLKRec3L4DnTWwddAvCuRn8035dhNiHzbg==", "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.59.0-alpha-2026-02-09" + "playwright-core": "1.59.0-alpha-1771104257000" }, "bin": { "playwright": "cli.js" @@ -1394,9 +1491,9 @@ } }, "node_modules/playwright-core": { - "version": "1.59.0-alpha-2026-02-09", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.59.0-alpha-2026-02-09.tgz", - "integrity": "sha512-O4Ugl6oq68hWeGIti4U3pNa/I7vEwn8PdzG/mZgcTkou+0IBNWAVH4WWk0+BJoufqaGBHmH0H7pVSjmlCusoYA==", + "version": "1.58.2", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.2.tgz", + "integrity": "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==", "license": "Apache-2.0", "bin": { "playwright-core": "cli.js" @@ -1409,6 +1506,18 @@ "resolved": "packages/cli", "link": true }, + "node_modules/playwright/node_modules/playwright-core": { + "version": "1.59.0-alpha-1771104257000", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.59.0-alpha-1771104257000.tgz", + "integrity": "sha512-YiXup3pnpQUCBMSIW5zx8CErwRx4K6O5Kojkw2BzJui8MazoMUDU6E3xGsb1kzFviEAE09LFQ+y1a0RhIJQ5SA==", + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/postcss": { "version": "8.5.6", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", @@ -1584,6 +1693,13 @@ "node": ">=14.0.0" } }, + "node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "dev": true, + "license": "MIT" + }, "node_modules/vite": { "version": "7.3.1", "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.1.tgz", @@ -1752,6 +1868,26 @@ } } }, + "node_modules/vitest-chrome": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/vitest-chrome/-/vitest-chrome-0.1.0.tgz", + "integrity": "sha512-Bs1uywAolbc46h2tcaETQyFMTnOHjSA85iH10Zoe8ZMEl/71nuSdxs3z+KMxVZtN88TEgWicnl5vmbDO1OhoEw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chrome": "^0.0.114" + } + }, + "node_modules/whatwg-mimetype": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz", + "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, "node_modules/why-is-node-running": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", @@ -1769,6 +1905,27 @@ "node": ">=8" } }, + "node_modules/ws": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", + "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "packages/cli": { "name": "playwright-repl", "version": "0.4.0", @@ -1787,11 +1944,42 @@ "node": ">=18.0.0" } }, + "packages/cli/node_modules/playwright": { + "version": "1.59.0-alpha-2026-02-19", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.59.0-alpha-2026-02-19.tgz", + "integrity": "sha512-dm0DERszC+UiJVrzFKHRe/rbIHBgWCIac/zT4adN66rqPAeRdmFqCM2D51cb0GWub3z2OGxdhGGcjEzUGp6ChA==", + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.59.0-alpha-2026-02-19" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "packages/cli/node_modules/playwright-core": { + "version": "1.59.0-alpha-2026-02-19", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.59.0-alpha-2026-02-19.tgz", + "integrity": "sha512-QStoDtLoeSiFhH5tKUs0O5eeTV2JHFsRNvt1HkX9muOq1L4H4IGt0PtgHgFxCxF68Z15EoGm0H8AtSay42b7bg==", + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, "packages/core": { "name": "@playwright-repl/core", "version": "0.3.0", "dependencies": { - "minimist": "^1.2.8" + "minimist": "^1.2.8", + "ws": "^8.19.0" }, "devDependencies": { "vitest": "^4.0.18" @@ -1799,7 +1987,13 @@ }, "packages/extension": { "name": "@playwright-repl/extension", - "version": "0.9.3" + "version": "1.0.0", + "devDependencies": { + "@vitest/coverage-v8": "^4.0.18", + "happy-dom": "^20.6.1", + "vitest": "^4.0.18", + "vitest-chrome": "^0.1.0" + } } } } diff --git a/package.json b/package.json index 5927175..adab242 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,9 @@ { "name": "playwright-repl", "private": true, - "workspaces": ["packages/*"], + "workspaces": [ + "packages/*" + ], "scripts": { "test": "npm test --workspaces --if-present", "test:core": "npm test -w packages/core", @@ -10,5 +12,9 @@ "devDependencies": { "@vitest/coverage-v8": "^4.0.18", "vitest": "^4.0.18" + }, + "dependencies": { + "playwright": "^1.59.0-alpha-1771104257000", + "playwright-core": "^1.58.2" } } diff --git a/packages/cli/bin/playwright-repl.mjs b/packages/cli/bin/playwright-repl.mjs index 4ebf817..355b420 100644 --- a/packages/cli/bin/playwright-repl.mjs +++ b/packages/cli/bin/playwright-repl.mjs @@ -15,7 +15,7 @@ import { startRepl } from '../src/repl.mjs'; const args = minimist(process.argv.slice(2), { boolean: ['headed', 'persistent', 'extension', 'help', 'step', 'silent'], - string: ['session', 'browser', 'profile', 'config', 'replay', 'record', 'connect'], + string: ['session', 'browser', 'profile', 'config', 'replay', 'record', 'connect', 'port'], alias: { s: 'session', h: 'help', b: 'browser', q: 'silent' }, default: { session: 'default' }, }); @@ -38,6 +38,8 @@ Options: --persistent Use persistent browser profile --profile Persistent profile directory --connect [port] Connect to existing Chrome via CDP (default: 9222) + --extension Start WebSocket server for Chrome extension + --port Extension server port (default: 3000) --config Path to config file --replay Replay a .pw session file --record Start REPL with recording to file @@ -62,6 +64,8 @@ Examples: playwright-repl --headed # start with visible browser playwright-repl --connect # connect to Chrome on port 9222 playwright-repl --connect 9333 # connect to Chrome on custom port + playwright-repl --extension # start extension server on port 3000 + playwright-repl --extension --port 4000 # custom extension port playwright-repl --replay login.pw # replay a session playwright-repl --replay login.pw --step # step through replay echo "open https://example.com" | playwright-repl # pipe commands @@ -76,6 +80,8 @@ startRepl({ persistent: args.persistent, profile: args.profile, connect: args.connect, + extension: args.extension, + port: args.port ? parseInt(args.port, 10) : undefined, config: args.config, replay: args.replay, record: args.record, diff --git a/packages/cli/src/repl.mjs b/packages/cli/src/repl.mjs index e3b7fab..b696f4c 100644 --- a/packages/cli/src/repl.mjs +++ b/packages/cli/src/repl.mjs @@ -28,7 +28,7 @@ export function filterResponse(text) { const content = section.substring(newline + 1).trim(); if (title === 'Error') kept.push(`${c.red}${content}${c.reset}`); - else if (title === 'Result' || title === 'Modal state') + else if (title === 'Result' || title === 'Modal state' || title === 'Page' || title === 'Snapshot') kept.push(content); } return kept.length > 0 ? kept.join('\n') : null; @@ -284,8 +284,8 @@ export async function processLine(ctx, line) { const result = await ctx.conn.run(args); const elapsed = (performance.now() - startTime).toFixed(0); if (result?.text) { - const output = filterResponse(result.text); - if (output) console.log(output); + const filtered = filterResponse(result.text); + if (filtered !== null) console.log(filtered); } ctx.commandCount++; ctx.session.record(line); @@ -504,14 +504,23 @@ export async function startRepl(opts = {}) { const log = (...args) => { if (!silent) console.log(...args); }; log(`${c.bold}${c.magenta}🎭 Playwright REPL${c.reset} ${c.dim}v${replVersion}${c.reset}`); - log(`${c.dim}Type .help for commands${c.reset}\n`); // ─── Start engine ──────────────────────────────────────────────── + if (opts.extension) { + log(`${c.dim}Extension mode: starting MCP Bridge (will open Chrome)...${c.reset}`); + log(''); + } else { + log(`${c.dim}Type .help for commands${c.reset}\n`); + } + const conn = new Engine(); try { await conn.start(opts); - log(`${c.green}✓${c.reset} Browser ready\n`); + if (opts.extension) + log(`${c.green}✓${c.reset} Extension mode ready (MCP Bridge connected)\n`); + else + log(`${c.green}✓${c.reset} Browser ready\n`); } catch (err) { console.error(`${c.red}✗${c.reset} Failed to start: ${err.message}`); process.exit(1); diff --git a/packages/cli/test/repl-helpers.test.mjs b/packages/cli/test/repl-helpers.test.mjs index 14fc248..f41cd67 100644 --- a/packages/cli/test/repl-helpers.test.mjs +++ b/packages/cli/test/repl-helpers.test.mjs @@ -84,12 +84,12 @@ describe('text locator buildRunCode output', () => { describe('filterResponse', () => { it('extracts Result section', () => { const text = '### Page\nhttp://example.com\n### Result\nClicked element'; - expect(filterResponse(text)).toBe('Clicked element'); + expect(filterResponse(text)).toBe('http://example.com\nClicked element'); }); it('extracts Error section in red', () => { const text = '### Page\nhttp://example.com\n### Error\nElement not found'; - expect(filterResponse(text)).toBe(`${c.red}Element not found${c.reset}`); + expect(filterResponse(text)).toBe(`http://example.com\n${c.red}Element not found${c.reset}`); }); it('extracts Modal state section', () => { @@ -97,14 +97,14 @@ describe('filterResponse', () => { expect(filterResponse(text)).toBe('[Alert] Are you sure?'); }); - it('strips Page and Snapshot sections', () => { + it('includes Page and Snapshot sections', () => { const text = '### Page\nhttp://example.com\n### Snapshot\n- element tree\n### Result\nDone'; - expect(filterResponse(text)).toBe('Done'); + expect(filterResponse(text)).toBe('http://example.com\n- element tree\nDone'); }); - it('returns null when no matching sections', () => { + it('returns Page and Snapshot content when no Result section', () => { const text = '### Page\nhttp://example.com\n### Snapshot\n- tree'; - expect(filterResponse(text)).toBeNull(); + expect(filterResponse(text)).toBe('http://example.com\n- tree'); }); it('returns null for text with no sections', () => { diff --git a/packages/core/package.json b/packages/core/package.json index 4bd4a5c..c04ce67 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -11,7 +11,8 @@ "test": "vitest run" }, "dependencies": { - "minimist": "^1.2.8" + "minimist": "^1.2.8", + "ws": "^8.19.0" }, "devDependencies": { "vitest": "^4.0.18" diff --git a/packages/core/src/engine.mjs b/packages/core/src/engine.mjs index 1135c84..617d024 100644 --- a/packages/core/src/engine.mjs +++ b/packages/core/src/engine.mjs @@ -7,12 +7,13 @@ * Three connection modes: * - launch: new browser via Playwright (default) * - connect: existing Chrome via CDP port (--connect [port]) - * - extension: Chrome extension CDP relay (--extension) + * - extension: DevTools extension CDP relay (--extension) */ import { createRequire } from 'node:module'; import path from 'node:path'; import url from 'node:url'; +import { replVersion } from './resolve.mjs'; // ─── Lazy-loaded Playwright dependencies ──────────────────────────────────── @@ -25,11 +26,12 @@ function loadDeps() { const pwDir = path.dirname(require.resolve('playwright/package.json')); const pwReq = (sub) => require(path.join(pwDir, sub)); _deps = { - BrowserServerBackend: pwReq('lib/mcp/browser/browserServerBackend.js').BrowserServerBackend, - contextFactory: pwReq('lib/mcp/browser/browserContextFactory.js').contextFactory, - resolveConfig: pwReq('lib/mcp/browser/config.js').resolveConfig, - commands: pwReq('lib/cli/daemon/commands.js').commands, - parseCommand: pwReq('lib/cli/daemon/command.js').parseCommand, + BrowserServerBackend: pwReq('lib/mcp/browser/browserServerBackend.js').BrowserServerBackend, + contextFactory: pwReq('lib/mcp/browser/browserContextFactory.js').contextFactory, + ExtensionContextFactory: pwReq('lib/mcp/extension/extensionContextFactory.js').ExtensionContextFactory, + resolveConfig: pwReq('lib/mcp/browser/config.js').resolveConfig, + commands: pwReq('lib/cli/daemon/commands.js').commands, + parseCommand: pwReq('lib/cli/daemon/command.js').parseCommand, }; return _deps; } @@ -58,32 +60,61 @@ export class Engine { async start(opts = {}) { const deps = this._deps || loadDeps(); const config = await this._buildConfig(opts, deps); - const factory = deps.contextFactory(config); const cwd = url.pathToFileURL(process.cwd()).href; const clientInfo = { name: 'playwright-repl', - version: '0.4.0', + version: replVersion, roots: [{ uri: cwd, name: 'cwd' }], timestamp: Date.now(), }; - const { browserContext, close } = await factory.createContext(clientInfo, new AbortController().signal, {}); - this._close = close; - - // Wrap in an "existing context" factory so BrowserServerBackend reuses it. - const existingContextFactory = { - createContext: () => Promise.resolve({ browserContext, close }), - }; - - this._backend = new deps.BrowserServerBackend(config, existingContextFactory, { allTools: true }); - await this._backend.initialize?.(clientInfo); - this._connected = true; - - // If the browser closes externally, update our state. - browserContext.on('close', () => { - this._connected = false; - }); + // Choose context factory based on mode. + let factory; + if (opts.extension) { + // Phase 1: ExtensionContextFactory (MCP Bridge) handles the CDP relay. + // CommandServer only provides HTTP /run for panel commands. + const { CommandServer } = await import('./extension-server.mjs'); + this._commandServer = new CommandServer(this); + await this._commandServer.start(opts.port || 3000); + + // ExtensionContextFactory spawns Chrome with MCP Bridge extension, + // creates CDPRelayServer, and connects Playwright through it. + const extFactory = new deps.ExtensionContextFactory('chrome', undefined, undefined); + const { browserContext, close } = await extFactory.createContext( + clientInfo, new AbortController().signal, {}, + ); + this._close = close; + + const existingContextFactory = { + createContext: () => Promise.resolve({ browserContext, close }), + }; + this._backend = new deps.BrowserServerBackend(config, existingContextFactory, { allTools: true }); + await this._backend.initialize?.(clientInfo); + this._connected = true; + + browserContext.on('close', () => { + this._connected = false; + }); + } else { + // Launch/connect mode: eagerly create context for immediate feedback. + factory = deps.contextFactory(config); + const { browserContext, close } = await factory.createContext( + clientInfo, new AbortController().signal, {}, + ); + this._close = close; + + const existingContextFactory = { + createContext: () => Promise.resolve({ browserContext, close }), + }; + this._backend = new deps.BrowserServerBackend(config, existingContextFactory, { allTools: true }); + await this._backend.initialize?.(clientInfo); + this._connected = true; + + browserContext.on('close', () => { + this._connected = false; + }); + } } /** @@ -116,6 +147,10 @@ export class Engine { */ async close() { this._connected = false; + if (this._commandServer) { + await this._commandServer.close(); + this._commandServer = null; + } if (this._backend) { this._backend.serverClosed(); this._backend = null; @@ -144,7 +179,7 @@ export class Engine { server: {}, network: {}, timeouts: { - action: 5000, + action: opts.extension ? 30000 : 5000, navigation: 60000, }, }; @@ -171,7 +206,7 @@ export class Engine { // Persistent profile if (opts.persistent || opts.profile) { config.browser.userDataDir = opts.profile || undefined; - } else { + } else if (!opts.extension) { config.browser.isolated = true; } diff --git a/packages/core/src/extension-server.mjs b/packages/core/src/extension-server.mjs new file mode 100644 index 0000000..22c096a --- /dev/null +++ b/packages/core/src/extension-server.mjs @@ -0,0 +1,154 @@ +/** + * CommandServer — HTTP server for the DevTools panel extension. + * + * Provides the POST /run endpoint so the panel can send commands + * to the engine. The CDP relay is handled by Playwright's + * ExtensionContextFactory + MCP Bridge extension. + * + * HTTP endpoints: + * POST /run { "raw": "click e5" } → { "text": "Clicked", "isError": false } + */ + +import { createServer } from 'node:http'; +import { parseInput } from './parser.mjs'; +import { + buildRunCode, verifyText, verifyElement, verifyValue, verifyList, + actionByText, fillByText, selectByText, checkByText, uncheckByText, +} from './page-scripts.mjs'; + +// ─── CommandServer ────────────────────────────────────────────────────────── + +export class CommandServer { + constructor(engine) { + this._engine = engine; + this._server = null; + this._port = null; + } + + get port() { return this._port; } + + async start(port = 3000) { + this._port = port; + this._server = createServer((req, res) => this._handleHttp(req, res)); + + return new Promise((resolve, reject) => { + this._server.listen(port, () => resolve()); + this._server.on('error', reject); + }); + } + + async close() { + if (this._server) { + await new Promise((resolve) => this._server.close(resolve)); + this._server = null; + } + } + + // ─── HTTP handler ─────────────────────────────────────────────────────── + + async _handleHttp(req, res) { + // CORS — allow chrome-extension:// origins + res.setHeader('Access-Control-Allow-Origin', '*'); + res.setHeader('Access-Control-Allow-Methods', 'POST, GET'); + res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); + + if (req.method === 'OPTIONS') { + res.writeHead(204); + res.end(); + return; + } + + // Panel command endpoint + if (req.method === 'POST' && req.url === '/run') { + try { + const body = await readBody(req); + const { raw } = JSON.parse(body); + let args = parseInput(raw); + if (!args) { + res.writeHead(400, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ text: `Unknown command: ${raw}`, isError: true })); + return; + } + args = resolveArgs(args); + const result = await this._engine.run(args); + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(result)); + } catch (e) { + res.writeHead(500, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ text: e.message, isError: true })); + } + return; + } + + res.writeHead(404); + res.end('Not found'); + } +} + +// ─── REPL-level argument transformations ──────────────────────────────────── + +/** + * Apply the same transformations the CLI REPL does before engine.run(): + * - Verify commands → run-code with page scripts + * - Text locators → run-code with actionByText/fillByText/etc. + * - Auto-wrap run-code body with async (page) => { ... } + */ +function resolveArgs(args) { + const cmdName = args._[0]; + + // ── Verify commands → run-code translation ────────────────── + const verifyFns = { + 'verify-text': verifyText, + 'verify-element': verifyElement, + 'verify-value': verifyValue, + 'verify-list': verifyList, + }; + if (verifyFns[cmdName]) { + const pos = args._.slice(1); + const fn = verifyFns[cmdName]; + let translated = null; + if (cmdName === 'verify-text') { + const text = pos.join(' '); + if (text) translated = buildRunCode(fn, text); + } else if (pos[0] && pos.length >= 2) { + const rest = cmdName === 'verify-list' ? pos.slice(1) : pos.slice(1).join(' '); + translated = buildRunCode(fn, pos[0], rest); + } + if (translated) args = translated; + } + + // ── Auto-resolve text to native Playwright locator ───────── + const textFns = { + click: actionByText, dblclick: actionByText, hover: actionByText, + fill: fillByText, select: selectByText, check: checkByText, uncheck: uncheckByText, + }; + if (textFns[cmdName] && args._[1] && !/^e\d+$/.test(args._[1])) { + const textArg = args._[1]; + const extraArgs = args._.slice(2); + const fn = textFns[cmdName]; + if (fn === actionByText) args = buildRunCode(fn, textArg, cmdName); + else if (cmdName === 'fill' || cmdName === 'select') args = buildRunCode(fn, textArg, extraArgs[0] || ''); + else args = buildRunCode(fn, textArg); + } + + // ── Auto-wrap run-code body with async (page) => { ... } ── + if (cmdName === 'run-code' && args._[1] && !args._[1].startsWith('async')) { + const STMT = /^(await|return|const|let|var|for|if|while|throw|try)\b/; + const body = !args._[1].includes(';') && !STMT.test(args._[1]) + ? `return await ${args._[1]}` + : args._[1]; + args = { _: ['run-code', `async (page) => { ${body} }`] }; + } + + return args; +} + +// ─── Helpers ──────────────────────────────────────────────────────────────── + +function readBody(req) { + return new Promise((resolve) => { + let data = ''; + req.on('data', (chunk) => data += chunk); + req.on('end', () => resolve(data)); + }); +} diff --git a/packages/core/src/index.mjs b/packages/core/src/index.mjs index c0854a9..3c3fa52 100644 --- a/packages/core/src/index.mjs +++ b/packages/core/src/index.mjs @@ -11,3 +11,4 @@ export { actionByText, fillByText, selectByText, checkByText, uncheckByText, } from './page-scripts.mjs'; export { Engine } from './engine.mjs'; +export { CommandServer } from './extension-server.mjs'; diff --git a/packages/core/src/resolve.mjs b/packages/core/src/resolve.mjs index c6d2edf..a2735f9 100644 --- a/packages/core/src/resolve.mjs +++ b/packages/core/src/resolve.mjs @@ -3,7 +3,6 @@ * No @playwright/cli — we start the daemon ourselves via daemon-launcher.cjs. */ -import fs from 'node:fs'; import { fileURLToPath } from 'node:url'; import { createRequire } from 'node:module'; @@ -14,8 +13,7 @@ const require = createRequire(import.meta.url); export const minimist = require('minimist'); const pkgUrl = new URL('../package.json', import.meta.url); -const pkg = JSON.parse(fs.readFileSync(pkgUrl, 'utf-8')); -export const replVersion = pkg.version; +export const replVersion = require('../../cli/package.json').version; // Must match what daemon-launcher.cjs computes via require.resolve('../package.json') export const packageLocation = fileURLToPath(pkgUrl); diff --git a/packages/core/test/extension-server.test.mjs b/packages/core/test/extension-server.test.mjs new file mode 100644 index 0000000..bbff7f8 --- /dev/null +++ b/packages/core/test/extension-server.test.mjs @@ -0,0 +1,359 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { WebSocket } from 'ws'; +import { CommandServer } from '../src/extension-server.mjs'; + +// ─── Helper: create a mock engine ───────────────────────────────────────────── + +function createMockEngine() { + return { + run: vi.fn().mockResolvedValue({ text: 'Clicked', isError: false }), + connected: true, + }; +} + +// ─── Tests ──────────────────────────────────────────────────────────────────── + +describe('CommandServer', () => { + let server; + let engine; + const TEST_PORT = 13579; + + beforeEach(() => { + engine = createMockEngine(); + server = new CommandServer(engine); + }); + + afterEach(async () => { + await server.close(); + }); + + describe('lifecycle', () => { + it('starts and listens on the given port', async () => { + await server.start(TEST_PORT); + expect(server.port).toBe(TEST_PORT); + }); + + it('close() is idempotent', async () => { + await server.start(TEST_PORT); + await server.close(); + await server.close(); // Should not throw + }); + + it('close() works when server was never started', async () => { + await server.close(); // Should not throw + }); + }); + + describe('POST /run', () => { + it('runs command through engine and returns result', async () => { + await server.start(TEST_PORT); + + const res = await fetch(`http://localhost:${TEST_PORT}/run`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ raw: 'click e5' }), + }); + + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.text).toBe('Clicked'); + expect(data.isError).toBe(false); + expect(engine.run).toHaveBeenCalled(); + }); + + it('returns 400 for unknown commands', async () => { + await server.start(TEST_PORT); + + const res = await fetch(`http://localhost:${TEST_PORT}/run`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ raw: '' }), + }); + + expect(res.status).toBe(400); + const data = await res.json(); + expect(data.isError).toBe(true); + }); + + it('returns 500 when engine throws', async () => { + engine.run.mockRejectedValueOnce(new Error('Engine exploded')); + await server.start(TEST_PORT); + + const res = await fetch(`http://localhost:${TEST_PORT}/run`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ raw: 'click e5' }), + }); + + expect(res.status).toBe(500); + const data = await res.json(); + expect(data.isError).toBe(true); + expect(data.text).toContain('Engine exploded'); + }); + }); + + describe('CORS', () => { + it('responds to OPTIONS preflight with CORS headers', async () => { + await server.start(TEST_PORT); + + const res = await fetch(`http://localhost:${TEST_PORT}/run`, { + method: 'OPTIONS', + }); + + expect(res.status).toBe(204); + expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*'); + expect(res.headers.get('Access-Control-Allow-Methods')).toBe('POST, GET'); + }); + + it('includes CORS headers on POST responses', async () => { + await server.start(TEST_PORT); + + const res = await fetch(`http://localhost:${TEST_PORT}/run`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ raw: 'click e5' }), + }); + + expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*'); + }); + }); + + describe('GET /json/version', () => { + it('returns webSocketDebuggerUrl for CDP discovery', async () => { + await server.start(TEST_PORT); + + const res = await fetch(`http://localhost:${TEST_PORT}/json/version`); + expect(res.status).toBe(200); + + const data = await res.json(); + expect(data.webSocketDebuggerUrl).toContain(`ws://127.0.0.1:${TEST_PORT}/devtools/browser/`); + expect(data['Protocol-Version']).toBe('1.3'); + }); + + it('also works with trailing slash', async () => { + await server.start(TEST_PORT); + + const res = await fetch(`http://localhost:${TEST_PORT}/json/version/`); + expect(res.status).toBe(200); + + const data = await res.json(); + expect(data.webSocketDebuggerUrl).toBeDefined(); + }); + }); + + describe('WebSocket /extension', () => { + it('accepts extension connection and resolves waitForExtension', async () => { + await server.start(TEST_PORT); + + const waitPromise = server.waitForExtension(); + const ws = new WebSocket(`ws://127.0.0.1:${TEST_PORT}/extension`); + await new Promise((resolve) => ws.on('open', resolve)); + + await waitPromise; // Should resolve when extension connects + ws.close(); + }); + + it('rejects second extension connection', async () => { + await server.start(TEST_PORT); + + const ws1 = new WebSocket(`ws://127.0.0.1:${TEST_PORT}/extension`); + await new Promise((resolve) => ws1.on('open', resolve)); + + const ws2 = new WebSocket(`ws://127.0.0.1:${TEST_PORT}/extension`); + const closeCode = await new Promise((resolve) => ws2.on('close', resolve)); + expect(closeCode).toBe(1000); + + ws1.close(); + }); + + it('waitForExtension resolves immediately if already connected', async () => { + await server.start(TEST_PORT); + + const ws = new WebSocket(`ws://127.0.0.1:${TEST_PORT}/extension`); + await new Promise((resolve) => ws.on('open', resolve)); + + await server.waitForExtension(); // Should resolve immediately + ws.close(); + }); + }); + + describe('CDP relay', () => { + let extWs; + let pwWs; + let pwMessages; // Collected messages from Playwright WebSocket + let extMessages; // Collected messages from Extension WebSocket + + async function connectExtension() { + extWs = new WebSocket(`ws://127.0.0.1:${TEST_PORT}/extension`); + extMessages = []; + await new Promise((resolve) => extWs.on('open', resolve)); + extWs.on('message', (data) => extMessages.push(JSON.parse(data.toString()))); + } + + async function connectPlaywright() { + const res = await fetch(`http://localhost:${TEST_PORT}/json/version`); + const { webSocketDebuggerUrl } = await res.json(); + pwWs = new WebSocket(webSocketDebuggerUrl); + pwMessages = []; + await new Promise((resolve) => pwWs.on('open', resolve)); + pwWs.on('message', (data) => pwMessages.push(JSON.parse(data.toString()))); + } + + function sendFromPlaywright(msg) { + pwWs.send(JSON.stringify(msg)); + } + + /** Wait until pw message array has at least `count` entries. */ + async function waitForPwMessages(count) { + while (pwMessages.length < count) { + await new Promise((r) => setTimeout(r, 20)); + } + } + + /** Wait until ext message array has at least `count` entries. */ + async function waitForExtMessages(count) { + while (extMessages.length < count) { + await new Promise((r) => setTimeout(r, 20)); + } + } + + /** Auto-attach helper: sends Target.setAutoAttach, responds with target info, drains responses. */ + async function doAutoAttach() { + const baseCount = extMessages.length; + sendFromPlaywright({ id: 1, method: 'Target.setAutoAttach', params: {} }); + await waitForExtMessages(baseCount + 1); + const attachMsg = extMessages[baseCount]; + expect(attachMsg.method).toBe('attachToTab'); + + const pwBaseCount = pwMessages.length; + extWs.send(JSON.stringify({ + id: attachMsg.id, + result: { targetInfo: { targetId: 'tab-1', type: 'page', title: 'Test', url: 'http://test.com' } }, + })); + await waitForPwMessages(pwBaseCount + 2); // event + response + } + + afterEach(() => { + extWs?.close(); + pwWs?.close(); + }); + + it('handles Browser.getVersion locally', async () => { + await server.start(TEST_PORT); + await connectExtension(); + await connectPlaywright(); + + sendFromPlaywright({ id: 1, method: 'Browser.getVersion', params: {} }); + await waitForPwMessages(1); + + expect(pwMessages[0].id).toBe(1); + expect(pwMessages[0].result.protocolVersion).toBe('1.3'); + expect(pwMessages[0].result.product).toContain('Chrome'); + }); + + it('handles Browser.setDownloadBehavior locally', async () => { + await server.start(TEST_PORT); + await connectExtension(); + await connectPlaywright(); + + sendFromPlaywright({ id: 2, method: 'Browser.setDownloadBehavior', params: {} }); + await waitForPwMessages(1); + + expect(pwMessages[0].id).toBe(2); + expect(pwMessages[0].result).toEqual({}); + }); + + it('handles Target.setAutoAttach by sending attachToTab to extension', async () => { + await server.start(TEST_PORT); + await connectExtension(); + await connectPlaywright(); + + await doAutoAttach(); + + const attachedEvent = pwMessages.find(m => m.method === 'Target.attachedToTarget'); + const autoAttachResponse = pwMessages.find(m => m.id === 1); + + expect(autoAttachResponse.result).toEqual({}); + expect(attachedEvent.params.targetInfo.targetId).toBe('tab-1'); + expect(attachedEvent.params.sessionId).toMatch(/^pw-tab-/); + }); + + it('forwards CDP commands to extension via forwardCDPCommand', async () => { + await server.start(TEST_PORT); + await connectExtension(); + await connectPlaywright(); + + await doAutoAttach(); + + // Now send a CDP command with the session ID + const extBaseCount = extMessages.length; + sendFromPlaywright({ + id: 10, + sessionId: 'pw-tab-1', + method: 'Page.navigate', + params: { url: 'http://example.com' }, + }); + await waitForExtMessages(extBaseCount + 1); + + const fwdMsg = extMessages[extBaseCount]; + expect(fwdMsg.method).toBe('forwardCDPCommand'); + expect(fwdMsg.params.method).toBe('Page.navigate'); + // Session ID should be stripped (maps to main tab) + expect(fwdMsg.params.sessionId).toBeUndefined(); + + // Extension responds + const pwBaseCount = pwMessages.length; + extWs.send(JSON.stringify({ id: fwdMsg.id, result: { frameId: 'f1' } })); + await waitForPwMessages(pwBaseCount + 1); + + const response = pwMessages[pwBaseCount]; + expect(response.id).toBe(10); + expect(response.result.frameId).toBe('f1'); + }); + + it('forwards CDP events from extension to Playwright', async () => { + await server.start(TEST_PORT); + await connectExtension(); + await connectPlaywright(); + + await doAutoAttach(); + + // Send CDP event from extension + const pwBaseCount = pwMessages.length; + extWs.send(JSON.stringify({ + method: 'forwardCDPEvent', + params: { method: 'Page.loadEventFired', params: { timestamp: 123 } }, + })); + await waitForPwMessages(pwBaseCount + 1); + + const event = pwMessages[pwBaseCount]; + expect(event.method).toBe('Page.loadEventFired'); + expect(event.params.timestamp).toBe(123); + expect(event.sessionId).toMatch(/^pw-tab-/); + }); + }); + + describe('other routes', () => { + it('returns 404 for unknown paths', async () => { + await server.start(TEST_PORT); + + const res = await fetch(`http://localhost:${TEST_PORT}/unknown`); + expect(res.status).toBe(404); + }); + + it('returns 404 for GET /run', async () => { + await server.start(TEST_PORT); + + const res = await fetch(`http://localhost:${TEST_PORT}/run`); + expect(res.status).toBe(404); + }); + + it('rejects WebSocket on invalid path', async () => { + await server.start(TEST_PORT); + + const ws = new WebSocket(`ws://127.0.0.1:${TEST_PORT}/invalid`); + const code = await new Promise((resolve) => ws.on('close', resolve)); + expect(code).toBe(4004); + }); + }); +}); diff --git a/packages/extension/background.js b/packages/extension/background.js new file mode 100644 index 0000000..ceb01fd --- /dev/null +++ b/packages/extension/background.js @@ -0,0 +1,184 @@ +/** + * background.js — Service worker for the Playwright REPL DevTools extension. + * + * Three roles: + * 1. CDP bridge: WebSocket connection to CommandServer, bridging chrome.debugger + * so Playwright can control the inspected tab via connectOverCDP + * 2. Command proxy: forward panel commands to CommandServer via HTTP POST /run + * 3. Recording: inject recorder.js, listen for __pw: events (extension-side only) + */ + +import { RelayConnection } from './lib/relayConnection.js'; + +// ─── State ─────────────────────────────────────────────────────────────────── + +let serverPort = 3000; +let panelPorts = {}; // tabId → port (for sending recorded commands to panel) +let recording = {}; // tabId → boolean +let activeRelay = null; // RelayConnection instance + +// ─── Bridge connection ────────────────────────────────────────────────────── + +function connectBridge(tabId) { + if (activeRelay) return; + + try { + const ws = new WebSocket(`ws://127.0.0.1:${serverPort}/extension`); + ws.onopen = () => { + activeRelay = new RelayConnection(ws, tabId); + activeRelay.onclose = () => { activeRelay = null; }; + console.log('[bridge] Connected to server, tabId:', tabId); + }; + ws.onerror = () => { + // Server not running yet, will retry when panel reconnects + }; + ws.onclose = () => { + if (activeRelay) return; // RelayConnection handles its own cleanup + // Auto-reconnect after delay if no active relay + setTimeout(() => connectBridge(tabId), 2000); + }; + } catch (e) { + // WebSocket constructor failed + } +} + +// ─── Panel command handling ────────────────────────────────────────────────── + +chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { + if (message.type === 'pw-command') { + handlePanelCommand(message.raw).then(sendResponse); + return true; + } + + if (message.type === 'pw-record-start') { + startRecording(message.tabId).then(sendResponse); + return true; + } + + if (message.type === 'pw-record-stop') { + stopRecording(message.tabId).then(sendResponse); + return true; + } +}); + +async function handlePanelCommand(raw) { + try { + const res = await fetch(`http://127.0.0.1:${serverPort}/run`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ raw }), + }); + return await res.json(); + } catch (e) { + return { text: 'Not connected to server. Run: playwright-repl --extension', isError: true }; + } +} + +// ─── Recording ─────────────────────────────────────────────────────────────── + +async function startRecording(tabId) { + try { + await ensureAttached(tabId); + await chrome.debugger.sendCommand({ tabId }, 'Runtime.enable'); + const recorderCode = await fetch(chrome.runtime.getURL('content/recorder.js')).then(r => r.text()); + await chrome.debugger.sendCommand({ tabId }, 'Page.enable'); + await chrome.debugger.sendCommand({ tabId }, 'Page.addScriptToEvaluateOnNewDocument', { + source: recorderCode, + }); + await chrome.debugger.sendCommand({ tabId }, 'Runtime.evaluate', { + expression: recorderCode, + returnByValue: false, + }); + recording[tabId] = true; + return { success: true }; + } catch (e) { + return { success: false, error: e.message }; + } +} + +async function stopRecording(tabId) { + recording[tabId] = false; + try { + await chrome.debugger.sendCommand({ tabId }, 'Runtime.evaluate', { + expression: 'window.__pwRecorderCleanup && window.__pwRecorderCleanup()', + returnByValue: false, + }); + } catch (e) { + // Page might have navigated + } + return { success: true }; +} + +// ─── Debugger attach/detach (for recording only) ──────────────────────────── + +let recordingAttachedTabId = null; + +async function ensureAttached(tabId) { + if (recordingAttachedTabId === tabId) return; + if (recordingAttachedTabId) { + try { await chrome.debugger.detach({ tabId: recordingAttachedTabId }); } catch (e) {} + } + await chrome.debugger.attach({ tabId }, '1.3'); + recordingAttachedTabId = tabId; +} + +chrome.debugger.onDetach.addListener((source) => { + if (source.tabId === recordingAttachedTabId) { + recordingAttachedTabId = null; + recording[source.tabId] = false; + } +}); + +// ─── CDP event forwarding (for recording only) ───────────────────────────── + +chrome.debugger.onEvent.addListener((source, method, params) => { + if (source.tabId !== recordingAttachedTabId) return; + if (method === 'Runtime.consoleAPICalled' && params?.type === 'debug') { + const text = params.args?.[0]?.value || ''; + if (text.startsWith('__pw:')) { + const command = text.slice(5); + const port = panelPorts[recordingAttachedTabId]; + if (port) port.postMessage({ type: 'pw-recorded-command', command }); + } + } +}); + +// ─── Panel port management ────────────────────────────────────────────────── + +chrome.runtime.onConnect.addListener((port) => { + if (!port.name.startsWith('pw-panel-')) return; + const tabId = parseInt(port.name.replace('pw-panel-', ''), 10); + panelPorts[tabId] = port; + + // When a panel connects, start the CDP bridge for this tab + connectBridge(tabId); + + port.onDisconnect.addListener(() => { + delete panelPorts[tabId]; + }); +}); + +// ─── Exports (for testing) ────────────────────────────────────────────────── + +export { + handlePanelCommand, + startRecording, + stopRecording, + ensureAttached, + connectBridge, +}; + +export function _getState() { + return { serverPort, panelPorts, recording, activeRelay, recordingAttachedTabId }; +} + +export function _resetState() { + panelPorts = {}; + recording = {}; + activeRelay = null; + recordingAttachedTabId = null; +} + +export function _setActiveRelay(relay) { + activeRelay = relay; +} diff --git a/packages/extension/content/recorder.js b/packages/extension/content/recorder.js new file mode 100644 index 0000000..90eada7 --- /dev/null +++ b/packages/extension/content/recorder.js @@ -0,0 +1,187 @@ +// Content recorder — injected into the inspected page via CDP. +// Captures user interactions and sends .pw commands back via console.debug. + +(() => { + if (window.__pwRecorderActive) return; + window.__pwRecorderActive = true; + + function getLocator(el) { + const ariaLabel = el.getAttribute && el.getAttribute("aria-label"); + if (ariaLabel) return quote(ariaLabel); + + if (el.id) { + const label = document.querySelector('label[for="' + CSS.escape(el.id) + '"]'); + if (label && label.textContent.trim()) return quote(label.textContent.trim()); + } + const parentLabel = el.closest && el.closest("label"); + if (parentLabel && parentLabel.textContent.trim()) { + return quote(parentLabel.textContent.trim()); + } + + if (el.placeholder) return quote(el.placeholder); + + const text = el.textContent ? el.textContent.trim() : ""; + if (text && text.length < 80 && el.children.length === 0) return quote(text); + + if ((el.tagName === "BUTTON" || el.tagName === "A") && text && text.length < 80) { + return quote(text); + } + + if (el.title) return quote(el.title); + + const tag = el.tagName ? el.tagName.toLowerCase() : "unknown"; + return quote(tag); + } + + // Get the primary text of a container (e.g., a list item's label) + function getItemContext(el) { + const item = el.closest && el.closest("li, tr, [role=listitem], [role=row], article"); + if (!item) return null; + // Look for a label, heading, or primary text element + const primary = item.querySelector("label, h1, h2, h3, h4, [class*=title], [class*=text], p, span"); + if (primary && primary !== el && primary.textContent.trim()) { + const t = primary.textContent.trim(); + if (t.length < 80) return t; + } + return null; + } + + function quote(s) { + return '"' + s.replace(/"/g, '\\"') + '"'; + } + + function send(command) { + console.debug("__pw:" + command); + } + + let fillTimer = null; + let fillTarget = null; + let fillValue = ""; + + function flushFill() { + if (fillTarget && fillValue) { + const locator = getLocator(fillTarget); + send('fill ' + locator + ' "' + fillValue.replace(/"/g, '\\"') + '"'); + } + fillTimer = null; + fillTarget = null; + fillValue = ""; + } + + // Elements that are non-interactive containers — skip recording clicks on these + var skipTags = new Set(["HTML", "BODY", "MAIN", "FOOTER", "HEADER", "NAV", "SECTION", "ARTICLE", "DIV", "UL", "OL", "FORM", "FIELDSET", "TABLE", "TBODY", "THEAD", "TR"]); + + function findCheckbox(el) { + // Check if el itself is a checkbox + if (el.tagName === "INPUT" && el.type === "checkbox") return el; + // Check if clicking a label that toggles a checkbox + if (el.tagName === "LABEL") { + var input = el.querySelector('input[type="checkbox"]'); + if (input) return input; + if (el.htmlFor) { + var target = document.getElementById(el.htmlFor); + if (target && target.type === "checkbox") return target; + } + } + // Check only the immediate parent label (not li/div which are too broad) + var parentLabel = el.closest("label"); + if (parentLabel) { + var cb = parentLabel.querySelector('input[type="checkbox"]'); + if (cb) return cb; + } + return null; + } + + function handleClick(e) { + try { + if (fillTimer) { clearTimeout(fillTimer); flushFill(); } + var el = e.target; + if (!el || !el.tagName) return; + + // Skip text inputs and textareas + if ((el.tagName === "INPUT" && el.type !== "checkbox" && el.type !== "radio") || el.tagName === "TEXTAREA") return; + + // Skip clicks on non-interactive container elements + if (skipTags.has(el.tagName) && !el.getAttribute("role") && !el.getAttribute("onclick")) return; + + // Check for checkbox (direct or via label/parent) + var checkbox = findCheckbox(el); + if (checkbox) { + var cbLabel = getItemContext(checkbox) || ""; + if (cbLabel) { + send(checkbox.checked ? 'check "' + cbLabel + '"' : 'uncheck "' + cbLabel + '"'); + } else { + var loc = getLocator(checkbox); + send(checkbox.checked ? 'check ' + loc : 'uncheck ' + loc); + } + return; + } + + var locator = getLocator(el); + // Detect action buttons (Delete, Remove, Edit, close icons, etc.) + // by text content, class name, or aria-label + var actionWords = new Set(["delete", "remove", "edit", "close", "destroy", "\u00d7", "\u2715", "\u2716", "\u2717", "\u2718", "x"]); + var elText = (el.textContent || "").trim().toLowerCase(); + var elClass = (el.className || "").toLowerCase(); + var elAriaLabel = (el.getAttribute && el.getAttribute("aria-label") || "").toLowerCase(); + var isAction = actionWords.has(elText) + || [...actionWords].some(function(w) { return elClass.includes(w); }) + || [...actionWords].some(function(w) { return elAriaLabel.includes(w); }) + || (el.tagName === "BUTTON" && !elText && el.closest && el.closest("li, tr, [role=listitem]")); + try { + var ctx = getItemContext(el); + if (ctx && isAction) { + send('click ' + locator + ' "' + ctx.replace(/"/g, '\\"') + '"'); + } else { + send('click ' + locator); + } + } catch(ce) { + send('click ' + locator); + } + } catch(err) { + console.debug("__pw:# click recording error: " + err.message); + } + } + + function handleInput(e) { + const el = e.target; + if (el.tagName !== "INPUT" && el.tagName !== "TEXTAREA") return; + if (el.type === "checkbox" || el.type === "radio") return; + fillTarget = el; + fillValue = el.value; + if (fillTimer) clearTimeout(fillTimer); + fillTimer = setTimeout(flushFill, 1500); + } + + function handleChange(e) { + const el = e.target; + if (el.tagName === "SELECT") { + const opt = el.options[el.selectedIndex]; + const optText = opt ? opt.text.trim() : el.value; + send('select ' + getLocator(el) + ' "' + optText.replace(/"/g, '\\"') + '"'); + } + } + + function handleKeydown(e) { + const specialKeys = ["Enter", "Tab", "Escape"]; + if (specialKeys.includes(e.key)) { + if (fillTimer) { clearTimeout(fillTimer); flushFill(); } + send('press ' + e.key); + } + } + + document.addEventListener("click", handleClick, true); + document.addEventListener("input", handleInput, true); + document.addEventListener("change", handleChange, true); + document.addEventListener("keydown", handleKeydown, true); + + window.__pwRecorderCleanup = () => { + if (fillTimer) { clearTimeout(fillTimer); flushFill(); } + document.removeEventListener("click", handleClick, true); + document.removeEventListener("input", handleInput, true); + document.removeEventListener("change", handleChange, true); + document.removeEventListener("keydown", handleKeydown, true); + window.__pwRecorderActive = false; + delete window.__pwRecorderCleanup; + }; +})(); diff --git a/packages/extension/devtools.html b/packages/extension/devtools.html new file mode 100644 index 0000000..c317bf3 --- /dev/null +++ b/packages/extension/devtools.html @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/packages/extension/devtools.js b/packages/extension/devtools.js new file mode 100644 index 0000000..89d94ed --- /dev/null +++ b/packages/extension/devtools.js @@ -0,0 +1,5 @@ +chrome.devtools.panels.create( + "Playwright REPL", + "icons/icon16.png", + "panel/panel.html" +); diff --git a/packages/extension/icons/icon128.png b/packages/extension/icons/icon128.png new file mode 100644 index 0000000000000000000000000000000000000000..248b9948d008f0aca2e2606ed29c7916e1233a5f GIT binary patch literal 742 zcmeAS@N?(olHy`uVBq!ia0vp^4Is?H1|$#LC7xzrU|Q?x;uumf=k1(>xrZGDj;s?Z zpQ?5#aFs8EeUAlS!p%w3HkYex_Y z0E_Nj35ASQHsAb9!`=RG+qtXu zMD~6AA@(I>v+Uc?sxLOC+1`4c_F^H3QhPBm&HmQ=;1`YC?maD%+}~e!UWD<&rT-8$tEDy_{mr)LWv0tHZrozW7N^v zZ^gvSu~(CM#V-wJj$VhKGX*6aUPv}DNToAGksI#7}>4`MZlmmwZL*56=Ih3+&x$uNR;OAAwlCFf# zczZ#Ic8(6;4GbL|83!{N7kuhun4}!>?z%tg1PR8i%y0jndL^i%TmPe9Y2)I(_Z|Be z)<{%MSS9e{eK&6ci)(=!$CvL%PRl1U$_O(5eOJcV^MGTXtKmuzkk?}>>lP6CkCKx(8f5<$RcA~(%VU2^#j}nI-M;22)4hDulvmdp3AAD~KG=ss@ L)z4*}Q$iB}{8A*y literal 0 HcmV?d00001 diff --git a/packages/extension/icons/icon48.png b/packages/extension/icons/icon48.png new file mode 100644 index 0000000000000000000000000000000000000000..ff3fb897dc7114b9a04b3cf8a2825dee47c8522b GIT binary patch literal 266 zcmV+l0rmcgP)>uzas;n!)GB>Kr}vspaHV+QN(gz zpLz?bc-k!(umb=UA3+%Ks9(r{6#xiC ${expr});`; + } + case "go-back": + case "back": + return `await page.goBack();`; + case "go-forward": + case "forward": + return `await page.goForward();`; + case "reload": + return `await page.reload();`; + case "verify-text": { + if (!args[0]) return null; + return `await expect(page.getByText(${JSON.stringify(args[0])})).toBeVisible();`; + } + case "verify-no-text": { + if (!args[0]) return null; + return `await expect(page.getByText(${JSON.stringify(args[0])})).not.toBeVisible();`; + } + case "verify-element": { + if (!args[0]) return null; + return `await expect(page.getByText(${JSON.stringify(args[0])})).toBeVisible();`; + } + case "verify-no-element": { + if (!args[0]) return null; + return `await expect(page.getByText(${JSON.stringify(args[0])})).not.toBeVisible();`; + } + case "verify-url": { + if (!args[0]) return null; + return `await expect(page).toHaveURL(/${args[0].replace(/[.*+?^${}()|[\]\\\/]/g, '\\$&')}/);`; + } + case "verify-title": { + if (!args[0]) return null; + return `await expect(page).toHaveTitle(/${args[0].replace(/[.*+?^${}()|[\]\\\/]/g, '\\$&')}/);`; + } + default: + return `// unknown command: ${cmd}`; + } +} diff --git a/packages/extension/lib/relayConnection.js b/packages/extension/lib/relayConnection.js new file mode 100644 index 0000000..6a18c66 --- /dev/null +++ b/packages/extension/lib/relayConnection.js @@ -0,0 +1,112 @@ +/** + * RelayConnection — CDP relay over WebSocket, matching Playwright's MCP Bridge pattern. + * + * Bridges chrome.debugger ↔ WebSocket so Playwright can control a browser tab + * via connectOverCDP through the CommandServer relay. + * + * Protocol (3 message types): + * Server → Extension: + * { id, method: "attachToTab", params: {} } + * → attach chrome.debugger, return real targetInfo from CDP + * { id, method: "forwardCDPCommand", params: { sessionId, method, params } } + * → forward to chrome.debugger with sessionId support + * Extension → Server: + * { method: "forwardCDPEvent", params: { sessionId, method, params } } + * → forward chrome.debugger.onEvent back to server + */ + +export class RelayConnection { + constructor(ws, tabId) { + this._ws = ws; + this._debuggee = { tabId }; + this._closed = false; + + this._eventListener = (source, method, params) => this._onDebuggerEvent(source, method, params); + this._detachListener = (source, reason) => this._onDebuggerDetach(source, reason); + chrome.debugger.onEvent.addListener(this._eventListener); + chrome.debugger.onDetach.addListener(this._detachListener); + + this._ws.onmessage = (event) => this._onMessage(event); + this._ws.onclose = () => this._onClose(); + + this.onclose = null; + } + + close(message) { + this._ws.close(1000, message); + this._onClose(); + } + + _onClose() { + if (this._closed) return; + this._closed = true; + chrome.debugger.onEvent.removeListener(this._eventListener); + chrome.debugger.onDetach.removeListener(this._detachListener); + chrome.debugger.detach(this._debuggee).catch(() => {}); + this.onclose?.(); + } + + // ─── CDP events from browser → server ───────────────────────────────── + + _onDebuggerEvent(source, method, params) { + if (source.tabId !== this._debuggee.tabId) return; + this._sendMessage({ + method: 'forwardCDPEvent', + params: { + sessionId: source.sessionId, + method, + params, + }, + }); + } + + _onDebuggerDetach(source, reason) { + if (source.tabId !== this._debuggee.tabId) return; + this.close(`Debugger detached: ${reason}`); + } + + // ─── Messages from server → extension ───────────────────────────────── + + _onMessage(event) { + this._onMessageAsync(event).catch(e => console.error('[relay] Error:', e)); + } + + async _onMessageAsync(event) { + let message; + try { + message = JSON.parse(event.data); + } catch (e) { + this._sendMessage({ error: `Parse error: ${e.message}` }); + return; + } + + const response = { id: message.id }; + try { + response.result = await this._handleCommand(message); + } catch (e) { + response.error = e.message; + } + this._sendMessage(response); + } + + async _handleCommand(message) { + if (message.method === 'attachToTab') { + // Attach chrome.debugger and get REAL targetInfo from CDP + await chrome.debugger.attach(this._debuggee, '1.3'); + const result = await chrome.debugger.sendCommand(this._debuggee, 'Target.getTargetInfo'); + return { targetInfo: result?.targetInfo }; + } + + if (message.method === 'forwardCDPCommand') { + const { sessionId, method, params } = message.params; + // Pass sessionId directly to chrome.debugger (key fix from MCP Bridge) + const debuggerSession = { ...this._debuggee, sessionId }; + return await chrome.debugger.sendCommand(debuggerSession, method, params || {}); + } + } + + _sendMessage(message) { + if (this._ws.readyState === WebSocket.OPEN) + this._ws.send(JSON.stringify(message)); + } +} diff --git a/packages/extension/manifest.json b/packages/extension/manifest.json new file mode 100644 index 0000000..58ad4e8 --- /dev/null +++ b/packages/extension/manifest.json @@ -0,0 +1,23 @@ +{ + "manifest_version": 3, + "name": "Playwright REPL", + "version": "1.0.0", + "description": "A REPL panel inside Chrome DevTools for Playwright-style browser automation commands.", + "devtools_page": "devtools.html", + "permissions": [ + "debugger", + "tabs" + ], + "host_permissions": [ + "http://127.0.0.1:*/*" + ], + "background": { + "service_worker": "background.js", + "type": "module" + }, + "icons": { + "16": "icons/icon16.png", + "48": "icons/icon48.png", + "128": "icons/icon128.png" + } +} diff --git a/packages/extension/package.json b/packages/extension/package.json index f2e7856..9b3ee2d 100644 --- a/packages/extension/package.json +++ b/packages/extension/package.json @@ -1,9 +1,17 @@ { "name": "@playwright-repl/extension", - "version": "0.9.3", + "version": "1.0.0", "private": true, "description": "Chrome DevTools panel extension for Playwright REPL", + "type": "module", "scripts": { - "test": "echo \"no tests yet\"" + "test": "vitest run", + "test:coverage": "vitest run --coverage" + }, + "devDependencies": { + "@vitest/coverage-v8": "^4.0.18", + "happy-dom": "^20.6.1", + "vitest": "^4.0.18", + "vitest-chrome": "^0.1.0" } } diff --git a/packages/extension/panel/panel.css b/packages/extension/panel/panel.css new file mode 100644 index 0000000..6d5adf8 --- /dev/null +++ b/packages/extension/panel/panel.css @@ -0,0 +1,690 @@ +/* === Theme variables === */ + +:root { + /* Light theme (default — matches Chrome DevTools) */ + --bg-body: #ffffff; + --bg-toolbar: #f3f3f3; + --bg-editor: #ffffff; + --bg-line-highlight: #e8e8e8; + --bg-button: #e0e0e0; + --bg-button-hover: #d0d0d0; + --bg-splitter: #f3f3f3; + --bg-splitter-hover: #e8e8e8; + --bg-scrollbar-track: #ffffff; + --bg-scrollbar-thumb: #c1c1c1; + --bg-scrollbar-thumb-hover: #a8a8a8; + + --text-default: #1e1e1e; + --text-line-numbers: #858585; + --text-dim: #6e6e6e; + --text-placeholder: #a0a0a0; + + --border-primary: #d4d4d4; + --border-button: #c8c8c8; + --border-screenshot: #d4d4d4; + + --color-run-bg: #2ea043; + --color-run-bg-hover: #3fb950; + --color-recording-bg: #fde8e8; + --color-recording-text: #d32f2f; + --color-recording-border: #d32f2f; + --color-error: #d32f2f; + --color-success: #2e7d32; + --color-command: #0451a5; + --color-snapshot: #0070c1; + --color-comment: #6a9955; + --color-active-line: #795e26; + --color-line-pass: #2e7d32; + --color-line-fail: #d32f2f; + --color-prompt: #2e7d32; + --color-splitter-handle: #a0a0a0; + --color-splitter-handle-hover: #007acc; + --color-toolbar-sep: #d4d4d4; + --color-caret: #1e1e1e; +} + +.theme-dark { + --bg-body: #1e1e1e; + --bg-toolbar: #252526; + --bg-editor: #1e1e1e; + --bg-line-highlight: #2a2d2e; + --bg-button: #333333; + --bg-button-hover: #3c3c3c; + --bg-splitter: #252526; + --bg-splitter-hover: #2a2d2e; + --bg-scrollbar-track: #1e1e1e; + --bg-scrollbar-thumb: #444444; + --bg-scrollbar-thumb-hover: #555555; + + --text-default: #d4d4d4; + --text-line-numbers: #858585; + --text-dim: #888888; + --text-placeholder: #555555; + + --border-primary: #333333; + --border-button: #444444; + --border-screenshot: #444444; + + --color-run-bg: #2ea043; + --color-run-bg-hover: #3fb950; + --color-recording-bg: #5c2020; + --color-recording-text: #f44747; + --color-recording-border: #f44747; + --color-error: #f44747; + --color-success: #6a9955; + --color-command: #569cd6; + --color-snapshot: #9cdcfe; + --color-comment: #6a9955; + --color-active-line: #dcdcaa; + --color-line-pass: #6a9955; + --color-line-fail: #f44747; + --color-prompt: #6a9955; + --color-splitter-handle: #555555; + --color-splitter-handle-hover: #007acc; + --color-toolbar-sep: #444444; + --color-caret: #d4d4d4; +} + +/* === Reset === */ + +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +html, body { + height: 100%; + background: var(--bg-body); + color: var(--text-default); + font-family: "Cascadia Code", "Fira Code", "Consolas", "Courier New", monospace; + font-size: 13px; + display: flex; + flex-direction: column; +} + +/* === Toolbar (top) === */ + +#toolbar { + display: flex; + justify-content: space-between; + align-items: center; + padding: 4px 8px; + background: var(--bg-toolbar); + border-bottom: 1px solid var(--border-primary); + flex-shrink: 0; +} + +#toolbar-left { + display: flex; + gap: 4px; + align-items: center; +} + +#toolbar-right { + display: flex; + align-items: center; +} + +.toolbar-sep { + width: 1px; + height: 18px; + background: var(--color-toolbar-sep); + margin: 0 4px; +} + +#toolbar button { + background: var(--bg-button); + color: var(--text-default); + border: 1px solid var(--border-button); + border-radius: 4px; + padding: 4px 10px; + font-family: inherit; + font-size: 11px; + cursor: pointer; +} + +#toolbar button:hover { + background: var(--bg-button-hover); +} + +#toolbar button:disabled { + opacity: 0.4; + cursor: default; +} + +#run-btn, +#step-btn { + min-width: 28px; + padding: 4px 8px; + font-size: 14px; + text-align: center; +} + +#run-btn { + background: var(--color-run-bg) !important; + color: white !important; + border-color: var(--color-run-bg) !important; + font-weight: bold; +} + +#run-btn:hover { + background: var(--color-run-bg-hover) !important; +} + +#record-btn.recording { + background: var(--color-recording-bg) !important; + color: var(--color-recording-text) !important; + border-color: var(--color-recording-border) !important; +} + +#file-info { + color: var(--text-dim); + font-size: 11px; +} + +/* === Editor pane === */ + +#editor-pane { + display: flex; + flex: 1; + min-height: 80px; + overflow: hidden; + background: var(--bg-editor); +} + +#line-numbers { + width: 40px; + flex-shrink: 0; + padding: 8px 4px 8px 8px; + text-align: right; + color: var(--text-line-numbers); + background: var(--bg-editor); + font-family: inherit; + font-size: inherit; + line-height: 18px; + overflow: hidden; + user-select: none; + border-right: 1px solid var(--border-primary); +} + +#line-numbers div { + height: 18px; +} + +#line-numbers .line-active { + color: var(--color-active-line); + background: var(--bg-line-highlight); +} + +#line-numbers .line-pass { + color: var(--color-line-pass); +} + +#line-numbers .line-pass::before { + content: "\2713"; + margin-right: 2px; + font-size: 10px; +} + +#line-numbers .line-fail { + color: var(--color-line-fail); +} + +#line-numbers .line-fail::before { + content: "\2717"; + margin-right: 2px; + font-size: 10px; +} + +#editor-wrapper { + flex: 1; + position: relative; + overflow: hidden; +} + +#line-highlight { + position: absolute; + left: 0; + right: 0; + height: 18px; + background: var(--bg-line-highlight); + display: none; + pointer-events: none; +} + +#editor { + width: 100%; + height: 100%; + resize: none; + background: transparent; + color: var(--text-default); + border: none; + outline: none; + padding: 8px; + font-family: inherit; + font-size: inherit; + line-height: 18px; + white-space: pre; + overflow-y: auto; + overflow-x: auto; + tab-size: 2; + caret-color: var(--color-caret); + position: relative; +} + +#editor::placeholder { + color: var(--text-placeholder); +} + +/* === Splitter === */ + +#splitter { + height: 6px; + background: var(--bg-splitter); + cursor: row-resize; + flex-shrink: 0; + display: flex; + align-items: center; + justify-content: center; + border-top: 1px solid var(--border-primary); + border-bottom: 1px solid var(--border-primary); +} + +#splitter-handle { + width: 40px; + height: 2px; + background: var(--color-splitter-handle); + border-radius: 1px; +} + +#splitter:hover { + background: var(--bg-splitter-hover); +} + +#splitter:hover #splitter-handle { + background: var(--color-splitter-handle-hover); +} + +/* === Console pane === */ + +#console-pane { + display: flex; + flex-direction: column; + flex: 1; + min-height: 80px; + overflow: hidden; +} + +#console-header { + display: flex; + justify-content: space-between; + align-items: center; + padding: 4px 12px; + background: var(--bg-toolbar); + border-bottom: 1px solid var(--border-primary); + flex-shrink: 0; + font-size: 11px; +} + +#console-title { + color: var(--text-default); + font-size: 12px; + font-weight: 600; +} + +#console-header-left { + display: flex; + align-items: center; + gap: 8px; +} + +#console-stats { + color: var(--text-dim); +} + +#console-stats .pass-count { + color: var(--color-success); +} + +#console-stats .fail-count { + color: var(--color-error); +} + +#console-clear-btn { + background: transparent; + border: none; + color: var(--text-dim); + font-family: inherit; + font-size: 11px; + cursor: pointer; + padding: 1px 6px; + border-radius: 3px; +} + +#console-clear-btn:hover { + color: var(--text-default); + background: var(--bg-button); +} + +/* Output area */ +#output { + flex: 1; + overflow-y: auto; + padding: 8px 12px; + white-space: pre-wrap; + word-break: break-word; +} + +/* Individual output lines */ +.line { + padding: 1px 0; +} + +.line-command { + color: var(--color-command); +} + +.line-command::before { + content: "> "; + color: var(--color-success); +} + +.line-success { + color: var(--color-success); +} + +.line-success::before { + content: "\2713 "; +} + +.line-error { + color: var(--color-error); +} + +.line-error::before { + content: "\2717 "; +} + +.line-info { + color: var(--text-default); +} + +.line-comment { + color: var(--color-comment); + font-style: italic; +} + +.line-snapshot { + color: var(--color-snapshot); + font-size: 12px; +} + +/* Screenshot block */ +.screenshot-block { + position: relative; + display: inline-block; + margin: 6px 0; +} + +.screenshot-block img { + max-width: 400px; + border: 1px solid var(--border-screenshot); + border-radius: 4px 4px 0 0; + display: block; + cursor: zoom-in; +} + +.screenshot-block:hover img { + opacity: 0.85; +} + +.screenshot-zoom-hint { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + background: rgba(0, 0, 0, 0.6); + color: #fff; + font-size: 11px; + padding: 4px 10px; + border-radius: 4px; + pointer-events: none; + opacity: 0; + transition: opacity 0.15s; +} + +.screenshot-block:hover .screenshot-zoom-hint { + opacity: 1; +} + +.screenshot-actions { + display: flex; + justify-content: flex-end; + padding: 4px 6px; + background: var(--bg-toolbar); + border: 1px solid var(--border-screenshot); + border-top: none; + border-radius: 0 0 4px 4px; +} + +.screenshot-btn { + background: var(--bg-button); + color: var(--text-default); + border: 1px solid var(--border-button); + border-radius: 3px; + padding: 2px 8px; + font-family: inherit; + font-size: 10px; + cursor: pointer; +} + +.screenshot-btn:hover { + background: var(--bg-button-hover); +} + +/* Lightbox */ +#lightbox { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + background: rgba(0, 0, 0, 0.8); + display: flex; + align-items: center; + justify-content: center; + z-index: 100; + cursor: pointer; +} + +#lightbox[hidden] { + display: none; +} + +#lightbox img { + max-width: 95%; + max-height: 95%; + border-radius: 4px; + box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5); + cursor: default; +} + +#lightbox-close-btn { + position: absolute; + top: 10px; + right: 10px; + background: rgba(255, 255, 255, 0.15); + color: #fff; + border: 1px solid rgba(255, 255, 255, 0.3); + border-radius: 4px; + padding: 4px 12px; + font-family: inherit; + font-size: 18px; + line-height: 1; + cursor: pointer; +} + +#lightbox-close-btn:hover { + background: rgba(255, 255, 255, 0.3); +} + +#lightbox-save-btn { + position: absolute; + top: 10px; + right: 50px; + background: rgba(255, 255, 255, 0.15); + color: #fff; + border: 1px solid rgba(255, 255, 255, 0.3); + border-radius: 4px; + padding: 4px 14px; + font-family: inherit; + font-size: 12px; + cursor: pointer; +} + +#lightbox-save-btn:hover { + background: rgba(255, 255, 255, 0.3); +} + +/* Code block (export output) */ +.code-block { + position: relative; + border: 1px solid var(--border-primary); + border-radius: 4px; + margin: 6px 0; + background: var(--bg-editor); +} + +.code-block .code-content { + margin: 0; + padding: 8px 12px; + color: var(--color-snapshot); + font-family: inherit; + font-size: 12px; + line-height: 16px; + white-space: pre-wrap; + word-break: break-word; +} + +.code-block .code-copy-btn { + position: absolute; + top: 4px; + right: 4px; + background: var(--bg-button); + color: var(--text-default); + border: 1px solid var(--border-button); + border-radius: 3px; + padding: 2px 8px; + font-family: inherit; + font-size: 10px; + cursor: pointer; +} + +.code-block .code-copy-btn:hover { + background: var(--bg-button-hover); +} + +/* Input bar */ +#input-bar { + display: flex; + align-items: center; + border-top: 1px solid var(--border-primary); + padding: 6px 12px; + background: var(--bg-toolbar); + gap: 8px; + flex-shrink: 0; +} + +#prompt { + color: var(--color-prompt); + font-weight: bold; + flex-shrink: 0; +} + +#input-wrapper { + flex: 1; + position: relative; +} + +#ghost-text { + position: absolute; + top: 0; + left: 0; + color: var(--text-placeholder); + font-family: inherit; + font-size: inherit; + line-height: normal; + pointer-events: none; + white-space: pre; +} + +#autocomplete-dropdown { + position: absolute; + bottom: 100%; + left: 0; + background: var(--bg-toolbar); + border: 1px solid var(--border-primary); + border-radius: 4px; + padding: 4px 0; + margin-bottom: 4px; + max-height: 200px; + overflow-y: auto; + z-index: 50; + box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.15); +} + +#autocomplete-dropdown[hidden] { + display: none; +} + +.autocomplete-item { + padding: 3px 12px; + cursor: pointer; + font-family: inherit; + font-size: 12px; + color: var(--text-default); +} + +.autocomplete-item:hover, +.autocomplete-item.active { + background: var(--bg-button); +} + +#command-input { + width: 100%; + background: transparent; + border: none; + outline: none; + color: var(--text-default); + font-family: inherit; + font-size: inherit; + caret-color: var(--color-caret); + position: relative; +} + +#command-input::placeholder { + color: var(--text-placeholder); +} + +/* Scrollbar styling */ +#output::-webkit-scrollbar, +#editor::-webkit-scrollbar { + width: 8px; +} + +#output::-webkit-scrollbar-track, +#editor::-webkit-scrollbar-track { + background: var(--bg-scrollbar-track); +} + +#output::-webkit-scrollbar-thumb, +#editor::-webkit-scrollbar-thumb { + background: var(--bg-scrollbar-thumb); + border-radius: 4px; +} + +#output::-webkit-scrollbar-thumb:hover, +#editor::-webkit-scrollbar-thumb:hover { + background: var(--bg-scrollbar-thumb-hover); +} diff --git a/packages/extension/panel/panel.html b/packages/extension/panel/panel.html new file mode 100644 index 0000000..f156b7b --- /dev/null +++ b/packages/extension/panel/panel.html @@ -0,0 +1,68 @@ + + + + + + + + +
+
+ + + + + + + + +
+
+ +
+
+ + +
+
+
+
+ +
+
+ + +
+ + +
+
+ + Terminal + + + +
+
+
+ pw> +
+ + + +
+
+
+ + + + + + + diff --git a/packages/extension/panel/panel.js b/packages/extension/panel/panel.js new file mode 100644 index 0000000..a5b6f4d --- /dev/null +++ b/packages/extension/panel/panel.js @@ -0,0 +1,1047 @@ +import { pwToPlaywright } from "../lib/converter.js"; + +// --- DOM references --- + +const output = document.getElementById("output"); +const input = document.getElementById("command-input"); +const editor = document.getElementById("editor"); +const lineNumbers = document.getElementById("line-numbers"); +const editorPane = document.getElementById("editor-pane"); +const splitter = document.getElementById("splitter"); +const consoleStats = document.getElementById("console-stats"); +const fileInfo = document.getElementById("file-info"); +const runBtn = document.getElementById("run-btn"); +const openBtn = document.getElementById("open-btn"); +const saveBtn = document.getElementById("save-btn"); +const exportBtn = document.getElementById("export-btn"); +const recordBtn = document.getElementById("record-btn"); +const copyBtn = document.getElementById("copy-btn"); +const stepBtn = document.getElementById("step-btn"); +const consoleClearBtn = document.getElementById("console-clear-btn"); +const lineHighlight = document.getElementById("line-highlight"); +const lightbox = document.getElementById("lightbox"); +const lightboxImg = document.getElementById("lightbox-img"); +const lightboxSaveBtn = document.getElementById("lightbox-save-btn"); +const lightboxCloseBtn = document.getElementById("lightbox-close-btn"); +const ghostText = document.getElementById("ghost-text"); +const dropdown = document.getElementById("autocomplete-dropdown"); + +// The tab we're inspecting +const inspectedTabId = chrome.devtools.inspectedWindow.tabId; + +// --- Theme detection --- +const themeName = chrome.devtools?.panels?.themeName; +if (themeName === "dark") { + document.body.classList.add("theme-dark"); +} + +// --- State --- + +// Command history (for REPL input up/down) +const history = []; +let historyIndex = -1; + +// Run state +let isRunning = false; +let currentRunLine = -1; +let runPassCount = 0; +let runFailCount = 0; +let lineResults = []; // "pass" | "fail" | null per line + +// Step state +let stepLine = -1; // Next line to execute when stepping, -1 = not stepping + +// File state +let currentFilename = ""; + +// Commands handled locally (not added to history, not sent to background) +const LOCAL_COMMANDS = new Set(["history", "clear", "reset"]); + +// All commands for autocomplete +const COMMANDS = [ + "goto", "open", "click", "dblclick", "fill", "select", + "check", "uncheck", "hover", "press", "snapshot", + "screenshot", "eval", "go-back", "back", "go-forward", "forward", + "reload", "verify-text", "verify-no-text", "verify-element", + "verify-no-element", "verify-url", "verify-title", + "export", "help", "history", "clear", "reset" +]; + +// --- Autocomplete --- + +function updateGhostText() { + const val = input.value.toLowerCase(); + if (!val || val.includes(" ")) { + ghostText.textContent = ""; + return; + } + const match = COMMANDS.find(cmd => cmd.startsWith(val) && cmd !== val); + if (match) { + ghostText.style.paddingLeft = val.length + "ch"; + ghostText.textContent = match.slice(val.length); + } else { + ghostText.textContent = ""; + } +} + +function clearGhostText() { + ghostText.textContent = ""; +} + +let dropdownItems = []; +let dropdownIndex = -1; + +function showDropdown(matches) { + dropdown.innerHTML = ""; + dropdownItems = matches; + dropdownIndex = -1; + for (let i = 0; i < matches.length; i++) { + const div = document.createElement("div"); + div.className = "autocomplete-item"; + div.textContent = matches[i]; + div.addEventListener("mousedown", (e) => { + e.preventDefault(); + input.value = matches[i] + " "; + hideDropdown(); + clearGhostText(); + input.focus(); + }); + dropdown.appendChild(div); + } + dropdown.hidden = false; +} + +function hideDropdown() { + dropdown.hidden = true; + dropdown.innerHTML = ""; + dropdownItems = []; + dropdownIndex = -1; +} + +function updateDropdownHighlight() { + const items = dropdown.querySelectorAll(".autocomplete-item"); + items.forEach((el, i) => { + el.classList.toggle("active", i === dropdownIndex); + }); +} + +// --- Output helpers --- + +function addLine(text, className) { + const div = document.createElement("div"); + div.className = `line ${className}`; + div.textContent = text; + output.appendChild(div); + output.scrollTop = output.scrollHeight; +} + +function addCommand(text) { + addLine(text, "line-command"); +} + +function addSuccess(text) { + addLine(text, "line-success"); +} + +function addError(text) { + addLine(text, "line-error"); +} + +function addInfo(text) { + addLine(text, "line-info"); +} + +function addSnapshot(text) { + addLine(text, "line-snapshot"); +} + +function addScreenshot(base64) { + const dataUrl = "data:image/png;base64," + base64; + + const wrapper = document.createElement("div"); + wrapper.className = "screenshot-block"; + + const img = document.createElement("img"); + img.src = dataUrl; + img.addEventListener("click", () => { + lightboxImg.src = dataUrl; + lightbox.hidden = false; + }); + wrapper.appendChild(img); + + const zoomHint = document.createElement("span"); + zoomHint.className = "screenshot-zoom-hint"; + zoomHint.textContent = "Click to enlarge"; + wrapper.appendChild(zoomHint); + + const actions = document.createElement("div"); + actions.className = "screenshot-actions"; + + const saveBtnEl = document.createElement("button"); + saveBtnEl.className = "screenshot-btn"; + saveBtnEl.textContent = "Save"; + saveBtnEl.addEventListener("click", () => { + const a = document.createElement("a"); + a.href = dataUrl; + a.download = "screenshot-" + new Date().toISOString().slice(0, 19).replace(/:/g, "-") + ".png"; + a.click(); + }); + actions.appendChild(saveBtnEl); + + wrapper.appendChild(actions); + + output.appendChild(wrapper); + output.scrollTop = output.scrollHeight; +} + +function addComment(text) { + addLine(text, "line-comment"); +} + +function addCodeBlock(code) { + const wrapper = document.createElement("div"); + wrapper.className = "code-block"; + + const copyBtn = document.createElement("button"); + copyBtn.className = "code-copy-btn"; + copyBtn.textContent = "Copy"; + copyBtn.addEventListener("click", () => { + if (copyToClipboard(code)) { + copyBtn.textContent = "Copied!"; + setTimeout(() => { copyBtn.textContent = "Copy"; }, 1500); + } + }); + wrapper.appendChild(copyBtn); + + const pre = document.createElement("pre"); + pre.className = "code-content"; + pre.textContent = code; + wrapper.appendChild(pre); + + output.appendChild(wrapper); + output.scrollTop = output.scrollHeight; +} + +// --- Clipboard helper (navigator.clipboard blocked in DevTools panels) --- + +function copyToClipboard(text) { + const textarea = document.createElement("textarea"); + textarea.value = text; + textarea.style.position = "fixed"; + textarea.style.opacity = "0"; + document.body.appendChild(textarea); + textarea.select(); + try { + document.execCommand("copy"); + return true; + } catch (e) { + return false; + } finally { + document.body.removeChild(textarea); + } +} + +// --- Editor helpers --- + +function updateLineNumbers() { + const lines = editor.value.split("\n"); + let html = ""; + for (let i = 0; i < lines.length; i++) { + let cls = ""; + if (i === currentRunLine) { + cls = "line-active"; + } else if (lineResults[i] === "pass") { + cls = "line-pass"; + } else if (lineResults[i] === "fail") { + cls = "line-fail"; + } + html += `
${i + 1}
`; + } + lineNumbers.innerHTML = html; + updateLineHighlight(); +} + +function updateLineHighlight() { + if (currentRunLine >= 0) { + // 8px padding + line index * 18px line-height, offset by scroll + lineHighlight.style.top = (8 + currentRunLine * 18 - editor.scrollTop) + "px"; + lineHighlight.style.display = "block"; + } else { + lineHighlight.style.display = "none"; + } +} + +function syncScroll() { + lineNumbers.scrollTop = editor.scrollTop; + updateLineHighlight(); +} + +function updateFileInfo() { + const lines = editor.value.split("\n"); + const count = lines.length; + const name = currentFilename || "untitled.pw"; + fileInfo.textContent = `${name} \u2014 ${count} line${count !== 1 ? "s" : ""}`; +} + +function updateButtonStates() { + const hasContent = editor.value.trim().length > 0; + copyBtn.disabled = !hasContent; + saveBtn.disabled = !hasContent; + exportBtn.disabled = !hasContent; +} + +function appendToEditor(text) { + const current = editor.value; + if (current && !current.endsWith("\n")) { + editor.value += "\n"; + } + editor.value += text; + updateLineNumbers(); + updateFileInfo(); + updateButtonStates(); + editor.scrollTop = editor.scrollHeight; +} + +function clearConsole() { + output.innerHTML = ""; + runPassCount = 0; + runFailCount = 0; + updateConsoleStats(); +} + +function findNextExecutableLine(startFrom, lines) { + for (let i = startFrom; i < lines.length; i++) { + const trimmed = lines[i].trim(); + if (trimmed && !trimmed.startsWith("#")) return i; + } + return -1; +} + +function updateConsoleStats() { + if (runPassCount === 0 && runFailCount === 0) { + consoleStats.textContent = ""; + return; + } + consoleStats.innerHTML = + `${runPassCount} passed / ` + + `${runFailCount} failed`; +} + +// Editor input/scroll listeners +editor.addEventListener("input", () => { + // Reset execution state when editor content changes + stepLine = -1; + currentRunLine = -1; + lineResults = []; + updateLineNumbers(); + updateFileInfo(); + updateButtonStates(); +}); +editor.addEventListener("scroll", syncScroll); + +// --- Export helper --- + +function exportFromLines(cmds) { + const lines = [ + `import { test, expect } from '@playwright/test';`, + ``, + `test('recorded session', async ({ page }) => {`, + ]; + for (const cmd of cmds) { + if (cmd.startsWith("#")) { + lines.push(` ${cmd.replace("#", "//")}`); + continue; + } + const converted = pwToPlaywright(cmd); + if (converted) { + lines.push(` ${converted}`); + } + } + lines.push(`});`); + + const code = lines.join("\n"); + addCodeBlock(code); +} + +// --- Command execution (REPL ad-hoc) --- + +async function executeCommand(raw) { + const trimmed = raw.trim(); + if (!trimmed) return; + + // Skip comments + if (trimmed.startsWith("#")) { + addComment(trimmed); + return; + } + + // Handle local console commands (no background needed, not added to history) + if (trimmed === "history") { + if (history.length === 0) { + addInfo("No command history."); + } else { + for (const cmd of history) { + addInfo(cmd); + } + } + return; + } + + if (trimmed === "clear") { + clearConsole(); + return; + } + + if (trimmed === "reset") { + history.length = 0; + historyIndex = -1; + clearConsole(); + addInfo("History and terminal cleared."); + return; + } + + // Handle export command locally (no CDP needed) + if (trimmed === "export") { + const editorLines = editor.value.split("\n").filter((l) => l.trim()); + if (editorLines.length === 0) { + addInfo("Nothing to export. Add commands to the editor first."); + } else { + exportFromLines(editorLines); + } + return; + } + if (trimmed.startsWith("export ")) { + const subCmd = trimmed.slice(7).trim(); + const converted = pwToPlaywright(subCmd); + if (converted) { + addCommand(trimmed); + addLine(converted, "line-snapshot"); + } else { + addError("Cannot convert: " + subCmd); + } + return; + } + + addCommand(trimmed); + + try { + const result = await chrome.runtime.sendMessage({ + type: "pw-command", + raw: trimmed, + tabId: inspectedTabId, + }); + + if (!result) { + addError("No response from background worker."); + return; + } + + // Handle Engine result format: { text, isError } + if (result.text !== undefined) { + if (result.isError) { + addError(result.text); + } else { + // Detect result type from content + const text = result.text; + if (text.startsWith("data:image/png;base64,")) { + addScreenshot(text.slice("data:image/png;base64,".length)); + } else if (text.includes("[ref=") || text.startsWith("- ")) { + for (const line of text.split("\n")) { + addSnapshot(line); + } + } else { + addSuccess(text); + } + } + return; + } + + // Legacy format: { type, data, success } + switch (result.type) { + case "success": + addSuccess(result.data); + break; + case "error": + addError(result.data); + break; + case "info": + addInfo(result.data); + break; + case "snapshot": + for (const line of result.data.split("\n")) { + addSnapshot(line); + } + break; + case "screenshot": + addScreenshot(result.data); + break; + default: + addInfo(result.data || "Done."); + } + } catch (e) { + addError(`Error: ${e.message}`); + } +} + +// --- Command execution for Run (with pass/fail tracking) --- + +async function executeCommandForRun(raw) { + const trimmed = raw.trim(); + if (!trimmed) return; + + // Handle comments + if (trimmed.startsWith("#")) { + addComment(trimmed); + return; + } + + addCommand(trimmed); + + try { + const result = await chrome.runtime.sendMessage({ + type: "pw-command", + raw: trimmed, + tabId: inspectedTabId, + }); + + if (!result) { + addError("No response from background worker."); + lineResults[currentRunLine] = "fail"; + runFailCount++; + updateConsoleStats(); + updateLineNumbers(); + return; + } + + // Handle Engine result format: { text, isError } + if (result.text !== undefined) { + if (result.isError) { + addError(result.text); + lineResults[currentRunLine] = "fail"; + runFailCount++; + } else { + const text = result.text; + if (text.startsWith("data:image/png;base64,")) { + addScreenshot(text.slice("data:image/png;base64,".length)); + } else if (text.includes("[ref=") || text.startsWith("- ")) { + for (const line of text.split("\n")) { + addSnapshot(line); + } + } else { + addSuccess(text); + } + lineResults[currentRunLine] = "pass"; + runPassCount++; + } + updateConsoleStats(); + updateLineNumbers(); + return; + } + + // Legacy format: { type, data, success } + switch (result.type) { + case "success": + addSuccess(result.data); + lineResults[currentRunLine] = "pass"; + runPassCount++; + break; + case "error": + addError(result.data); + lineResults[currentRunLine] = "fail"; + runFailCount++; + break; + case "info": + addInfo(result.data); + lineResults[currentRunLine] = "pass"; + runPassCount++; + break; + case "snapshot": + for (const line of result.data.split("\n")) { + addSnapshot(line); + } + lineResults[currentRunLine] = "pass"; + runPassCount++; + break; + case "screenshot": + addScreenshot(result.data); + lineResults[currentRunLine] = "pass"; + runPassCount++; + break; + default: + addInfo(result.data || "Done."); + lineResults[currentRunLine] = "pass"; + runPassCount++; + } + } catch (e) { + addError(`Error: ${e.message}`); + lineResults[currentRunLine] = "fail"; + runFailCount++; + } + updateConsoleStats(); + updateLineNumbers(); +} + +// --- REPL input handling --- + +function selectDropdownItem(cmd) { + input.value = cmd + " "; + hideDropdown(); + clearGhostText(); +} + +input.addEventListener("keydown", (e) => { + // When dropdown is visible, arrow keys navigate it + if (!dropdown.hidden && dropdownItems.length > 0) { + if (e.key === "ArrowDown") { + e.preventDefault(); + dropdownIndex = (dropdownIndex + 1) % dropdownItems.length; + updateDropdownHighlight(); + return; + } + if (e.key === "ArrowUp") { + e.preventDefault(); + dropdownIndex = dropdownIndex <= 0 ? dropdownItems.length - 1 : dropdownIndex - 1; + updateDropdownHighlight(); + return; + } + if (e.key === "Enter" && dropdownIndex >= 0) { + e.preventDefault(); + selectDropdownItem(dropdownItems[dropdownIndex]); + return; + } + if (e.key === "Tab") { + e.preventDefault(); + if (dropdownIndex >= 0) { + selectDropdownItem(dropdownItems[dropdownIndex]); + } else if (dropdownItems.length > 0) { + selectDropdownItem(dropdownItems[0]); + } + return; + } + if (e.key === "Escape") { + e.preventDefault(); + e.stopPropagation(); + hideDropdown(); + clearGhostText(); + return; + } + } + + if (e.key === "Enter") { + const value = input.value; + if (value.trim()) { + const cmd = value.trim().toLowerCase(); + if (!LOCAL_COMMANDS.has(cmd)) { + history.push(value); + historyIndex = history.length; + } + executeCommand(value); + } + input.value = ""; + hideDropdown(); + clearGhostText(); + } else if (e.key === "Tab") { + e.preventDefault(); + const val = input.value.toLowerCase().trim(); + if (val.includes(" ")) return; + if (!val) { + showDropdown(COMMANDS); + return; + } + const matches = COMMANDS.filter(cmd => cmd.startsWith(val) && cmd !== val); + if (matches.length === 1) { + selectDropdownItem(matches[0]); + } else if (matches.length > 1) { + showDropdown(matches); + } + } else if (e.key === "ArrowUp") { + e.preventDefault(); + if (historyIndex > 0) { + historyIndex--; + input.value = history[historyIndex]; + } + hideDropdown(); + clearGhostText(); + } else if (e.key === "ArrowDown") { + e.preventDefault(); + if (historyIndex < history.length - 1) { + historyIndex++; + input.value = history[historyIndex]; + } else { + historyIndex = history.length; + input.value = ""; + } + hideDropdown(); + clearGhostText(); + } else if (e.key === "Escape") { + hideDropdown(); + clearGhostText(); + } else if (e.key === " " && e.ctrlKey) { + e.preventDefault(); + const val = input.value.toLowerCase().trim(); + if (val.includes(" ")) return; + const matches = val + ? COMMANDS.filter(cmd => cmd.startsWith(val) && cmd !== val) + : COMMANDS; + if (matches.length > 0) showDropdown(matches); + } +}); + +input.addEventListener("input", () => { + updateGhostText(); + // Auto-show dropdown while typing + const val = input.value.toLowerCase().trim(); + if (!val || val.includes(" ")) { + hideDropdown(); + return; + } + const matches = COMMANDS.filter(cmd => cmd.startsWith(val) && cmd !== val); + if (matches.length > 1) { + showDropdown(matches); + } else { + hideDropdown(); + } +}); + +// --- Editor keyboard shortcut --- + +editor.addEventListener("keydown", (e) => { + if ((e.ctrlKey || e.metaKey) && e.key === "Enter") { + e.preventDefault(); + runBtn.click(); + } +}); + +// --- Run button --- + +runBtn.addEventListener("click", async () => { + if (isRunning) { + isRunning = false; + runBtn.textContent = "\u25B6"; + addInfo("Run stopped."); + currentRunLine = -1; + updateLineNumbers(); + return; + } + + const content = editor.value; + if (!content.trim()) { + addInfo("Editor is empty. Open a .pw file or type commands."); + return; + } + + const lines = content.split("\n"); + const startLine = stepLine > 0 ? stepLine : 0; + + isRunning = true; + stepBtn.disabled = true; + runBtn.textContent = "\u25A0"; + + // Only reset stats if starting fresh (not continuing from step) + if (startLine === 0) { + runPassCount = 0; + runFailCount = 0; + lineResults = new Array(lines.length).fill(null); + updateConsoleStats(); + } + + addInfo(startLine > 0 ? "Continuing run from step..." : "Running script..."); + + for (let i = startLine; i < lines.length; i++) { + if (!isRunning) break; + const line = lines[i].trim(); + + // Skip empty lines and comments (comments shown but not counted) + if (!line) continue; + + currentRunLine = i; + updateLineNumbers(); + + await executeCommandForRun(line); + + if (isRunning) await new Promise((r) => setTimeout(r, 300)); + } + + isRunning = false; + stepBtn.disabled = false; + runBtn.textContent = "\u25B6"; + currentRunLine = -1; + stepLine = -1; + updateLineNumbers(); + addInfo("Run complete."); +}); + +// --- Step button --- + +stepBtn.addEventListener("click", async () => { + if (isRunning) return; + + const content = editor.value; + if (!content.trim()) { + addInfo("Editor is empty. Open a .pw file or type commands."); + return; + } + + const lines = content.split("\n"); + + // Initialize step state on first click + if (stepLine === -1) { + stepLine = 0; + lineResults = new Array(lines.length).fill(null); + runPassCount = 0; + runFailCount = 0; + updateConsoleStats(); + } + + // Find next executable line from current step position + const nextLine = findNextExecutableLine(stepLine, lines); + + if (nextLine === -1) { + addInfo("Step complete. No more lines to execute."); + stepLine = -1; + currentRunLine = -1; + updateLineNumbers(); + return; + } + + // Execute the line + stepBtn.disabled = true; + currentRunLine = nextLine; + updateLineNumbers(); + + await executeCommandForRun(lines[nextLine]); + + stepLine = nextLine + 1; + currentRunLine = nextLine; // Keep highlight on last stepped line + updateLineNumbers(); + stepBtn.disabled = false; + + // Check if there are more executable lines + if (findNextExecutableLine(stepLine, lines) === -1) { + addInfo("Step complete. All lines executed."); + stepLine = -1; + currentRunLine = -1; + updateLineNumbers(); + } +}); + +// --- Open button --- + +openBtn.addEventListener("click", () => { + const fileInput = document.createElement("input"); + fileInput.type = "file"; + fileInput.accept = ".pw,.txt"; + fileInput.addEventListener("change", () => { + const file = fileInput.files[0]; + if (!file) return; + const reader = new FileReader(); + reader.onload = () => { + editor.value = reader.result; + currentFilename = file.name; + lineResults = []; + updateLineNumbers(); + updateFileInfo(); + updateButtonStates(); + addInfo(`Opened ${file.name}`); + }; + reader.readAsText(file); + }); + fileInput.click(); +}); + +// --- Save button --- + +saveBtn.addEventListener("click", () => { + const content = editor.value; + if (!content.trim()) { + addInfo("Nothing to save."); + return; + } + const defaultName = + currentFilename || "commands-" + new Date().toISOString().slice(0, 10) + ".pw"; + const filename = prompt("Save as:", defaultName); + if (!filename) return; + const finalName = filename.endsWith(".pw") ? filename : filename + ".pw"; + const blob = new Blob([content], { type: "text/plain" }); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = finalName; + a.click(); + URL.revokeObjectURL(url); + currentFilename = finalName; + updateFileInfo(); + addSuccess("Saved as " + finalName); +}); + +// --- Export button --- + +exportBtn.addEventListener("click", () => { + const content = editor.value; + if (!content.trim()) { + addInfo("Nothing to export."); + return; + } + const editorLines = content.split("\n").filter((l) => l.trim()); + exportFromLines(editorLines); +}); + +// --- Copy button --- + +copyBtn.addEventListener("click", () => { + const content = editor.value; + if (!content.trim()) { + addInfo("Nothing to copy."); + return; + } + if (copyToClipboard(content)) { + addSuccess("Editor content copied to clipboard."); + } else { + addError("Failed to copy to clipboard."); + } +}); + +// --- Console header clear button --- + +consoleClearBtn.addEventListener("click", clearConsole); + +// --- Record button --- + +recordBtn.addEventListener("click", async () => { + recordBtn.classList.toggle("recording"); + const isRecording = recordBtn.classList.contains("recording"); + recordBtn.textContent = isRecording ? "\u23F9 Stop" : "\u23FA Record"; + + if (isRecording) { + try { + const result = await chrome.runtime.sendMessage({ + type: "pw-record-start", + tabId: inspectedTabId, + }); + if (result?.success) { + addInfo("Recording started. Interact with the page..."); + } else { + addError("Failed to start recording: " + (result?.error || "unknown")); + recordBtn.classList.remove("recording"); + recordBtn.textContent = "\u23FA Record"; + } + } catch (e) { + addError("Record error: " + e.message); + recordBtn.classList.remove("recording"); + recordBtn.textContent = "\u23FA Record"; + } + } else { + await chrome.runtime.sendMessage({ + type: "pw-record-stop", + tabId: inspectedTabId, + }); + addInfo("Recording stopped."); + } +}); + +// --- Port connection for recorded commands --- +// Service workers in Manifest V3 can terminate and restart at any time. +// When that happens, the port disconnects and panelPorts is lost. +// We reconnect automatically so recording keeps working. + +let port = null; + +function connectPort() { + // chrome.runtime.id is undefined when the extension context is invalidated + // (e.g., after extension reload/update). Stop retrying in that case. + if (!chrome.runtime?.id) return; + try { + port = chrome.runtime.connect({ name: `pw-panel-${inspectedTabId}` }); + } catch (e) { + return; + } + port.onMessage.addListener((message) => { + if (message.type === "pw-recorded-command") { + appendToEditor(message.command); + } + }); + port.onDisconnect.addListener(() => { + if (!chrome.runtime?.id) return; + setTimeout(connectPort, 500); + }); +} + +connectPort(); + +// --- Draggable splitter --- + +let isDragging = false; +let dragStartY = 0; +let dragStartHeight = 0; + +splitter.addEventListener("mousedown", (e) => { + isDragging = true; + dragStartY = e.clientY; + dragStartHeight = editorPane.offsetHeight; + document.body.style.cursor = "row-resize"; + document.body.style.userSelect = "none"; + e.preventDefault(); +}); + +document.addEventListener("mousemove", (e) => { + if (!isDragging) return; + const delta = e.clientY - dragStartY; + const newHeight = dragStartY === 0 ? dragStartHeight : dragStartHeight + delta; + const minEditor = 80; + const bodyHeight = document.body.offsetHeight; + const fixedHeight = + document.getElementById("toolbar").offsetHeight + + splitter.offsetHeight + + document.getElementById("console-header").offsetHeight + + document.getElementById("input-bar").offsetHeight; + const maxEditor = bodyHeight - fixedHeight - 80; + editorPane.style.flex = `0 0 ${Math.max(minEditor, Math.min(maxEditor, newHeight))}px`; +}); + +document.addEventListener("mouseup", () => { + if (!isDragging) return; + isDragging = false; + document.body.style.cursor = ""; + document.body.style.userSelect = ""; +}); + +// --- Lightbox --- + +lightbox.addEventListener("click", (e) => { + // Only close when clicking the backdrop, not the image or save button + if (e.target === lightbox) { + lightbox.hidden = true; + lightboxImg.src = ""; + } +}); + +lightboxCloseBtn.addEventListener("click", () => { + lightbox.hidden = true; + lightboxImg.src = ""; +}); + +lightboxSaveBtn.addEventListener("click", () => { + const a = document.createElement("a"); + a.href = lightboxImg.src; + a.download = "screenshot-" + new Date().toISOString().slice(0, 19).replace(/:/g, "-") + ".png"; + a.click(); +}); + +document.addEventListener("keydown", (e) => { + if (e.key === "Escape" && !lightbox.hidden) { + e.stopPropagation(); + e.preventDefault(); + lightbox.hidden = true; + lightboxImg.src = ""; + } +}); + +// --- Init --- + +updateLineNumbers(); +updateFileInfo(); +updateButtonStates(); +editor.focus(); + +addInfo("Playwright REPL v1.0.0"); +addInfo('Type commands below or open a .pw file in the editor.'); diff --git a/packages/extension/test/background.test.js b/packages/extension/test/background.test.js new file mode 100644 index 0000000..68d8af9 --- /dev/null +++ b/packages/extension/test/background.test.js @@ -0,0 +1,371 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { chrome } from "vitest-chrome/lib/index.esm.js"; +import { readFileSync } from "fs"; +import { resolve } from "path"; +import { RelayConnection } from "../lib/relayConnection.js"; + +// Read the actual recorder.js file content for fetch mock +const recorderCode = readFileSync( + resolve(import.meta.dirname, "..", "content", "recorder.js"), + "utf-8" +); + +// Mock WebSocket +class MockWebSocket { + constructor(url) { + this.url = url; + this.readyState = 1; // OPEN + this.send = vi.fn(); + this.close = vi.fn(); + } +} +MockWebSocket.OPEN = 1; +MockWebSocket.CLOSED = 3; +globalThis.WebSocket = MockWebSocket; + +// Mock fetch +globalThis.fetch = vi.fn(() => + Promise.resolve({ text: () => Promise.resolve(recorderCode) }) +); +chrome.runtime.getURL = vi.fn((path) => `chrome-extension://test/${path}`); + +// ─── Import + reset helpers ───────────────────────────────────────────────── + +let mod; +let getState, resetState; + +beforeEach(async () => { + vi.restoreAllMocks(); + + globalThis.WebSocket = MockWebSocket; + globalThis.fetch = vi.fn(() => + Promise.resolve({ text: () => Promise.resolve(recorderCode) }) + ); + globalThis.chrome = chrome; + chrome.runtime.getURL = vi.fn((path) => `chrome-extension://test/${path}`); + chrome.debugger.sendCommand.mockReset(); + chrome.debugger.attach.mockReset(); + chrome.debugger.detach.mockReset(); + chrome.debugger.onEvent.clearListeners(); + chrome.debugger.onDetach.clearListeners(); + chrome.runtime.onConnect.clearListeners(); + chrome.runtime.onMessage.clearListeners(); + + vi.resetModules(); + mod = await import("../background.js"); + getState = mod._getState; + resetState = mod._resetState; +}); + +// ─── Tests ────────────────────────────────────────────────────────────────── + +describe("handlePanelCommand", () => { + it("sends HTTP POST to command server", async () => { + globalThis.fetch = vi.fn(() => + Promise.resolve({ + json: () => Promise.resolve({ text: "Clicked", isError: false }), + }) + ); + + const result = await mod.handlePanelCommand("click e5"); + + expect(globalThis.fetch).toHaveBeenCalledWith( + "http://127.0.0.1:3000/run", + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ raw: "click e5" }), + } + ); + expect(result.text).toBe("Clicked"); + expect(result.isError).toBe(false); + }); + + it("returns error when server is not reachable", async () => { + globalThis.fetch = vi.fn(() => + Promise.reject(new Error("Connection refused")) + ); + + const result = await mod.handlePanelCommand("snapshot"); + + expect(result.isError).toBe(true); + expect(result.text).toContain("Not connected to server"); + }); +}); + +describe("RelayConnection", () => { + it("handles attachToTab by attaching debugger and returning real targetInfo", async () => { + chrome.debugger.attach.mockResolvedValue(undefined); + chrome.debugger.sendCommand.mockResolvedValue({ + targetInfo: { + targetId: "ABC123", + type: "page", + title: "Example", + url: "http://example.com", + browserContextId: "CTX1", + }, + }); + + const mockWs = new MockWebSocket("ws://test"); + const relay = new RelayConnection(mockWs, 42); + + // Simulate server sending attachToTab + await relay._onMessageAsync({ + data: JSON.stringify({ id: 1, method: "attachToTab", params: {} }), + }); + + // Should have attached to tab 42 + expect(chrome.debugger.attach).toHaveBeenCalledWith({ tabId: 42 }, "1.3"); + + // Should have called Target.getTargetInfo via CDP + expect(chrome.debugger.sendCommand).toHaveBeenCalledWith( + { tabId: 42 }, + "Target.getTargetInfo" + ); + + // Should have sent response with real targetInfo + expect(mockWs.send).toHaveBeenCalled(); + const response = JSON.parse(mockWs.send.mock.calls[0][0]); + expect(response.id).toBe(1); + expect(response.result.targetInfo.targetId).toBe("ABC123"); + expect(response.result.targetInfo.browserContextId).toBe("CTX1"); + }); + + it("handles forwardCDPCommand with sessionId", async () => { + chrome.debugger.sendCommand.mockResolvedValue({ result: { value: 42 } }); + + const mockWs = new MockWebSocket("ws://test"); + const relay = new RelayConnection(mockWs, 10); + + await relay._onMessageAsync({ + data: JSON.stringify({ + id: 2, + method: "forwardCDPCommand", + params: { + sessionId: "session-1", + method: "Runtime.evaluate", + params: { expression: "1+1" }, + }, + }), + }); + + // Should pass sessionId directly to chrome.debugger + expect(chrome.debugger.sendCommand).toHaveBeenCalledWith( + { tabId: 10, sessionId: "session-1" }, + "Runtime.evaluate", + { expression: "1+1" } + ); + + const response = JSON.parse(mockWs.send.mock.calls[0][0]); + expect(response.id).toBe(2); + expect(response.result).toEqual({ result: { value: 42 } }); + }); + + it("handles forwardCDPCommand without sessionId", async () => { + chrome.debugger.sendCommand.mockResolvedValue({}); + + const mockWs = new MockWebSocket("ws://test"); + const relay = new RelayConnection(mockWs, 10); + + await relay._onMessageAsync({ + data: JSON.stringify({ + id: 3, + method: "forwardCDPCommand", + params: { method: "Page.enable", params: {} }, + }), + }); + + expect(chrome.debugger.sendCommand).toHaveBeenCalledWith( + { tabId: 10, sessionId: undefined }, + "Page.enable", + {} + ); + }); + + it("forwards CDP events to server", () => { + const mockWs = new MockWebSocket("ws://test"); + const relay = new RelayConnection(mockWs, 10); + + // Simulate chrome.debugger.onEvent + chrome.debugger.onEvent.callListeners( + { tabId: 10, sessionId: undefined }, + "Page.loadEventFired", + { timestamp: 123 } + ); + + expect(mockWs.send).toHaveBeenCalled(); + const sent = JSON.parse(mockWs.send.mock.calls[0][0]); + expect(sent.method).toBe("forwardCDPEvent"); + expect(sent.params.method).toBe("Page.loadEventFired"); + expect(sent.params.params.timestamp).toBe(123); + }); + + it("ignores CDP events from other tabs", () => { + const mockWs = new MockWebSocket("ws://test"); + const relay = new RelayConnection(mockWs, 10); + + chrome.debugger.onEvent.callListeners( + { tabId: 99 }, + "Page.loadEventFired", + {} + ); + + expect(mockWs.send).not.toHaveBeenCalled(); + }); + + it("handles command errors", async () => { + chrome.debugger.attach.mockRejectedValue(new Error("Cannot attach")); + + const mockWs = new MockWebSocket("ws://test"); + const relay = new RelayConnection(mockWs, 10); + + await relay._onMessageAsync({ + data: JSON.stringify({ id: 1, method: "attachToTab", params: {} }), + }); + + const response = JSON.parse(mockWs.send.mock.calls[0][0]); + expect(response.id).toBe(1); + expect(response.error).toContain("Cannot attach"); + }); + + it("cleans up on close", () => { + chrome.debugger.detach.mockResolvedValue(undefined); + const mockWs = new MockWebSocket("ws://test"); + const relay = new RelayConnection(mockWs, 10); + mod._setActiveRelay(relay); + relay.onclose = () => { mod._setActiveRelay(null); }; + + relay.close("test"); + + expect(mockWs.close).toHaveBeenCalledWith(1000, "test"); + expect(chrome.debugger.detach).toHaveBeenCalledWith({ tabId: 10 }); + expect(getState().activeRelay).toBeNull(); + }); +}); + +describe("ensureAttached (recording)", () => { + it("attaches debugger", async () => { + chrome.debugger.attach.mockResolvedValue(undefined); + + await mod.ensureAttached(1); + + expect(chrome.debugger.attach).toHaveBeenCalledWith({ tabId: 1 }, "1.3"); + }); + + it("skips attach if already attached to same tab", async () => { + chrome.debugger.attach.mockResolvedValue(undefined); + + await mod.ensureAttached(1); + chrome.debugger.attach.mockClear(); + + await mod.ensureAttached(1); + expect(chrome.debugger.attach).not.toHaveBeenCalled(); + }); + + it("detaches previous tab before attaching new one", async () => { + chrome.debugger.attach.mockResolvedValue(undefined); + chrome.debugger.detach.mockResolvedValue(undefined); + + await mod.ensureAttached(1); + await mod.ensureAttached(2); + + expect(chrome.debugger.detach).toHaveBeenCalledWith({ tabId: 1 }); + expect(chrome.debugger.attach).toHaveBeenCalledWith({ tabId: 2 }, "1.3"); + }); +}); + +describe("startRecording", () => { + it("returns success when recording starts", async () => { + chrome.debugger.attach.mockResolvedValue(undefined); + chrome.debugger.sendCommand.mockResolvedValue({ identifier: "script-1" }); + + const result = await mod.startRecording(1); + + expect(result.success).toBe(true); + expect(getState().recording[1]).toBe(true); + }); + + it("injects recorder.js via CDP", async () => { + chrome.debugger.attach.mockResolvedValue(undefined); + chrome.debugger.sendCommand.mockResolvedValue({ identifier: "script-1" }); + + await mod.startRecording(1); + + const methods = chrome.debugger.sendCommand.mock.calls.map((c) => c[1]); + expect(methods).toContain("Page.enable"); + expect(methods).toContain("Page.addScriptToEvaluateOnNewDocument"); + expect(methods).toContain("Runtime.evaluate"); + }); + + it("returns error when attach fails", async () => { + chrome.debugger.attach.mockRejectedValue(new Error("Cannot attach")); + + const result = await mod.startRecording(1); + + expect(result.success).toBe(false); + expect(result.error).toContain("Cannot attach"); + }); +}); + +describe("stopRecording", () => { + it("returns success and clears recording state", async () => { + chrome.debugger.attach.mockResolvedValue(undefined); + chrome.debugger.sendCommand.mockResolvedValue(undefined); + + await mod.startRecording(1); + expect(getState().recording[1]).toBe(true); + + const result = await mod.stopRecording(1); + + expect(result.success).toBe(true); + expect(getState().recording[1]).toBe(false); + }); + + it("handles cleanup failure gracefully", async () => { + chrome.debugger.sendCommand.mockRejectedValue( + new Error("Context destroyed") + ); + + const result = await mod.stopRecording(1); + expect(result.success).toBe(true); + }); +}); + +describe("panel port management", () => { + it("registers panel port on connect", () => { + const mockPort = { + name: "pw-panel-42", + onDisconnect: { addListener: vi.fn() }, + }; + + chrome.runtime.onConnect.callListeners(mockPort); + + expect(getState().panelPorts[42]).toBe(mockPort); + }); + + it("removes panel port on disconnect", () => { + const disconnectCallbacks = []; + const mockPort = { + name: "pw-panel-42", + onDisconnect: { + addListener: (cb) => disconnectCallbacks.push(cb), + }, + }; + + chrome.runtime.onConnect.callListeners(mockPort); + expect(getState().panelPorts[42]).toBe(mockPort); + + disconnectCallbacks[0](); + expect(getState().panelPorts[42]).toBeUndefined(); + }); + + it("ignores non-panel ports", () => { + const mockPort = { + name: "other-port", + onDisconnect: { addListener: vi.fn() }, + }; + + chrome.runtime.onConnect.callListeners(mockPort); + expect(Object.keys(getState().panelPorts)).toHaveLength(0); + }); +}); diff --git a/packages/extension/test/converter.test.js b/packages/extension/test/converter.test.js new file mode 100644 index 0000000..4b4a8ca --- /dev/null +++ b/packages/extension/test/converter.test.js @@ -0,0 +1,289 @@ +import { describe, it, expect } from "vitest"; +import { tokenize, pwToPlaywright } from "../lib/converter.js"; + +describe("tokenize", () => { + it("tokenizes simple words", () => { + expect(tokenize("click Submit")).toEqual(["click", "Submit"]); + }); + + it("tokenizes double-quoted strings", () => { + expect(tokenize('fill "Email" "test@example.com"')).toEqual([ + "fill", + "Email", + "test@example.com", + ]); + }); + + it("tokenizes single-quoted strings", () => { + expect(tokenize("fill 'Username' 'alice'")).toEqual([ + "fill", + "Username", + "alice", + ]); + }); + + it("returns empty array for empty string", () => { + expect(tokenize("")).toEqual([]); + }); + + it("returns empty array for whitespace", () => { + expect(tokenize(" ")).toEqual([]); + }); + + it("returns empty array for comments", () => { + expect(tokenize("# a comment")).toEqual([]); + }); + + it("handles mixed quoted and unquoted", () => { + expect(tokenize('click "destroy" costco')).toEqual([ + "click", + "destroy", + "costco", + ]); + }); + + it("handles tabs as separators", () => { + expect(tokenize("goto\thttps://example.com")).toEqual([ + "goto", + "https://example.com", + ]); + }); + + it("handles quoted string with spaces", () => { + expect(tokenize('click "Sign In"')).toEqual(["click", "Sign In"]); + }); +}); + +describe("pwToPlaywright", () => { + it("returns null for empty string", () => { + expect(pwToPlaywright("")).toBeNull(); + }); + + it("returns null for comments", () => { + expect(pwToPlaywright("# comment")).toBeNull(); + }); + + // goto / open + it("converts goto with URL", () => { + expect(pwToPlaywright("goto https://example.com")).toBe( + 'await page.goto("https://example.com");' + ); + }); + + it("converts goto without protocol", () => { + expect(pwToPlaywright("goto example.com")).toBe( + 'await page.goto("https://example.com");' + ); + }); + + it("converts open alias", () => { + expect(pwToPlaywright("open https://example.com")).toBe( + 'await page.goto("https://example.com");' + ); + }); + + it("returns null for goto without URL", () => { + expect(pwToPlaywright("goto")).toBeNull(); + }); + + // click + it("converts click with text", () => { + expect(pwToPlaywright('click "Submit"')).toBe( + 'await page.getByText("Submit").click();' + ); + }); + + it("converts click with scope (second arg)", () => { + expect(pwToPlaywright('click "destroy" "costco"')).toBe( + 'await page.getByText("costco").getByText("destroy").click();' + ); + }); + + it("converts click with snapshot ref to comment", () => { + expect(pwToPlaywright("click e5")).toContain("snapshot ref"); + }); + + it("converts c alias", () => { + expect(pwToPlaywright('c "Submit"')).toBe( + 'await page.getByText("Submit").click();' + ); + }); + + it("returns null for click without target", () => { + expect(pwToPlaywright("click")).toBeNull(); + }); + + // dblclick + it("converts dblclick", () => { + expect(pwToPlaywright('dblclick "Item"')).toBe( + 'await page.getByText("Item").dblclick();' + ); + }); + + // fill + it("converts fill with label and value", () => { + expect(pwToPlaywright('fill "Email" "test@example.com"')).toBe( + 'await page.getByLabel("Email").fill("test@example.com");' + ); + }); + + it("converts f alias", () => { + expect(pwToPlaywright('f "Name" "Alice"')).toBe( + 'await page.getByLabel("Name").fill("Alice");' + ); + }); + + it("returns null for fill with missing value", () => { + expect(pwToPlaywright('fill "Email"')).toBeNull(); + }); + + // select + it("converts select", () => { + expect(pwToPlaywright('select "Country" "US"')).toBe( + 'await page.getByLabel("Country").selectOption("US");' + ); + }); + + // check / uncheck + it("converts check", () => { + expect(pwToPlaywright('check "Remember me"')).toBe( + 'await page.getByLabel("Remember me").check();' + ); + }); + + it("converts uncheck", () => { + expect(pwToPlaywright('uncheck "Terms"')).toBe( + 'await page.getByLabel("Terms").uncheck();' + ); + }); + + // hover + it("converts hover", () => { + expect(pwToPlaywright('hover "Menu"')).toBe( + 'await page.getByText("Menu").hover();' + ); + }); + + // press + it("converts press with capitalization", () => { + expect(pwToPlaywright("press enter")).toBe( + 'await page.keyboard.press("Enter");' + ); + }); + + it("converts p alias", () => { + expect(pwToPlaywright("p tab")).toBe( + 'await page.keyboard.press("Tab");' + ); + }); + + // screenshot + it("converts screenshot", () => { + expect(pwToPlaywright("screenshot")).toBe( + "await page.screenshot({ path: 'screenshot.png' });" + ); + }); + + it("converts screenshot full", () => { + expect(pwToPlaywright("screenshot full")).toBe( + "await page.screenshot({ path: 'screenshot.png', fullPage: true });" + ); + }); + + // snapshot + it("converts snapshot to comment", () => { + expect(pwToPlaywright("snapshot")).toContain("// snapshot"); + }); + + it("converts s alias to comment", () => { + expect(pwToPlaywright("s")).toContain("// snapshot"); + }); + + // eval + it("converts eval", () => { + expect(pwToPlaywright("eval document.title")).toBe( + "await page.evaluate(() => document.title);" + ); + }); + + // navigation + it("converts go-back", () => { + expect(pwToPlaywright("go-back")).toBe("await page.goBack();"); + }); + + it("converts back alias", () => { + expect(pwToPlaywright("back")).toBe("await page.goBack();"); + }); + + it("converts go-forward", () => { + expect(pwToPlaywright("go-forward")).toBe("await page.goForward();"); + }); + + it("converts forward alias", () => { + expect(pwToPlaywright("forward")).toBe("await page.goForward();"); + }); + + it("converts reload", () => { + expect(pwToPlaywright("reload")).toBe("await page.reload();"); + }); + + // verify commands + it("converts verify-text", () => { + expect(pwToPlaywright('verify-text "Hello"')).toBe( + 'await expect(page.getByText("Hello")).toBeVisible();' + ); + }); + + it("converts verify-no-text", () => { + expect(pwToPlaywright('verify-no-text "Gone"')).toBe( + 'await expect(page.getByText("Gone")).not.toBeVisible();' + ); + }); + + it("converts verify-element", () => { + expect(pwToPlaywright('verify-element "Submit"')).toBe( + 'await expect(page.getByText("Submit")).toBeVisible();' + ); + }); + + it("converts verify-no-element", () => { + expect(pwToPlaywright('verify-no-element "Deleted"')).toBe( + 'await expect(page.getByText("Deleted")).not.toBeVisible();' + ); + }); + + it("converts verify-url", () => { + expect(pwToPlaywright('verify-url "dashboard"')).toBe( + "await expect(page).toHaveURL(/dashboard/);" + ); + }); + + it("converts verify-url with regex special chars", () => { + expect(pwToPlaywright('verify-url "example.com/path"')).toBe( + "await expect(page).toHaveURL(/example\\.com\\/path/);" + ); + }); + + it("converts verify-title", () => { + expect(pwToPlaywright('verify-title "My App"')).toBe( + "await expect(page).toHaveTitle(/My App/);" + ); + }); + + it("returns null for verify-text without arg", () => { + expect(pwToPlaywright("verify-text")).toBeNull(); + }); + + it("returns null for verify-url without arg", () => { + expect(pwToPlaywright("verify-url")).toBeNull(); + }); + + it("returns null for verify-title without arg", () => { + expect(pwToPlaywright("verify-title")).toBeNull(); + }); + + // unknown + it("converts unknown command to comment", () => { + expect(pwToPlaywright("foobar")).toBe("// unknown command: foobar"); + }); +}); diff --git a/packages/extension/test/devtools.test.js b/packages/extension/test/devtools.test.js new file mode 100644 index 0000000..861d7a3 --- /dev/null +++ b/packages/extension/test/devtools.test.js @@ -0,0 +1,14 @@ +import { describe, it, expect } from "vitest"; +import { chrome } from "vitest-chrome/lib/index.esm.js"; + +describe("devtools.js", () => { + it("registers a DevTools panel", async () => { + await import("../devtools.js"); + + expect(chrome.devtools.panels.create).toHaveBeenCalledWith( + "Playwright REPL", + "icons/icon16.png", + "panel/panel.html" + ); + }); +}); diff --git a/packages/extension/test/panel.test.js b/packages/extension/test/panel.test.js new file mode 100644 index 0000000..1159916 --- /dev/null +++ b/packages/extension/test/panel.test.js @@ -0,0 +1,1725 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { chrome } from "vitest-chrome/lib/index.esm.js"; + +let mockPort; + +describe("panel.js", () => { + beforeEach(() => { + vi.restoreAllMocks(); + vi.resetModules(); + + // Clear chrome event listeners accumulated from re-imports + chrome.runtime.onConnect.clearListeners(); + chrome.runtime.onMessage.clearListeners(); + chrome.runtime.sendMessage.mockReset(); + chrome.runtime.connect.mockReset(); + + // Set up the DOM that panel.js expects (split editor/REPL layout) + document.body.innerHTML = ` +
+
+ + + + + + + + +
+
+ +
+
+
+
+
+
+ +
+
+
+
+
+ + Terminal + + + +
+
+
+ pw> +
+ + + +
+
+
+ + `; + + // Remove any theme class from previous test + document.body.classList.remove("theme-dark"); + + // Mock chrome.devtools.inspectedWindow.tabId + chrome.devtools = { + inspectedWindow: { tabId: 42 }, + panels: { create: vi.fn(), themeName: "default" }, + }; + + // Mock chrome.runtime.connect to return a port-like object + mockPort = { + onMessage: { addListener: vi.fn() }, + postMessage: vi.fn(), + onDisconnect: { addListener: vi.fn() }, + name: "pw-panel-42", + }; + chrome.runtime.id = "mock-extension-id"; + chrome.runtime.connect.mockReturnValue(mockPort); + chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); + }); + + // --- Init --- + + it("renders welcome message on load", async () => { + await import("../panel/panel.js"); + const output = document.getElementById("output"); + expect(output.textContent).toContain("Playwright REPL v1.0.0"); + expect(output.textContent).toContain("editor"); + }); + + it("connects to background via port", async () => { + await import("../panel/panel.js"); + expect(chrome.runtime.connect).toHaveBeenCalledWith({ + name: "pw-panel-42", + }); + }); + + it("reconnects port when service worker restarts", async () => { + await import("../panel/panel.js"); + // Grab the onDisconnect callback that panel.js registered + const disconnectCb = mockPort.onDisconnect.addListener.mock.calls[0][0]; + // Simulate service worker restart (port disconnects) + vi.useFakeTimers(); + disconnectCb(); + vi.advanceTimersByTime(500); + // Should have reconnected + expect(chrome.runtime.connect).toHaveBeenCalledTimes(2); + vi.useRealTimers(); + }); + + it("focuses the editor on load", async () => { + const editor = document.getElementById("editor"); + const focusSpy = vi.spyOn(editor, "focus"); + await import("../panel/panel.js"); + expect(focusSpy).toHaveBeenCalled(); + }); + + it("has disabled copy, save, and export buttons initially", async () => { + await import("../panel/panel.js"); + expect(document.getElementById("copy-btn").disabled).toBe(true); + expect(document.getElementById("save-btn").disabled).toBe(true); + expect(document.getElementById("export-btn").disabled).toBe(true); + }); + + it("has enabled open button", async () => { + await import("../panel/panel.js"); + expect(document.getElementById("open-btn").disabled).toBe(false); + }); + + // --- Theme --- + + it("defaults to light theme (no theme-dark class)", async () => { + chrome.devtools.panels.themeName = "default"; + await import("../panel/panel.js"); + expect(document.body.classList.contains("theme-dark")).toBe(false); + }); + + it("applies dark theme when DevTools theme is dark", async () => { + chrome.devtools.panels.themeName = "dark"; + await import("../panel/panel.js"); + expect(document.body.classList.contains("theme-dark")).toBe(true); + }); + + it("applies light theme when themeName is undefined", async () => { + chrome.devtools.panels.themeName = undefined; + await import("../panel/panel.js"); + expect(document.body.classList.contains("theme-dark")).toBe(false); + }); + + // --- Line numbers --- + + it("renders line numbers for editor content", async () => { + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com\nclick \"OK\"\npress Enter"; + editor.dispatchEvent(new Event("input")); + const lineNums = document.getElementById("line-numbers"); + const divs = lineNums.querySelectorAll("div"); + expect(divs.length).toBe(3); + expect(divs[0].textContent).toBe("1"); + expect(divs[1].textContent).toBe("2"); + expect(divs[2].textContent).toBe("3"); + }); + + it("shows file info with line count", async () => { + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com\nclick \"OK\""; + editor.dispatchEvent(new Event("input")); + const fileInfo = document.getElementById("file-info"); + expect(fileInfo.textContent).toContain("2 lines"); + }); + + // --- REPL input --- + + it("sends command to background on Enter key", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + input.value = "help"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + await vi.waitFor(() => { + expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ + type: "pw-command", + raw: "help", + tabId: 42, + }); + }); + }); + + it("clears input after Enter", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + input.value = "snapshot"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + expect(input.value).toBe(""); + }); + + it("does not send empty commands", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + input.value = " "; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + expect(chrome.runtime.sendMessage).not.toHaveBeenCalled(); + }); + + // --- Response display (legacy format) --- + + it("displays success response in output", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "Navigated to https://example.com" }); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + input.value = "goto https://example.com"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + await vi.waitFor(() => { + const output = document.getElementById("output"); + expect(output.textContent).toContain("Navigated to https://example.com"); + }); + }); + + it("displays error response in output", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "error", data: "Element not found" }); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + input.value = 'click "Missing"'; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + await vi.waitFor(() => { + const output = document.getElementById("output"); + expect(output.textContent).toContain("Element not found"); + }); + }); + + it("displays snapshot lines in output", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "snapshot", data: '- button "OK" [ref=e1]\n- link "Home" [ref=e2]' }); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + input.value = "snapshot"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + await vi.waitFor(() => { + const output = document.getElementById("output"); + expect(output.textContent).toContain("button"); + expect(output.textContent).toContain("link"); + }); + }); + + it("displays screenshot as image in output", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "screenshot", data: "fakebase64" }); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + input.value = "screenshot"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + await vi.waitFor(() => { + const img = document.querySelector("img"); + expect(img).not.toBeNull(); + expect(img.src).toContain("fakebase64"); + }); + }); + + it("displays info response in output", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "info", data: "Available commands:" }); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + input.value = "help"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + await vi.waitFor(() => { + const output = document.getElementById("output"); + expect(output.textContent).toContain("Available commands:"); + }); + }); + + // --- Engine format: { text, isError } --- + + it("displays Engine success result in output", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ text: "Clicked", isError: false }); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + input.value = 'click "OK"'; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + await vi.waitFor(() => { + const output = document.getElementById("output"); + expect(output.textContent).toContain("Clicked"); + }); + }); + + it("displays Engine error result in output", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ text: "Element not found", isError: true }); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + input.value = 'click "Missing"'; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + await vi.waitFor(() => { + const output = document.getElementById("output"); + expect(output.textContent).toContain("Element not found"); + }); + }); + + // --- Error handling --- + + it("handles null response from background", async () => { + chrome.runtime.sendMessage.mockResolvedValue(null); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + input.value = "snapshot"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + await vi.waitFor(() => { + const output = document.getElementById("output"); + expect(output.textContent).toContain("No response"); + }); + }); + + it("handles sendMessage rejection", async () => { + chrome.runtime.sendMessage.mockRejectedValue(new Error("Disconnected")); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + input.value = "snapshot"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + await vi.waitFor(() => { + const output = document.getElementById("output"); + expect(output.textContent).toContain("Error: Disconnected"); + }); + }); + + it("displays comments without sending to background", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + input.value = "# this is a comment"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + const output = document.getElementById("output"); + expect(output.textContent).toContain("# this is a comment"); + expect(chrome.runtime.sendMessage).not.toHaveBeenCalled(); + }); + + // --- History --- + + it("navigates command history with ArrowUp/ArrowDown", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + + input.value = "help"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + input.value = "snapshot"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true })); + expect(input.value).toBe("snapshot"); + + input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true })); + expect(input.value).toBe("help"); + + input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })); + expect(input.value).toBe("snapshot"); + + input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })); + expect(input.value).toBe(""); + }); + + // --- Copy/Save/Export tied to editor --- + + it("enables copy, save, export when editor has content", async () => { + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com"; + editor.dispatchEvent(new Event("input")); + + expect(document.getElementById("copy-btn").disabled).toBe(false); + expect(document.getElementById("save-btn").disabled).toBe(false); + expect(document.getElementById("export-btn").disabled).toBe(false); + }); + + it("disables copy, save, export when editor is empty", async () => { + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com"; + editor.dispatchEvent(new Event("input")); + expect(document.getElementById("copy-btn").disabled).toBe(false); + + editor.value = ""; + editor.dispatchEvent(new Event("input")); + expect(document.getElementById("copy-btn").disabled).toBe(true); + expect(document.getElementById("save-btn").disabled).toBe(true); + expect(document.getElementById("export-btn").disabled).toBe(true); + }); + + // --- Copy --- + + it("copy button copies editor content to clipboard", async () => { + document.execCommand = vi.fn().mockReturnValue(true); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com\nclick \"OK\""; + editor.dispatchEvent(new Event("input")); + + document.getElementById("copy-btn").click(); + expect(document.execCommand).toHaveBeenCalledWith("copy"); + expect(document.getElementById("output").textContent).toContain("copied"); + }); + + it("copy button shows message when editor is empty", async () => { + await import("../panel/panel.js"); + document.getElementById("copy-btn").disabled = false; + document.getElementById("copy-btn").click(); + expect(document.getElementById("output").textContent).toContain("Nothing to copy"); + }); + + // --- Export --- + + it("export button converts editor to Playwright code", async () => { + await import("../panel/panel.js"); + document.execCommand = vi.fn().mockReturnValue(true); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com\nclick \"Submit\""; + editor.dispatchEvent(new Event("input")); + + document.getElementById("export-btn").click(); + const output = document.getElementById("output"); + const codeBlock = output.querySelector(".code-block"); + expect(codeBlock).not.toBeNull(); + expect(codeBlock.textContent).toContain("@playwright/test"); + expect(codeBlock.querySelector(".code-copy-btn")).not.toBeNull(); + }); + + it("export command in REPL reads from editor", async () => { + await import("../panel/panel.js"); + document.execCommand = vi.fn().mockReturnValue(true); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com"; + editor.dispatchEvent(new Event("input")); + + const input = document.getElementById("command-input"); + input.value = "export"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + const output = document.getElementById("output"); + const codeBlock = output.querySelector(".code-block"); + expect(codeBlock).not.toBeNull(); + expect(codeBlock.textContent).toContain("@playwright/test"); + }); + + it("export shows nothing when editor is empty", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + input.value = "export"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + const output = document.getElementById("output"); + expect(output.textContent).toContain("Nothing to export"); + }); + + it("export single command converts to Playwright", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + input.value = 'export click "Submit"'; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + const output = document.getElementById("output"); + expect(output.textContent).toContain("click"); + }); + + // --- Recording --- + + it("record button toggles recording state", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ success: true }); + await import("../panel/panel.js"); + const recordBtn = document.getElementById("record-btn"); + + recordBtn.click(); + await vi.waitFor(() => { + expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ + type: "pw-record-start", + tabId: 42, + }); + }); + expect(recordBtn.classList.contains("recording")).toBe(true); + expect(recordBtn.textContent).toContain("Stop"); + }); + + it("record button stops recording on second click", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ success: true }); + await import("../panel/panel.js"); + const recordBtn = document.getElementById("record-btn"); + + recordBtn.click(); + await vi.waitFor(() => { + expect(recordBtn.classList.contains("recording")).toBe(true); + }); + + recordBtn.click(); + await vi.waitFor(() => { + expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ + type: "pw-record-stop", + tabId: 42, + }); + }); + expect(recordBtn.classList.contains("recording")).toBe(false); + expect(recordBtn.textContent).toContain("Record"); + }); + + it("record button reverts on failure", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ success: false, error: "Failed" }); + await import("../panel/panel.js"); + const recordBtn = document.getElementById("record-btn"); + + recordBtn.click(); + await vi.waitFor(() => { + expect(recordBtn.classList.contains("recording")).toBe(false); + expect(recordBtn.textContent).toContain("Record"); + }); + expect(document.getElementById("output").textContent).toContain("Failed to start recording"); + }); + + it("recorded commands append to editor", async () => { + await import("../panel/panel.js"); + const onMessageCallback = mockPort.onMessage.addListener.mock.calls[0][0]; + onMessageCallback({ type: "pw-recorded-command", command: 'click "Submit"' }); + const editor = document.getElementById("editor"); + expect(editor.value).toContain('click "Submit"'); + expect(document.getElementById("copy-btn").disabled).toBe(false); + }); + + // --- Run button --- + + it("run button executes editor lines", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com\nclick \"OK\""; + editor.dispatchEvent(new Event("input")); + + document.getElementById("run-btn").click(); + await vi.waitFor(() => { + const output = document.getElementById("output"); + expect(output.textContent).toContain("Running script..."); + expect(output.textContent).toContain("Run complete."); + }); + + expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ + type: "pw-command", + raw: "goto https://example.com", + tabId: 42, + }); + expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ + type: "pw-command", + raw: 'click "OK"', + tabId: 42, + }); + }); + + it("run button shows pass/fail stats", async () => { + let callCount = 0; + chrome.runtime.sendMessage.mockImplementation(() => { + callCount++; + if (callCount === 1) return Promise.resolve({ type: "success", data: "OK" }); + return Promise.resolve({ type: "error", data: "Not found" }); + }); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com\nclick \"Missing\""; + editor.dispatchEvent(new Event("input")); + + document.getElementById("run-btn").click(); + await vi.waitFor(() => { + const stats = document.getElementById("console-stats"); + expect(stats.textContent).toContain("1 passed"); + expect(stats.textContent).toContain("1 failed"); + }); + }); + + it("run button shows message for empty editor", async () => { + await import("../panel/panel.js"); + document.getElementById("run-btn").click(); + const output = document.getElementById("output"); + expect(output.textContent).toContain("Editor is empty"); + }); + + it("run button skips empty lines and comments", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "# comment\n\ngoto https://example.com"; + editor.dispatchEvent(new Event("input")); + + document.getElementById("run-btn").click(); + await vi.waitFor(() => { + expect(document.getElementById("output").textContent).toContain("Run complete."); + }); + const pwCalls = chrome.runtime.sendMessage.mock.calls.filter( + (c) => c[0].type === "pw-command" + ); + expect(pwCalls.length).toBe(1); + expect(pwCalls[0][0].raw).toBe("goto https://example.com"); + }); + + // --- Ctrl+Enter --- + + it("Ctrl+Enter in editor triggers run", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com"; + editor.dispatchEvent(new Event("input")); + + editor.dispatchEvent(new KeyboardEvent("keydown", { + key: "Enter", + ctrlKey: true, + bubbles: true, + })); + + await vi.waitFor(() => { + expect(document.getElementById("output").textContent).toContain("Running script..."); + }); + }); + + // --- Console commands (history, clear, reset) --- + + it("history command displays history in terminal", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + + input.value = "help"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + input.value = "snapshot"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + await vi.waitFor(() => { + expect(chrome.runtime.sendMessage).toHaveBeenCalledTimes(2); + }); + + input.value = "history"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + const output = document.getElementById("output"); + expect(output.textContent).toContain("help"); + expect(output.textContent).toContain("snapshot"); + expect(document.getElementById("editor").value).toBe(""); + }); + + it("history command shows info when history is empty", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + + input.value = "history"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + expect(document.getElementById("output").textContent).toContain("No command history"); + }); + + it("history command is not added to history itself", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + + input.value = "help"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + input.value = "history"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true })); + expect(input.value).toBe("help"); + }); + + it("history command is not sent to background", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + + input.value = "history"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + expect(chrome.runtime.sendMessage).not.toHaveBeenCalled(); + }); + + it("clear command clears console output", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "Done" }); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + + input.value = "help"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + await vi.waitFor(() => { + expect(document.getElementById("output").textContent).toContain("Done"); + }); + + input.value = "clear"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + expect(document.getElementById("output").innerHTML).toBe(""); + }); + + it("clear command is not sent to background", async () => { + await import("../panel/panel.js"); + chrome.runtime.sendMessage.mockClear(); + const input = document.getElementById("command-input"); + + input.value = "clear"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + expect(chrome.runtime.sendMessage).not.toHaveBeenCalled(); + }); + + it("clear command is not added to history", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + + input.value = "help"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + input.value = "clear"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true })); + expect(input.value).toBe("help"); + }); + + it("reset command clears history and console", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "Done" }); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + + input.value = "help"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + await vi.waitFor(() => { + expect(document.getElementById("output").textContent).toContain("Done"); + }); + + input.value = "reset"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + expect(document.getElementById("output").textContent).toContain("History and terminal cleared"); + + input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true })); + expect(input.value).toBe(""); + }); + + it("reset command is not added to history", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + + input.value = "help"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + input.value = "reset"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true })); + expect(input.value).toBe(""); + }); + + // --- Console header clear button --- + + it("console header clear button clears output", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "Done" }); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + input.value = "help"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + await vi.waitFor(() => { + expect(document.getElementById("output").textContent).toContain("Done"); + }); + + document.getElementById("console-clear-btn").click(); + expect(document.getElementById("output").innerHTML).toBe(""); + }); + + it("console header clear button resets pass/fail stats", async () => { + let callCount = 0; + chrome.runtime.sendMessage.mockImplementation(() => { + callCount++; + if (callCount === 1) return Promise.resolve({ type: "success", data: "OK" }); + return Promise.resolve({ type: "error", data: "Not found" }); + }); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com\nclick \"Missing\""; + editor.dispatchEvent(new Event("input")); + + document.getElementById("run-btn").click(); + await vi.waitFor(() => { + const stats = document.getElementById("console-stats"); + expect(stats.textContent).toContain("1 passed"); + }); + + document.getElementById("console-clear-btn").click(); + expect(document.getElementById("console-stats").textContent).toBe(""); + }); + + // --- Step button --- + + it("step button executes the first executable line", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com\nclick \"OK\""; + editor.dispatchEvent(new Event("input")); + + document.getElementById("step-btn").click(); + await vi.waitFor(() => { + expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ + type: "pw-command", + raw: "goto https://example.com", + tabId: 42, + }); + }); + }); + + it("step button skips empty lines and comments", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "# comment\n\ngoto https://example.com"; + editor.dispatchEvent(new Event("input")); + + document.getElementById("step-btn").click(); + await vi.waitFor(() => { + expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ + type: "pw-command", + raw: "goto https://example.com", + tabId: 42, + }); + }); + }); + + it("step button advances to next line on subsequent clicks", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com\nclick \"OK\""; + editor.dispatchEvent(new Event("input")); + + document.getElementById("step-btn").click(); + await vi.waitFor(() => { + expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ + type: "pw-command", + raw: "goto https://example.com", + tabId: 42, + }); + }); + + await vi.waitFor(() => { + expect(document.getElementById("step-btn").disabled).toBe(false); + }); + + chrome.runtime.sendMessage.mockClear(); + document.getElementById("step-btn").click(); + await vi.waitFor(() => { + expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ + type: "pw-command", + raw: 'click "OK"', + tabId: 42, + }); + }); + }); + + it("step button shows message for empty editor", async () => { + await import("../panel/panel.js"); + document.getElementById("step-btn").click(); + expect(document.getElementById("output").textContent).toContain("Editor is empty"); + }); + + it("step button shows complete message after last line", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com"; + editor.dispatchEvent(new Event("input")); + + document.getElementById("step-btn").click(); + await vi.waitFor(() => { + expect(document.getElementById("output").textContent).toContain("Step complete"); + }); + }); + + it("step state resets when editor content changes", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com\nclick \"OK\""; + editor.dispatchEvent(new Event("input")); + + document.getElementById("step-btn").click(); + await vi.waitFor(() => { + expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ + type: "pw-command", + raw: "goto https://example.com", + tabId: 42, + }); + }); + + await vi.waitFor(() => { + expect(document.getElementById("step-btn").disabled).toBe(false); + }); + + editor.value = "goto https://other.com"; + editor.dispatchEvent(new Event("input")); + + chrome.runtime.sendMessage.mockClear(); + document.getElementById("step-btn").click(); + await vi.waitFor(() => { + expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ + type: "pw-command", + raw: "goto https://other.com", + tabId: 42, + }); + }); + }); + + // --- Autocomplete --- + + it("ghost text shows completion hint while typing", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + const ghost = document.getElementById("ghost-text"); + + input.value = "go"; + input.dispatchEvent(new Event("input", { bubbles: true })); + expect(ghost.textContent).toBe("to"); + }); + + it("ghost text shows hint for screenshot", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + const ghost = document.getElementById("ghost-text"); + + input.value = "scr"; + input.dispatchEvent(new Event("input", { bubbles: true })); + expect(ghost.textContent).toBe("eenshot"); + }); + + it("ghost text clears when full command is typed", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + const ghost = document.getElementById("ghost-text"); + + input.value = "goto"; + input.dispatchEvent(new Event("input", { bubbles: true })); + expect(ghost.textContent).toBe(""); + }); + + it("ghost text clears when space is typed after command", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + const ghost = document.getElementById("ghost-text"); + + input.value = "goto "; + input.dispatchEvent(new Event("input", { bubbles: true })); + expect(ghost.textContent).toBe(""); + }); + + it("ghost text clears on empty input", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + const ghost = document.getElementById("ghost-text"); + + input.value = ""; + input.dispatchEvent(new Event("input", { bubbles: true })); + expect(ghost.textContent).toBe(""); + }); + + it("Tab completes single matching command", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + + input.value = "scr"; + input.dispatchEvent(new Event("input", { bubbles: true })); + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true })); + expect(input.value).toBe("screenshot "); + }); + + it("dropdown shows for multiple matches", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + const dd = document.getElementById("autocomplete-dropdown"); + + input.value = "go"; + input.dispatchEvent(new Event("input", { bubbles: true })); + + expect(dd.hidden).toBe(false); + expect(dd.querySelectorAll(".autocomplete-item").length).toBeGreaterThan(1); + }); + + it("Tab selects first dropdown item when dropdown is open", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + const dd = document.getElementById("autocomplete-dropdown"); + + input.value = "go"; + input.dispatchEvent(new Event("input", { bubbles: true })); + expect(dd.hidden).toBe(false); + + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true })); + expect(input.value.startsWith("go")).toBe(true); + expect(input.value.endsWith(" ")).toBe(true); + expect(dd.hidden).toBe(true); + }); + + it("ArrowDown navigates dropdown items", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + const dd = document.getElementById("autocomplete-dropdown"); + + input.value = "go"; + input.dispatchEvent(new Event("input", { bubbles: true })); + expect(dd.hidden).toBe(false); + + input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })); + const items = dd.querySelectorAll(".autocomplete-item"); + expect(items[0].classList.contains("active")).toBe(true); + }); + + it("Enter selects highlighted dropdown item", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + const dd = document.getElementById("autocomplete-dropdown"); + + input.value = "go"; + input.dispatchEvent(new Event("input", { bubbles: true })); + + input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })); + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + expect(input.value.startsWith("go")).toBe(true); + expect(input.value.endsWith(" ")).toBe(true); + expect(dd.hidden).toBe(true); + }); + + it("Escape closes dropdown", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + const dd = document.getElementById("autocomplete-dropdown"); + + input.value = "go"; + input.dispatchEvent(new Event("input", { bubbles: true })); + expect(dd.hidden).toBe(false); + + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); + expect(dd.hidden).toBe(true); + }); + + it("dropdown hides when single match remains", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + const dd = document.getElementById("autocomplete-dropdown"); + + input.value = "scr"; + input.dispatchEvent(new Event("input", { bubbles: true })); + expect(dd.hidden).toBe(true); + }); + + it("clicking dropdown item selects it", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + const dd = document.getElementById("autocomplete-dropdown"); + + input.value = "go"; + input.dispatchEvent(new Event("input", { bubbles: true })); + expect(dd.hidden).toBe(false); + + const firstItem = dd.querySelector(".autocomplete-item"); + firstItem.dispatchEvent(new Event("mousedown", { bubbles: true })); + expect(input.value.endsWith(" ")).toBe(true); + expect(dd.hidden).toBe(true); + }); + + it("Enter clears ghost text", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + const ghost = document.getElementById("ghost-text"); + + input.value = "go"; + input.dispatchEvent(new Event("input", { bubbles: true })); + expect(ghost.textContent).not.toBe(""); + + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + expect(ghost.textContent).toBe(""); + }); + + it("ArrowUp clears ghost text when no dropdown", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + const ghost = document.getElementById("ghost-text"); + + input.value = "scr"; + input.dispatchEvent(new Event("input", { bubbles: true })); + expect(ghost.textContent).not.toBe(""); + + input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true })); + expect(ghost.textContent).toBe(""); + }); + + it("ArrowDown clears ghost text when no dropdown", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + const ghost = document.getElementById("ghost-text"); + + input.value = "scr"; + input.dispatchEvent(new Event("input", { bubbles: true })); + expect(ghost.textContent).not.toBe(""); + + input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })); + expect(ghost.textContent).toBe(""); + }); + + // ─── Engine format (executeCommand & executeCommandForRun) ──────────────── + + it("REPL handles Engine format screenshot response", async () => { + const fakeData = "data:image/png;base64,AAAA"; + chrome.runtime.sendMessage.mockResolvedValue({ text: fakeData, isError: false }); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + + input.value = "screenshot"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + await vi.waitFor(() => { + expect(document.querySelector(".screenshot-block")).toBeTruthy(); + }); + }); + + it("REPL handles Engine format snapshot response", async () => { + const snap = "- heading [ref=e1]\n- button [ref=e2]"; + chrome.runtime.sendMessage.mockResolvedValue({ text: snap, isError: false }); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + + input.value = "snapshot"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + await vi.waitFor(() => { + expect(document.querySelectorAll(".line-snapshot").length).toBeGreaterThanOrEqual(1); + }); + }); + + it("REPL handles null response from background", async () => { + chrome.runtime.sendMessage.mockResolvedValue(null); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + + input.value = "goto https://example.com"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + await vi.waitFor(() => { + expect(document.getElementById("output").textContent).toContain("No response"); + }); + }); + + it("REPL handles legacy default type response", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "other", data: "Some data" }); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + + input.value = "help"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + await vi.waitFor(() => { + expect(document.getElementById("output").textContent).toContain("Some data"); + }); + }); + + it("REPL export command shows conversion for unknown commands", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + + input.value = "export totally-invalid-command"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + await vi.waitFor(() => { + expect(document.getElementById("output").textContent).toContain("unknown command"); + }); + }); + + // ─── Engine format in executeCommandForRun ──────────────────────────────── + + it("run button handles Engine format error in run mode", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ text: "Element not found", isError: true }); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = 'click "missing"'; + editor.dispatchEvent(new Event("input")); + + document.getElementById("run-btn").click(); + await vi.waitFor(() => { + const stats = document.getElementById("console-stats"); + expect(stats.textContent).toContain("1 failed"); + }); + }); + + it("run button handles Engine format screenshot in run mode", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ + text: "data:image/png;base64,AAAA", + isError: false, + }); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "screenshot"; + editor.dispatchEvent(new Event("input")); + + document.getElementById("run-btn").click(); + await vi.waitFor(() => { + expect(document.querySelector(".screenshot-block")).toBeTruthy(); + }); + }); + + it("run button handles Engine format snapshot in run mode", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ + text: "- heading [ref=e1]\n- button [ref=e2]", + isError: false, + }); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "snapshot"; + editor.dispatchEvent(new Event("input")); + + document.getElementById("run-btn").click(); + await vi.waitFor(() => { + expect(document.querySelectorAll(".line-snapshot").length).toBeGreaterThanOrEqual(1); + }); + }); + + it("run button handles null result in run mode", async () => { + chrome.runtime.sendMessage.mockResolvedValue(null); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com"; + editor.dispatchEvent(new Event("input")); + + document.getElementById("run-btn").click(); + await vi.waitFor(() => { + expect(document.getElementById("output").textContent).toContain("No response"); + }); + }); + + it("run button handles legacy info type in run mode", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "info", data: "Page loaded" }); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com"; + editor.dispatchEvent(new Event("input")); + + document.getElementById("run-btn").click(); + await vi.waitFor(() => { + expect(document.getElementById("output").textContent).toContain("Page loaded"); + }); + }); + + it("run button handles legacy snapshot type in run mode", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ + type: "snapshot", + data: "- heading [ref=e1]\n- button [ref=e2]", + }); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "snapshot"; + editor.dispatchEvent(new Event("input")); + + document.getElementById("run-btn").click(); + await vi.waitFor(() => { + expect(document.querySelectorAll(".line-snapshot").length).toBeGreaterThanOrEqual(1); + }); + }); + + it("run button handles legacy screenshot type in run mode", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ + type: "screenshot", + data: "AAAA", + }); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "screenshot"; + editor.dispatchEvent(new Event("input")); + + document.getElementById("run-btn").click(); + await vi.waitFor(() => { + expect(document.querySelector(".screenshot-block")).toBeTruthy(); + }); + }); + + it("run button handles legacy default type in run mode", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "other", data: "OK done" }); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com"; + editor.dispatchEvent(new Event("input")); + + document.getElementById("run-btn").click(); + await vi.waitFor(() => { + expect(document.getElementById("output").textContent).toContain("OK done"); + }); + }); + + it("run button handles sendMessage exception in run mode", async () => { + chrome.runtime.sendMessage.mockRejectedValue(new Error("Connection lost")); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com"; + editor.dispatchEvent(new Event("input")); + + document.getElementById("run-btn").click(); + await vi.waitFor(() => { + expect(document.getElementById("output").textContent).toContain("Connection lost"); + }); + }); + + // ─── Run button stop ───────────────────────────────────────────────────── + + it("run button can be stopped while running", async () => { + let resolveFirst; + chrome.runtime.sendMessage.mockImplementation( + () => new Promise((r) => { resolveFirst = r; }) + ); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com\nclick \"OK\""; + editor.dispatchEvent(new Event("input")); + + const runBtn = document.getElementById("run-btn"); + runBtn.click(); + + // Wait for isRunning to be true (button changes text) + await vi.waitFor(() => { + expect(runBtn.textContent).toContain("\u25A0"); // stop symbol + }); + + // Click stop + runBtn.click(); + await vi.waitFor(() => { + expect(document.getElementById("output").textContent).toContain("Run stopped"); + }); + + // Resolve the pending command + resolveFirst({ type: "success", data: "Done" }); + }); + + // ─── Tab on empty input ─────────────────────────────────────────────────── + + it("Tab on empty input shows all commands", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + const dd = document.getElementById("autocomplete-dropdown"); + + input.value = ""; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true })); + expect(dd.hidden).toBe(false); + expect(dd.querySelectorAll(".autocomplete-item").length).toBeGreaterThan(5); + }); + + it("Tab with multiple matches shows dropdown", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + const dd = document.getElementById("autocomplete-dropdown"); + + input.value = "go"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true })); + expect(dd.hidden).toBe(false); + }); + + // ─── Ctrl+Space autocomplete ────────────────────────────────────────────── + + it("Ctrl+Space shows all commands when input is empty", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + const dd = document.getElementById("autocomplete-dropdown"); + + input.value = ""; + input.dispatchEvent( + new KeyboardEvent("keydown", { key: " ", ctrlKey: true, bubbles: true }) + ); + expect(dd.hidden).toBe(false); + expect(dd.querySelectorAll(".autocomplete-item").length).toBeGreaterThan(5); + }); + + it("Ctrl+Space shows filtered commands when typing", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + const dd = document.getElementById("autocomplete-dropdown"); + + input.value = "go"; + input.dispatchEvent( + new KeyboardEvent("keydown", { key: " ", ctrlKey: true, bubbles: true }) + ); + expect(dd.hidden).toBe(false); + expect(dd.querySelectorAll(".autocomplete-item").length).toBeGreaterThanOrEqual(1); + }); + + it("Ctrl+Space does nothing when input has space", async () => { + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + const dd = document.getElementById("autocomplete-dropdown"); + + input.value = "goto https://example.com"; + input.dispatchEvent( + new KeyboardEvent("keydown", { key: " ", ctrlKey: true, bubbles: true }) + ); + expect(dd.hidden).toBe(true); + }); + + // ─── Screenshot & lightbox interactions ─────────────────────────────────── + + it("screenshot image click opens lightbox", async () => { + const fakeData = "data:image/png;base64,AAAA"; + chrome.runtime.sendMessage.mockResolvedValue({ text: fakeData, isError: false }); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + + input.value = "screenshot"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + await vi.waitFor(() => { + expect(document.querySelector(".screenshot-block img")).toBeTruthy(); + }); + + document.querySelector(".screenshot-block img").click(); + expect(document.getElementById("lightbox").hidden).toBe(false); + expect(document.getElementById("lightbox-img").src).toContain("AAAA"); + }); + + it("screenshot save button triggers download", async () => { + const fakeData = "data:image/png;base64,AAAA"; + chrome.runtime.sendMessage.mockResolvedValue({ text: fakeData, isError: false }); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + + input.value = "screenshot"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + await vi.waitFor(() => { + expect(document.querySelector(".screenshot-btn")).toBeTruthy(); + }); + + // Click save button — just verify no error is thrown + document.querySelector(".screenshot-btn").click(); + }); + + it("lightbox closes when clicking backdrop", async () => { + await import("../panel/panel.js"); + const lightbox = document.getElementById("lightbox"); + lightbox.hidden = false; + + lightbox.dispatchEvent(new MouseEvent("click", { bubbles: true })); + expect(lightbox.hidden).toBe(true); + }); + + it("lightbox does not close when clicking image", async () => { + await import("../panel/panel.js"); + const lightbox = document.getElementById("lightbox"); + const img = document.getElementById("lightbox-img"); + lightbox.hidden = false; + + img.dispatchEvent(new MouseEvent("click", { bubbles: true })); + // Should not close because target is img, not lightbox + expect(lightbox.hidden).toBe(false); + }); + + it("lightbox close button works", async () => { + await import("../panel/panel.js"); + const lightbox = document.getElementById("lightbox"); + lightbox.hidden = false; + + document.getElementById("lightbox-close-btn").click(); + expect(lightbox.hidden).toBe(true); + }); + + it("lightbox save button triggers download", async () => { + await import("../panel/panel.js"); + const lightbox = document.getElementById("lightbox"); + const lightboxImg = document.getElementById("lightbox-img"); + lightbox.hidden = false; + lightboxImg.src = "data:image/png;base64,AAAA"; + + document.getElementById("lightbox-save-btn").click(); + // Just verify no error thrown + }); + + it("Escape key closes lightbox when visible", async () => { + await import("../panel/panel.js"); + const lightbox = document.getElementById("lightbox"); + lightbox.hidden = false; + + document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); + expect(lightbox.hidden).toBe(true); + }); + + // ─── Code block copy button ─────────────────────────────────────────────── + + it("code block copy button copies text", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ + text: "```\nconst x = 1;\n```", + isError: false, + }); + await import("../panel/panel.js"); + const input = document.getElementById("command-input"); + + input.value = "run-code const x = 1"; + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + await vi.waitFor(() => { + const copyBtns = document.querySelectorAll(".code-copy-btn"); + if (copyBtns.length > 0) { + copyBtns[0].click(); + } + }); + }); + + // ─── Save button ────────────────────────────────────────────────────────── + + it("save button saves editor content", async () => { + window.prompt = vi.fn().mockReturnValue("test.pw"); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com"; + editor.dispatchEvent(new Event("input")); + + document.getElementById("save-btn").click(); + + expect(document.getElementById("output").textContent).toContain("Saved as test.pw"); + }); + + it("save button does nothing for empty editor", async () => { + window.prompt = vi.fn(); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + // Enable buttons with real content + editor.value = "goto https://example.com"; + editor.dispatchEvent(new Event("input")); + // Then clear content without updating button states + editor.value = ""; + + document.getElementById("save-btn").click(); + + expect(document.getElementById("output").textContent).toContain("Nothing to save"); + }); + + it("save button cancelled by user", async () => { + window.prompt = vi.fn().mockReturnValue(null); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com"; + editor.dispatchEvent(new Event("input")); + + document.getElementById("save-btn").click(); + + const output = document.getElementById("output").textContent; + expect(output).not.toContain("Saved"); + }); + + it("save button appends .pw if missing", async () => { + window.prompt = vi.fn().mockReturnValue("test"); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com"; + editor.dispatchEvent(new Event("input")); + + document.getElementById("save-btn").click(); + + expect(document.getElementById("output").textContent).toContain("Saved as test.pw"); + }); + + // ─── Open button ────────────────────────────────────────────────────────── + + it("open button loads file content into editor", async () => { + await import("../panel/panel.js"); + + // Trigger open button + const openBtn = document.getElementById("open-btn"); + + // We need to mock the file input that gets created + const realCreateElement = document.createElement.bind(document); + let fileInputEl; + vi.spyOn(document, "createElement").mockImplementation((tag) => { + const el = realCreateElement(tag); + if (tag === "input") { + fileInputEl = el; + // Mock click to trigger change event with a fake file + el.click = () => { + const file = new File(["goto https://example.com\nclick \"OK\""], "test.pw", { type: "text/plain" }); + Object.defineProperty(el, "files", { value: [file] }); + el.dispatchEvent(new Event("change")); + }; + } + return el; + }); + + openBtn.click(); + + await vi.waitFor(() => { + expect(document.getElementById("editor").value).toContain("goto https://example.com"); + }); + + document.createElement.mockRestore(); + }); + + // ─── Export empty editor ────────────────────────────────────────────────── + + it("export button shows message for empty editor", async () => { + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + // Enable buttons with real content + editor.value = "goto https://example.com"; + editor.dispatchEvent(new Event("input")); + // Then clear content without updating button states + editor.value = ""; + + document.getElementById("export-btn").click(); + + expect(document.getElementById("output").textContent).toContain("Nothing to export"); + }); + + it("export converts comments with hash to JS comments", async () => { + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "# my comment\ngoto https://example.com"; + editor.dispatchEvent(new Event("input")); + + document.getElementById("export-btn").click(); + + await vi.waitFor(() => { + // Should produce a code block with the export + const output = document.getElementById("output").textContent; + expect(output).toContain("//"); + }); + }); + + // ─── Copy clipboard failure ─────────────────────────────────────────────── + + it("copy button shows error on clipboard failure", async () => { + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com"; + editor.dispatchEvent(new Event("input")); + + // Make execCommand fail + vi.spyOn(document, "execCommand").mockImplementation(() => { + throw new Error("copy failed"); + }); + + document.getElementById("copy-btn").click(); + + expect(document.getElementById("output").textContent).toContain("Failed to copy"); + + document.execCommand.mockRestore(); + }); + + // ─── appendToEditor adds newline ────────────────────────────────────────── + + it("appendToEditor adds newline when editor does not end with one", async () => { + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "line1"; + + // Simulate a recorded command coming in via port + const portListener = mockPort.onMessage.addListener.mock.calls[0]?.[0]; + if (portListener) { + portListener({ type: "pw-recorded-command", command: "click \"OK\"" }); + expect(editor.value).toBe("line1\nclick \"OK\""); + } + }); + + // ─── syncScroll ─────────────────────────────────────────────────────────── + + it("editor scroll syncs line numbers", async () => { + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = Array(50).fill("line").join("\n"); + editor.dispatchEvent(new Event("input")); + + editor.scrollTop = 100; + editor.dispatchEvent(new Event("scroll")); + // Just verify no error thrown + }); + + // ─── Splitter drag ─────────────────────────────────────────────────────── + + it("splitter drag resizes editor pane", async () => { + await import("../panel/panel.js"); + const splitter = document.getElementById("splitter"); + const editorPane = document.getElementById("editor-pane"); + + // Simulate drag + splitter.dispatchEvent(new MouseEvent("mousedown", { clientY: 200, bubbles: true })); + expect(document.body.style.cursor).toBe("row-resize"); + + document.dispatchEvent(new MouseEvent("mousemove", { clientY: 250, bubbles: true })); + + document.dispatchEvent(new MouseEvent("mouseup", { bubbles: true })); + expect(document.body.style.cursor).toBe(""); + }); + + // ─── Recording error ───────────────────────────────────────────────────── + + it("record button handles start error", async () => { + chrome.runtime.sendMessage.mockRejectedValue(new Error("Cannot attach")); + await import("../panel/panel.js"); + + const recordBtn = document.getElementById("record-btn"); + recordBtn.click(); + + await vi.waitFor(() => { + expect(document.getElementById("output").textContent).toContain("Record error"); + }); + expect(recordBtn.classList.contains("recording")).toBe(false); + }); + + // ─── Step complete at end ───────────────────────────────────────────────── + + it("step button shows no-more-lines when editor shrinks between steps", async () => { + chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); + await import("../panel/panel.js"); + const editor = document.getElementById("editor"); + editor.value = "goto https://example.com\nclick \"OK\""; + editor.dispatchEvent(new Event("input")); + + const stepBtn = document.getElementById("step-btn"); + stepBtn.click(); + await vi.waitFor(() => { + expect(stepBtn.disabled).toBe(false); + }); + + // Shrink editor to only 1 line while stepLine=1 + editor.value = "goto https://example.com"; + // Don't dispatch input — stepLine stays at 1 + + stepBtn.click(); + await vi.waitFor(() => { + expect(document.getElementById("output").textContent).toContain("No more lines"); + }); + }); +}); diff --git a/packages/extension/test/recorder.test.js b/packages/extension/test/recorder.test.js new file mode 100644 index 0000000..76b1c91 --- /dev/null +++ b/packages/extension/test/recorder.test.js @@ -0,0 +1,534 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; + +describe("content/recorder.js", () => { + let debugSpy; + + beforeEach(() => { + // Reset the recorder state + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + // Spy on console.debug (the recorder uses it to send commands) + debugSpy = vi.spyOn(console, "debug").mockImplementation(() => {}); + }); + + afterEach(() => { + // Clean up if recorder is active + if (window.__pwRecorderCleanup) { + window.__pwRecorderCleanup(); + } + debugSpy.mockRestore(); + }); + + it("sets __pwRecorderActive on load", async () => { + await import("../content/recorder.js"); + expect(window.__pwRecorderActive).toBe(true); + }); + + it("provides a cleanup function", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + await import("../content/recorder.js"); + expect(typeof window.__pwRecorderCleanup).toBe("function"); + }); + + it("does not run twice when __pwRecorderActive is set", async () => { + window.__pwRecorderActive = true; + const cleanupBefore = window.__pwRecorderCleanup; + await import("../content/recorder.js"); + // Cleanup should not be set (skipped due to guard) + expect(window.__pwRecorderCleanup).toBe(cleanupBefore); + }); + + it("cleanup resets __pwRecorderActive", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + await import("../content/recorder.js"); + expect(window.__pwRecorderActive).toBe(true); + window.__pwRecorderCleanup(); + expect(window.__pwRecorderActive).toBe(false); + }); + + it("cleanup removes __pwRecorderCleanup", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + await import("../content/recorder.js"); + window.__pwRecorderCleanup(); + expect(window.__pwRecorderCleanup).toBeUndefined(); + }); + + it("records click events", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + document.body.innerHTML = ''; + + await import("../content/recorder.js"); + + const btn = document.getElementById("test-btn"); + btn.click(); + + expect(debugSpy).toHaveBeenCalledWith("__pw:click \"Submit\""); + }); + + it("records checkbox check/uncheck", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + document.body.innerHTML = ''; + + await import("../content/recorder.js"); + + const cb = document.getElementById("test-cb"); + cb.checked = true; + cb.dispatchEvent(new Event("click", { bubbles: true })); + + expect(debugSpy).toHaveBeenCalledWith( + expect.stringContaining("__pw:check") + ); + }); + + it("records special key presses", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + await import("../content/recorder.js"); + + document.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + + expect(debugSpy).toHaveBeenCalledWith("__pw:press Enter"); + }); + + it("records Tab key press", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + await import("../content/recorder.js"); + + document.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true })); + + expect(debugSpy).toHaveBeenCalledWith("__pw:press Tab"); + }); + + it("records Escape key press", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + await import("../content/recorder.js"); + + document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); + + expect(debugSpy).toHaveBeenCalledWith("__pw:press Escape"); + }); + + it("does not record non-special key presses", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + await import("../content/recorder.js"); + + document.dispatchEvent(new KeyboardEvent("keydown", { key: "a", bubbles: true })); + + const pwCalls = debugSpy.mock.calls.filter(c => String(c[0]).startsWith("__pw:")); + expect(pwCalls).toHaveLength(0); + }); + + it("skips clicks on text input elements", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + document.body.innerHTML = ''; + + await import("../content/recorder.js"); + + const input = document.getElementById("test-input"); + input.click(); + + const pwCalls = debugSpy.mock.calls.filter(c => String(c[0]).startsWith("__pw:")); + expect(pwCalls).toHaveLength(0); + }); + + it("skips clicks on textarea elements", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + document.body.innerHTML = ''; + + await import("../content/recorder.js"); + + document.getElementById("test-ta").click(); + + const pwCalls = debugSpy.mock.calls.filter(c => String(c[0]).startsWith("__pw:")); + expect(pwCalls).toHaveLength(0); + }); + + it("records input events as debounced fill commands", async () => { + vi.resetModules(); + vi.useFakeTimers(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + document.body.innerHTML = ''; + + await import("../content/recorder.js"); + + const input = document.getElementById("test-input"); + input.value = "alice"; + input.dispatchEvent(new Event("input", { bubbles: true })); + + // Should not send immediately (debounced at 1500ms) + const pwCallsBefore = debugSpy.mock.calls.filter(c => String(c[0]).startsWith("__pw:")); + expect(pwCallsBefore).toHaveLength(0); + + // After debounce timer fires + vi.advanceTimersByTime(1500); + + expect(debugSpy).toHaveBeenCalledWith( + expect.stringContaining("__pw:fill") + ); + expect(debugSpy).toHaveBeenCalledWith( + expect.stringContaining("alice") + ); + + vi.useRealTimers(); + }); + + it("records select changes", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + document.body.innerHTML = ` + + `; + + await import("../content/recorder.js"); + + const sel = document.getElementById("test-sel"); + sel.value = "b"; + sel.dispatchEvent(new Event("change", { bubbles: true })); + + expect(debugSpy).toHaveBeenCalledWith( + expect.stringContaining("__pw:select") + ); + }); + + it("records link clicks with text content", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + document.body.innerHTML = '
About Us'; + + await import("../content/recorder.js"); + + document.getElementById("test-link").click(); + + expect(debugSpy).toHaveBeenCalledWith('__pw:click "About Us"'); + }); + + it("uses aria-label for locator", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + document.body.innerHTML = ''; + + await import("../content/recorder.js"); + + document.querySelector("button").click(); + + expect(debugSpy).toHaveBeenCalledWith( + expect.stringContaining('__pw:click "Close dialog"') + ); + }); + + // ─── getLocator: parent label ───────────────────────────────────────────── + + it("uses parent label text for locator", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + document.body.innerHTML = ''; + + await import("../content/recorder.js"); + + const cb = document.getElementById("cb"); + cb.checked = true; + cb.dispatchEvent(new Event("click", { bubbles: true })); + + expect(debugSpy).toHaveBeenCalledWith( + expect.stringContaining("Full Name") + ); + }); + + // ─── getLocator: button/link text, title, tag fallbacks ──────────────────── + + it("uses title attribute as locator fallback", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + document.body.innerHTML = ''; + + await import("../content/recorder.js"); + + document.querySelector("button").click(); + + expect(debugSpy).toHaveBeenCalledWith('__pw:click "Delete item"'); + }); + + it("falls back to tag name when no other locator available", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + // Element with no text, no aria-label, no title, no id + document.body.innerHTML = ''; + + await import("../content/recorder.js"); + + // Remove the id so getLocator falls through all branches + const btn = document.getElementById("test-empty"); + btn.removeAttribute("id"); + btn.click(); + + expect(debugSpy).toHaveBeenCalledWith('__pw:click "button"'); + }); + + it("uses placeholder for input locator", async () => { + vi.resetModules(); + vi.useFakeTimers(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + document.body.innerHTML = ''; + + await import("../content/recorder.js"); + + const input = document.getElementById("search"); + input.value = "hello"; + input.dispatchEvent(new Event("input", { bubbles: true })); + + vi.advanceTimersByTime(1500); + + expect(debugSpy).toHaveBeenCalledWith( + expect.stringContaining("Search...") + ); + + vi.useRealTimers(); + }); + + // ─── getItemContext: scoped clicks ───────────────────────────────────────── + + it("records action button with item context", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + document.body.innerHTML = ` +
    +
  • + Buy milk + +
  • +
+ `; + + await import("../content/recorder.js"); + + document.getElementById("del-btn").click(); + + expect(debugSpy).toHaveBeenCalledWith( + expect.stringContaining("Buy milk") + ); + }); + + // ─── findCheckbox: label with htmlFor ────────────────────────────────────── + + it("finds checkbox via label htmlFor", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + document.body.innerHTML = ` + + + `; + + await import("../content/recorder.js"); + + const label = document.querySelector("label"); + const cb = document.getElementById("terms-cb"); + cb.checked = true; + label.click(); + + expect(debugSpy).toHaveBeenCalledWith( + expect.stringContaining("__pw:check") + ); + }); + + it("finds checkbox in parent label", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + document.body.innerHTML = ` + + `; + + await import("../content/recorder.js"); + + const cb = document.getElementById("nested-cb"); + cb.checked = true; + // Click the span, which is inside the label + document.getElementById("label-text").click(); + + expect(debugSpy).toHaveBeenCalledWith( + expect.stringContaining("__pw:check") + ); + }); + + // ─── checkbox with item context ──────────────────────────────────────────── + + it("records checkbox with item context label", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + document.body.innerHTML = ` +
    +
  • + + +
  • +
+ `; + + await import("../content/recorder.js"); + + const cb = document.getElementById("task-cb"); + cb.checked = true; + cb.dispatchEvent(new Event("click", { bubbles: true })); + + expect(debugSpy).toHaveBeenCalledWith( + expect.stringContaining("Buy groceries") + ); + }); + + // ─── skips non-interactive containers ────────────────────────────────────── + + it("skips clicks on non-interactive containers like div", async () => { + vi.resetModules(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + document.body.innerHTML = '
Some content
'; + + await import("../content/recorder.js"); + + document.getElementById("container").click(); + + const pwCalls = debugSpy.mock.calls.filter(c => String(c[0]).startsWith("__pw:click")); + expect(pwCalls).toHaveLength(0); + }); + + // ─── click flushes pending fill ──────────────────────────────────────────── + + it("click flushes pending fill before recording click", async () => { + vi.resetModules(); + vi.useFakeTimers(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + document.body.innerHTML = ` + + + `; + + await import("../content/recorder.js"); + + const input = document.getElementById("name-input"); + input.value = "Alice"; + input.dispatchEvent(new Event("input", { bubbles: true })); + + // Click before debounce fires — should flush fill first + document.getElementById("submit-btn").click(); + + const pwCalls = debugSpy.mock.calls.filter(c => String(c[0]).startsWith("__pw:")); + expect(pwCalls[0][0]).toContain("__pw:fill"); + expect(pwCalls[1][0]).toContain("__pw:click"); + + vi.useRealTimers(); + }); + + // ─── label[for] locator ──────────────────────────────────────────────────── + + it("uses associated label text for locator via for attribute", async () => { + vi.resetModules(); + vi.useFakeTimers(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + document.body.innerHTML = ` + + + `; + + await import("../content/recorder.js"); + + const input = document.getElementById("email-input"); + input.value = "test@test.com"; + input.dispatchEvent(new Event("input", { bubbles: true })); + + vi.advanceTimersByTime(1500); + + expect(debugSpy).toHaveBeenCalledWith( + expect.stringContaining("Email Address") + ); + + vi.useRealTimers(); + }); + + it("cleanup flushes pending fill", async () => { + vi.resetModules(); + vi.useFakeTimers(); + delete window.__pwRecorderActive; + delete window.__pwRecorderCleanup; + + document.body.innerHTML = ''; + + await import("../content/recorder.js"); + + const input = document.getElementById("test-input"); + input.value = "test@test.com"; + input.dispatchEvent(new Event("input", { bubbles: true })); + + // Cleanup should flush pending fill + window.__pwRecorderCleanup(); + + expect(debugSpy).toHaveBeenCalledWith( + expect.stringContaining("__pw:fill") + ); + + vi.useRealTimers(); + }); +}); diff --git a/packages/extension/test/setup.js b/packages/extension/test/setup.js new file mode 100644 index 0000000..bd35de7 --- /dev/null +++ b/packages/extension/test/setup.js @@ -0,0 +1,4 @@ +import * as chrome from "vitest-chrome/lib/index.esm.js"; + +// Add chrome object to global scope so imported modules can use it +Object.assign(global, chrome); diff --git a/packages/extension/vitest.config.js b/packages/extension/vitest.config.js new file mode 100644 index 0000000..f6d81cb --- /dev/null +++ b/packages/extension/vitest.config.js @@ -0,0 +1,13 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + setupFiles: "./test/setup.js", + environment: "happy-dom", + coverage: { + provider: "v8", + include: ["content/**/*.js", "lib/**/*.js", "panel/**/*.js", "background.js", "devtools.js"], + reporter: ["text", "html"], + }, + }, +}); From bfc27d9941c0f769b249b3169da2aa5db07b159e Mon Sep 17 00:00:00 2001 From: Steve Zhang Date: Thu, 19 Feb 2026 15:56:31 -0500 Subject: [PATCH 02/27] extension: copy MCP Bridge relay pattern into our extension MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RelayConnection and background.js now match Playwright's MCP Bridge exactly (deferred setTabId, connect.html flow, tab lifecycle, badges). Phase 1 still uses ExtensionContextFactory — extension relay code is ready for Phase 2. Co-Authored-By: Claude Opus 4.6 --- packages/core/test/extension-server.test.mjs | 224 ----------------- packages/extension/background.js | 239 +++++++++++++++---- packages/extension/connect.html | 161 +++++++++++++ packages/extension/lib/relayConnection.js | 90 ++++--- packages/extension/manifest.json | 11 +- packages/extension/test/background.test.js | 41 +++- 6 files changed, 459 insertions(+), 307 deletions(-) create mode 100644 packages/extension/connect.html diff --git a/packages/core/test/extension-server.test.mjs b/packages/core/test/extension-server.test.mjs index bbff7f8..10c823c 100644 --- a/packages/core/test/extension-server.test.mjs +++ b/packages/core/test/extension-server.test.mjs @@ -1,5 +1,4 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { WebSocket } from 'ws'; import { CommandServer } from '../src/extension-server.mjs'; // ─── Helper: create a mock engine ───────────────────────────────────────────── @@ -118,221 +117,6 @@ describe('CommandServer', () => { }); }); - describe('GET /json/version', () => { - it('returns webSocketDebuggerUrl for CDP discovery', async () => { - await server.start(TEST_PORT); - - const res = await fetch(`http://localhost:${TEST_PORT}/json/version`); - expect(res.status).toBe(200); - - const data = await res.json(); - expect(data.webSocketDebuggerUrl).toContain(`ws://127.0.0.1:${TEST_PORT}/devtools/browser/`); - expect(data['Protocol-Version']).toBe('1.3'); - }); - - it('also works with trailing slash', async () => { - await server.start(TEST_PORT); - - const res = await fetch(`http://localhost:${TEST_PORT}/json/version/`); - expect(res.status).toBe(200); - - const data = await res.json(); - expect(data.webSocketDebuggerUrl).toBeDefined(); - }); - }); - - describe('WebSocket /extension', () => { - it('accepts extension connection and resolves waitForExtension', async () => { - await server.start(TEST_PORT); - - const waitPromise = server.waitForExtension(); - const ws = new WebSocket(`ws://127.0.0.1:${TEST_PORT}/extension`); - await new Promise((resolve) => ws.on('open', resolve)); - - await waitPromise; // Should resolve when extension connects - ws.close(); - }); - - it('rejects second extension connection', async () => { - await server.start(TEST_PORT); - - const ws1 = new WebSocket(`ws://127.0.0.1:${TEST_PORT}/extension`); - await new Promise((resolve) => ws1.on('open', resolve)); - - const ws2 = new WebSocket(`ws://127.0.0.1:${TEST_PORT}/extension`); - const closeCode = await new Promise((resolve) => ws2.on('close', resolve)); - expect(closeCode).toBe(1000); - - ws1.close(); - }); - - it('waitForExtension resolves immediately if already connected', async () => { - await server.start(TEST_PORT); - - const ws = new WebSocket(`ws://127.0.0.1:${TEST_PORT}/extension`); - await new Promise((resolve) => ws.on('open', resolve)); - - await server.waitForExtension(); // Should resolve immediately - ws.close(); - }); - }); - - describe('CDP relay', () => { - let extWs; - let pwWs; - let pwMessages; // Collected messages from Playwright WebSocket - let extMessages; // Collected messages from Extension WebSocket - - async function connectExtension() { - extWs = new WebSocket(`ws://127.0.0.1:${TEST_PORT}/extension`); - extMessages = []; - await new Promise((resolve) => extWs.on('open', resolve)); - extWs.on('message', (data) => extMessages.push(JSON.parse(data.toString()))); - } - - async function connectPlaywright() { - const res = await fetch(`http://localhost:${TEST_PORT}/json/version`); - const { webSocketDebuggerUrl } = await res.json(); - pwWs = new WebSocket(webSocketDebuggerUrl); - pwMessages = []; - await new Promise((resolve) => pwWs.on('open', resolve)); - pwWs.on('message', (data) => pwMessages.push(JSON.parse(data.toString()))); - } - - function sendFromPlaywright(msg) { - pwWs.send(JSON.stringify(msg)); - } - - /** Wait until pw message array has at least `count` entries. */ - async function waitForPwMessages(count) { - while (pwMessages.length < count) { - await new Promise((r) => setTimeout(r, 20)); - } - } - - /** Wait until ext message array has at least `count` entries. */ - async function waitForExtMessages(count) { - while (extMessages.length < count) { - await new Promise((r) => setTimeout(r, 20)); - } - } - - /** Auto-attach helper: sends Target.setAutoAttach, responds with target info, drains responses. */ - async function doAutoAttach() { - const baseCount = extMessages.length; - sendFromPlaywright({ id: 1, method: 'Target.setAutoAttach', params: {} }); - await waitForExtMessages(baseCount + 1); - const attachMsg = extMessages[baseCount]; - expect(attachMsg.method).toBe('attachToTab'); - - const pwBaseCount = pwMessages.length; - extWs.send(JSON.stringify({ - id: attachMsg.id, - result: { targetInfo: { targetId: 'tab-1', type: 'page', title: 'Test', url: 'http://test.com' } }, - })); - await waitForPwMessages(pwBaseCount + 2); // event + response - } - - afterEach(() => { - extWs?.close(); - pwWs?.close(); - }); - - it('handles Browser.getVersion locally', async () => { - await server.start(TEST_PORT); - await connectExtension(); - await connectPlaywright(); - - sendFromPlaywright({ id: 1, method: 'Browser.getVersion', params: {} }); - await waitForPwMessages(1); - - expect(pwMessages[0].id).toBe(1); - expect(pwMessages[0].result.protocolVersion).toBe('1.3'); - expect(pwMessages[0].result.product).toContain('Chrome'); - }); - - it('handles Browser.setDownloadBehavior locally', async () => { - await server.start(TEST_PORT); - await connectExtension(); - await connectPlaywright(); - - sendFromPlaywright({ id: 2, method: 'Browser.setDownloadBehavior', params: {} }); - await waitForPwMessages(1); - - expect(pwMessages[0].id).toBe(2); - expect(pwMessages[0].result).toEqual({}); - }); - - it('handles Target.setAutoAttach by sending attachToTab to extension', async () => { - await server.start(TEST_PORT); - await connectExtension(); - await connectPlaywright(); - - await doAutoAttach(); - - const attachedEvent = pwMessages.find(m => m.method === 'Target.attachedToTarget'); - const autoAttachResponse = pwMessages.find(m => m.id === 1); - - expect(autoAttachResponse.result).toEqual({}); - expect(attachedEvent.params.targetInfo.targetId).toBe('tab-1'); - expect(attachedEvent.params.sessionId).toMatch(/^pw-tab-/); - }); - - it('forwards CDP commands to extension via forwardCDPCommand', async () => { - await server.start(TEST_PORT); - await connectExtension(); - await connectPlaywright(); - - await doAutoAttach(); - - // Now send a CDP command with the session ID - const extBaseCount = extMessages.length; - sendFromPlaywright({ - id: 10, - sessionId: 'pw-tab-1', - method: 'Page.navigate', - params: { url: 'http://example.com' }, - }); - await waitForExtMessages(extBaseCount + 1); - - const fwdMsg = extMessages[extBaseCount]; - expect(fwdMsg.method).toBe('forwardCDPCommand'); - expect(fwdMsg.params.method).toBe('Page.navigate'); - // Session ID should be stripped (maps to main tab) - expect(fwdMsg.params.sessionId).toBeUndefined(); - - // Extension responds - const pwBaseCount = pwMessages.length; - extWs.send(JSON.stringify({ id: fwdMsg.id, result: { frameId: 'f1' } })); - await waitForPwMessages(pwBaseCount + 1); - - const response = pwMessages[pwBaseCount]; - expect(response.id).toBe(10); - expect(response.result.frameId).toBe('f1'); - }); - - it('forwards CDP events from extension to Playwright', async () => { - await server.start(TEST_PORT); - await connectExtension(); - await connectPlaywright(); - - await doAutoAttach(); - - // Send CDP event from extension - const pwBaseCount = pwMessages.length; - extWs.send(JSON.stringify({ - method: 'forwardCDPEvent', - params: { method: 'Page.loadEventFired', params: { timestamp: 123 } }, - })); - await waitForPwMessages(pwBaseCount + 1); - - const event = pwMessages[pwBaseCount]; - expect(event.method).toBe('Page.loadEventFired'); - expect(event.params.timestamp).toBe(123); - expect(event.sessionId).toMatch(/^pw-tab-/); - }); - }); - describe('other routes', () => { it('returns 404 for unknown paths', async () => { await server.start(TEST_PORT); @@ -347,13 +131,5 @@ describe('CommandServer', () => { const res = await fetch(`http://localhost:${TEST_PORT}/run`); expect(res.status).toBe(404); }); - - it('rejects WebSocket on invalid path', async () => { - await server.start(TEST_PORT); - - const ws = new WebSocket(`ws://127.0.0.1:${TEST_PORT}/invalid`); - const code = await new Promise((resolve) => ws.on('close', resolve)); - expect(code).toBe(4004); - }); }); }); diff --git a/packages/extension/background.js b/packages/extension/background.js index ceb01fd..dbfb38e 100644 --- a/packages/extension/background.js +++ b/packages/extension/background.js @@ -1,50 +1,67 @@ /** * background.js — Service worker for the Playwright REPL DevTools extension. * - * Three roles: - * 1. CDP bridge: WebSocket connection to CommandServer, bridging chrome.debugger - * so Playwright can control the inspected tab via connectOverCDP + * Roles: + * 1. CDP bridge: Handles connect.html flow from Playwright's CDPRelayServer, + * bridging chrome.debugger via RelayConnection (copied from MCP Bridge) * 2. Command proxy: forward panel commands to CommandServer via HTTP POST /run * 3. Recording: inject recorder.js, listen for __pw: events (extension-side only) */ -import { RelayConnection } from './lib/relayConnection.js'; +import { RelayConnection, debugLog } from './lib/relayConnection.js'; // ─── State ─────────────────────────────────────────────────────────────────── let serverPort = 3000; let panelPorts = {}; // tabId → port (for sending recorded commands to panel) let recording = {}; // tabId → boolean -let activeRelay = null; // RelayConnection instance -// ─── Bridge connection ────────────────────────────────────────────────────── +// ─── MCP Bridge relay (matches TabShareExtension from Playwright MCP Bridge) ─ -function connectBridge(tabId) { - if (activeRelay) return; +let activeConnection = null; +let connectedTabId = null; +const pendingTabSelection = new Map(); // selectorTabId → { connection, timerId? } - try { - const ws = new WebSocket(`ws://127.0.0.1:${serverPort}/extension`); - ws.onopen = () => { - activeRelay = new RelayConnection(ws, tabId); - activeRelay.onclose = () => { activeRelay = null; }; - console.log('[bridge] Connected to server, tabId:', tabId); - }; - ws.onerror = () => { - // Server not running yet, will retry when panel reconnects - }; - ws.onclose = () => { - if (activeRelay) return; // RelayConnection handles its own cleanup - // Auto-reconnect after delay if no active relay - setTimeout(() => connectBridge(tabId), 2000); - }; - } catch (e) { - // WebSocket constructor failed +// ─── Message handling (MCP Bridge + panel commands) ────────────────────────── + +chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { + // MCP Bridge messages (from connect.html) + if (message.type === 'connectToMCPRelay') { + connectToRelay(sender.tab.id, message.mcpRelayUrl).then( + () => sendResponse({ success: true }), + (error) => sendResponse({ success: false, error: error.message })); + return true; } -} -// ─── Panel command handling ────────────────────────────────────────────────── + if (message.type === 'getTabs') { + getTabs().then( + tabs => sendResponse({ success: true, tabs, currentTabId: sender.tab?.id }), + (error) => sendResponse({ success: false, error: error.message })); + return true; + } -chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { + if (message.type === 'connectToTab') { + const tabId = message.tabId || sender.tab?.id; + const windowId = message.windowId || sender.tab?.windowId; + connectTab(sender.tab.id, tabId, windowId, message.mcpRelayUrl).then( + () => sendResponse({ success: true }), + (error) => sendResponse({ success: false, error: error.message })); + return true; + } + + if (message.type === 'getConnectionStatus') { + sendResponse({ connectedTabId }); + return false; + } + + if (message.type === 'disconnect') { + disconnect().then( + () => sendResponse({ success: true }), + (error) => sendResponse({ success: false, error: error.message })); + return true; + } + + // Panel commands (from DevTools panel) if (message.type === 'pw-command') { handlePanelCommand(message.raw).then(sendResponse); return true; @@ -61,6 +78,149 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { } }); +// ─── MCP Bridge relay functions ───────────────────────────────────────────── + +async function connectToRelay(selectorTabId, mcpRelayUrl) { + try { + debugLog(`Connecting to relay at ${mcpRelayUrl}`); + const socket = new WebSocket(mcpRelayUrl); + await new Promise((resolve, reject) => { + socket.onopen = () => resolve(); + socket.onerror = () => reject(new Error('WebSocket error')); + setTimeout(() => reject(new Error('Connection timeout')), 5000); + }); + + const connection = new RelayConnection(socket); + connection.onclose = () => { + debugLog('Connection closed'); + pendingTabSelection.delete(selectorTabId); + }; + pendingTabSelection.set(selectorTabId, { connection }); + debugLog(`Connected to MCP relay`); + } catch (error) { + const message = `Failed to connect to MCP relay: ${error.message}`; + debugLog(message); + throw new Error(message); + } +} + +async function connectTab(selectorTabId, tabId, windowId, mcpRelayUrl) { + try { + debugLog(`Connecting tab ${tabId} to relay at ${mcpRelayUrl}`); + try { + activeConnection?.close('Another connection is requested'); + } catch (error) { + debugLog(`Error closing active connection:`, error); + } + await setConnectedTabId(null); + + activeConnection = pendingTabSelection.get(selectorTabId)?.connection; + if (!activeConnection) + throw new Error('No active MCP relay connection'); + pendingTabSelection.delete(selectorTabId); + + activeConnection.setTabId(tabId); + activeConnection.onclose = () => { + debugLog('MCP connection closed'); + activeConnection = null; + void setConnectedTabId(null); + }; + + await Promise.all([ + setConnectedTabId(tabId), + chrome.tabs.update(tabId, { active: true }), + chrome.windows.update(windowId, { focused: true }), + ]); + debugLog(`Connected to MCP bridge`); + } catch (error) { + await setConnectedTabId(null); + debugLog(`Failed to connect tab ${tabId}:`, error.message); + throw error; + } +} + +async function setConnectedTabId(tabId) { + const oldTabId = connectedTabId; + connectedTabId = tabId; + if (oldTabId && oldTabId !== tabId) + await updateBadge(oldTabId, { text: '' }); + if (tabId) + await updateBadge(tabId, { text: '\u2713', color: '#4CAF50', title: 'Connected to MCP client' }); +} + +async function updateBadge(tabId, { text, color, title }) { + try { + await chrome.action.setBadgeText({ tabId, text }); + await chrome.action.setTitle({ tabId, title: title || '' }); + if (color) + await chrome.action.setBadgeBackgroundColor({ tabId, color }); + } catch (error) { + // Ignore errors as the tab may be closed already. + } +} + +async function getTabs() { + const tabs = await chrome.tabs.query({}); + return tabs.filter(tab => tab.url && !['chrome:', 'edge:', 'devtools:'].some(scheme => tab.url.startsWith(scheme))); +} + +async function disconnect() { + activeConnection?.close('User disconnected'); + activeConnection = null; + await setConnectedTabId(null); +} + +// ─── Tab lifecycle ────────────────────────────────────────────────────────── + +chrome.tabs.onRemoved.addListener((tabId) => { + const pendingConn = pendingTabSelection.get(tabId)?.connection; + if (pendingConn) { + pendingTabSelection.delete(tabId); + pendingConn.close('Browser tab closed'); + return; + } + if (connectedTabId !== tabId) return; + activeConnection?.close('Browser tab closed'); + activeConnection = null; + connectedTabId = null; +}); + +chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => { + if (connectedTabId === tabId) + void setConnectedTabId(tabId); +}); + +chrome.tabs.onActivated.addListener((activeInfo) => { + for (const [tabId, pending] of pendingTabSelection) { + if (tabId === activeInfo.tabId) { + if (pending.timerId) { + clearTimeout(pending.timerId); + pending.timerId = undefined; + } + continue; + } + if (!pending.timerId) { + pending.timerId = setTimeout(() => { + const existed = pendingTabSelection.delete(tabId); + if (existed) { + pending.connection.close('Tab has been inactive for 5 seconds'); + chrome.tabs.sendMessage(tabId, { type: 'connectionTimeout' }); + } + }, 5000); + return; + } + } +}); + +chrome.action.onClicked.addListener(async () => { + await chrome.tabs.create({ + url: chrome.runtime.getURL('connect.html'), + active: true, + }); +}); + +// ─── Panel command handling ────────────────────────────────────────────────── + async function handlePanelCommand(raw) { try { const res = await fetch(`http://127.0.0.1:${serverPort}/run`, { @@ -76,6 +236,8 @@ async function handlePanelCommand(raw) { // ─── Recording ─────────────────────────────────────────────────────────────── +let recordingAttachedTabId = null; + async function startRecording(tabId) { try { await ensureAttached(tabId); @@ -109,10 +271,6 @@ async function stopRecording(tabId) { return { success: true }; } -// ─── Debugger attach/detach (for recording only) ──────────────────────────── - -let recordingAttachedTabId = null; - async function ensureAttached(tabId) { if (recordingAttachedTabId === tabId) return; if (recordingAttachedTabId) { @@ -150,9 +308,6 @@ chrome.runtime.onConnect.addListener((port) => { const tabId = parseInt(port.name.replace('pw-panel-', ''), 10); panelPorts[tabId] = port; - // When a panel connects, start the CDP bridge for this tab - connectBridge(tabId); - port.onDisconnect.addListener(() => { delete panelPorts[tabId]; }); @@ -165,20 +320,20 @@ export { startRecording, stopRecording, ensureAttached, - connectBridge, + connectToRelay, + connectTab, + disconnect, }; export function _getState() { - return { serverPort, panelPorts, recording, activeRelay, recordingAttachedTabId }; + return { serverPort, panelPorts, recording, activeConnection, connectedTabId, recordingAttachedTabId, pendingTabSelection }; } export function _resetState() { panelPorts = {}; recording = {}; - activeRelay = null; + activeConnection = null; + connectedTabId = null; recordingAttachedTabId = null; -} - -export function _setActiveRelay(relay) { - activeRelay = relay; + pendingTabSelection.clear(); } diff --git a/packages/extension/connect.html b/packages/extension/connect.html new file mode 100644 index 0000000..1f0cf61 --- /dev/null +++ b/packages/extension/connect.html @@ -0,0 +1,161 @@ + + + + Playwright REPL - Connect + + + + +
+
+
+ + + + diff --git a/packages/extension/lib/relayConnection.js b/packages/extension/lib/relayConnection.js index 6a18c66..51a0a39 100644 --- a/packages/extension/lib/relayConnection.js +++ b/packages/extension/lib/relayConnection.js @@ -1,39 +1,57 @@ /** - * RelayConnection — CDP relay over WebSocket, matching Playwright's MCP Bridge pattern. + * RelayConnection — CDP relay over WebSocket. * - * Bridges chrome.debugger ↔ WebSocket so Playwright can control a browser tab - * via connectOverCDP through the CommandServer relay. + * Copied from Playwright MCP Bridge (packages/extension/src/relayConnection.ts), + * converted to plain JS. Bridges chrome.debugger <-> WebSocket so Playwright + * can control a browser tab via connectOverCDP. * * Protocol (3 message types): - * Server → Extension: + * Server -> Extension: * { id, method: "attachToTab", params: {} } - * → attach chrome.debugger, return real targetInfo from CDP + * -> attach chrome.debugger, return targetInfo * { id, method: "forwardCDPCommand", params: { sessionId, method, params } } - * → forward to chrome.debugger with sessionId support - * Extension → Server: + * -> forward to chrome.debugger + * Extension -> Server: * { method: "forwardCDPEvent", params: { sessionId, method, params } } - * → forward chrome.debugger.onEvent back to server + * -> forward chrome.debugger.onEvent to server */ +export function debugLog(...args) { + console.log('[Extension]', ...args); +} + export class RelayConnection { - constructor(ws, tabId) { + constructor(ws) { + this._debuggee = {}; this._ws = ws; - this._debuggee = { tabId }; this._closed = false; + this.onclose = null; + + // Tab ID is set later via setTabId(); attachToTab waits for it. + this._tabPromise = new Promise(resolve => { + this._tabPromiseResolve = resolve; + }); + this._ws.onmessage = (event) => this._onMessage(event); + this._ws.onclose = () => this._onClose(); + + // Store listeners for cleanup this._eventListener = (source, method, params) => this._onDebuggerEvent(source, method, params); this._detachListener = (source, reason) => this._onDebuggerDetach(source, reason); chrome.debugger.onEvent.addListener(this._eventListener); chrome.debugger.onDetach.addListener(this._detachListener); + } - this._ws.onmessage = (event) => this._onMessage(event); - this._ws.onclose = () => this._onClose(); - - this.onclose = null; + // Either setTabId or close is called after creating the connection. + setTabId(tabId) { + this._debuggee = { tabId }; + this._tabPromiseResolve(); } close(message) { this._ws.close(1000, message); + // ws.onclose is called asynchronously, so we call it here to avoid forwarding + // CDP events to the closed connection. this._onClose(); } @@ -46,65 +64,77 @@ export class RelayConnection { this.onclose?.(); } - // ─── CDP events from browser → server ───────────────────────────────── + // ─── CDP events from browser -> server ────────────────────────────────── _onDebuggerEvent(source, method, params) { if (source.tabId !== this._debuggee.tabId) return; + debugLog('Forwarding CDP event:', method, params); + const sessionId = source.sessionId; this._sendMessage({ method: 'forwardCDPEvent', - params: { - sessionId: source.sessionId, - method, - params, - }, + params: { sessionId, method, params }, }); } _onDebuggerDetach(source, reason) { if (source.tabId !== this._debuggee.tabId) return; this.close(`Debugger detached: ${reason}`); + this._debuggee = {}; } - // ─── Messages from server → extension ───────────────────────────────── + // ─── Messages from server -> extension ────────────────────────────────── _onMessage(event) { - this._onMessageAsync(event).catch(e => console.error('[relay] Error:', e)); + this._onMessageAsync(event).catch(e => debugLog('Error handling message:', e)); } async _onMessageAsync(event) { let message; try { message = JSON.parse(event.data); - } catch (e) { - this._sendMessage({ error: `Parse error: ${e.message}` }); + } catch (error) { + debugLog('Error parsing message:', error); + this._sendError(-32700, `Error parsing message: ${error.message}`); return; } + debugLog('Received message:', message); + const response = { id: message.id }; try { response.result = await this._handleCommand(message); - } catch (e) { - response.error = e.message; + } catch (error) { + debugLog('Error handling command:', error); + response.error = error.message; } + debugLog('Sending response:', response); this._sendMessage(response); } async _handleCommand(message) { if (message.method === 'attachToTab') { - // Attach chrome.debugger and get REAL targetInfo from CDP + await this._tabPromise; + debugLog('Attaching debugger to tab:', this._debuggee); await chrome.debugger.attach(this._debuggee, '1.3'); const result = await chrome.debugger.sendCommand(this._debuggee, 'Target.getTargetInfo'); return { targetInfo: result?.targetInfo }; } - + if (!this._debuggee.tabId) + throw new Error('No tab is connected.'); if (message.method === 'forwardCDPCommand') { const { sessionId, method, params } = message.params; - // Pass sessionId directly to chrome.debugger (key fix from MCP Bridge) + debugLog('CDP command:', method, params); const debuggerSession = { ...this._debuggee, sessionId }; - return await chrome.debugger.sendCommand(debuggerSession, method, params || {}); + return await chrome.debugger.sendCommand(debuggerSession, method, params); } } + _sendError(code, message) { + this._sendMessage({ + error: { code, message }, + }); + } + _sendMessage(message) { if (this._ws.readyState === WebSocket.OPEN) this._ws.send(JSON.stringify(message)); diff --git a/packages/extension/manifest.json b/packages/extension/manifest.json index 58ad4e8..56fba98 100644 --- a/packages/extension/manifest.json +++ b/packages/extension/manifest.json @@ -6,11 +6,20 @@ "devtools_page": "devtools.html", "permissions": [ "debugger", + "activeTab", "tabs" ], "host_permissions": [ - "http://127.0.0.1:*/*" + "" ], + "action": { + "default_title": "Playwright REPL", + "default_icon": { + "16": "icons/icon16.png", + "48": "icons/icon48.png", + "128": "icons/icon128.png" + } + }, "background": { "service_worker": "background.js", "type": "module" diff --git a/packages/extension/test/background.test.js b/packages/extension/test/background.test.js index 68d8af9..730337c 100644 --- a/packages/extension/test/background.test.js +++ b/packages/extension/test/background.test.js @@ -29,6 +29,14 @@ globalThis.fetch = vi.fn(() => ); chrome.runtime.getURL = vi.fn((path) => `chrome-extension://test/${path}`); +// Mock chrome.action (not provided by vitest-chrome) +chrome.action = { + onClicked: { addListener: vi.fn() }, + setBadgeText: vi.fn(() => Promise.resolve()), + setBadgeBackgroundColor: vi.fn(() => Promise.resolve()), + setTitle: vi.fn(() => Promise.resolve()), +}; + // ─── Import + reset helpers ───────────────────────────────────────────────── let mod; @@ -50,6 +58,12 @@ beforeEach(async () => { chrome.debugger.onDetach.clearListeners(); chrome.runtime.onConnect.clearListeners(); chrome.runtime.onMessage.clearListeners(); + chrome.action = { + onClicked: { addListener: vi.fn() }, + setBadgeText: vi.fn(() => Promise.resolve()), + setBadgeBackgroundColor: vi.fn(() => Promise.resolve()), + setTitle: vi.fn(() => Promise.resolve()), + }; vi.resetModules(); mod = await import("../background.js"); @@ -107,7 +121,8 @@ describe("RelayConnection", () => { }); const mockWs = new MockWebSocket("ws://test"); - const relay = new RelayConnection(mockWs, 42); + const relay = new RelayConnection(mockWs); + relay.setTabId(42); // Simulate server sending attachToTab await relay._onMessageAsync({ @@ -135,7 +150,8 @@ describe("RelayConnection", () => { chrome.debugger.sendCommand.mockResolvedValue({ result: { value: 42 } }); const mockWs = new MockWebSocket("ws://test"); - const relay = new RelayConnection(mockWs, 10); + const relay = new RelayConnection(mockWs); + relay.setTabId(10); await relay._onMessageAsync({ data: JSON.stringify({ @@ -165,7 +181,8 @@ describe("RelayConnection", () => { chrome.debugger.sendCommand.mockResolvedValue({}); const mockWs = new MockWebSocket("ws://test"); - const relay = new RelayConnection(mockWs, 10); + const relay = new RelayConnection(mockWs); + relay.setTabId(10); await relay._onMessageAsync({ data: JSON.stringify({ @@ -184,7 +201,8 @@ describe("RelayConnection", () => { it("forwards CDP events to server", () => { const mockWs = new MockWebSocket("ws://test"); - const relay = new RelayConnection(mockWs, 10); + const relay = new RelayConnection(mockWs); + relay.setTabId(10); // Simulate chrome.debugger.onEvent chrome.debugger.onEvent.callListeners( @@ -202,7 +220,8 @@ describe("RelayConnection", () => { it("ignores CDP events from other tabs", () => { const mockWs = new MockWebSocket("ws://test"); - const relay = new RelayConnection(mockWs, 10); + const relay = new RelayConnection(mockWs); + relay.setTabId(10); chrome.debugger.onEvent.callListeners( { tabId: 99 }, @@ -217,7 +236,8 @@ describe("RelayConnection", () => { chrome.debugger.attach.mockRejectedValue(new Error("Cannot attach")); const mockWs = new MockWebSocket("ws://test"); - const relay = new RelayConnection(mockWs, 10); + const relay = new RelayConnection(mockWs); + relay.setTabId(10); await relay._onMessageAsync({ data: JSON.stringify({ id: 1, method: "attachToTab", params: {} }), @@ -231,15 +251,16 @@ describe("RelayConnection", () => { it("cleans up on close", () => { chrome.debugger.detach.mockResolvedValue(undefined); const mockWs = new MockWebSocket("ws://test"); - const relay = new RelayConnection(mockWs, 10); - mod._setActiveRelay(relay); - relay.onclose = () => { mod._setActiveRelay(null); }; + const relay = new RelayConnection(mockWs); + relay.setTabId(10); + const onclose = vi.fn(); + relay.onclose = onclose; relay.close("test"); expect(mockWs.close).toHaveBeenCalledWith(1000, "test"); expect(chrome.debugger.detach).toHaveBeenCalledWith({ tabId: 10 }); - expect(getState().activeRelay).toBeNull(); + expect(onclose).toHaveBeenCalled(); }); }); From 3bd6006839936ecba343cec01ce81ed4b6d654be Mon Sep 17 00:00:00 2001 From: Steve Zhang Date: Thu, 19 Feb 2026 21:16:32 -0500 Subject: [PATCH 03/27] extension: use Playwright's CDPRelayServer + our connect.html for Phase 2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace ExtensionContextFactory (spawns separate Chrome with MCP Bridge) with CDPRelayServer directly. Engine spawns Chrome opening our extension's connect.html, which triggers background.js relay via RelayConnection. Playwright connects through CDPRelayServer — the proven relay. Co-Authored-By: Claude Opus 4.6 --- package-lock.json | 15 +- package.json | 3 +- packages/cli/src/repl.mjs | 4 +- packages/core/src/engine.mjs | 53 +++- packages/core/src/extension-server.mjs | 337 ++++++++++++++++++++++++- packages/extension/background.js | 46 +++- packages/extension/connect.html | 133 +--------- packages/extension/connect.js | 137 ++++++++++ 8 files changed, 562 insertions(+), 166 deletions(-) create mode 100644 packages/extension/connect.js diff --git a/package-lock.json b/package-lock.json index 333fff4..1ae68f9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,8 +9,7 @@ "packages/*" ], "dependencies": { - "playwright": "^1.59.0-alpha-1771104257000", - "playwright-core": "^1.58.2" + "playwright": "^1.59.0-alpha-1771104257000" }, "devDependencies": { "@vitest/coverage-v8": "^4.0.18", @@ -1490,18 +1489,6 @@ "fsevents": "2.3.2" } }, - "node_modules/playwright-core": { - "version": "1.58.2", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.2.tgz", - "integrity": "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==", - "license": "Apache-2.0", - "bin": { - "playwright-core": "cli.js" - }, - "engines": { - "node": ">=18" - } - }, "node_modules/playwright-repl": { "resolved": "packages/cli", "link": true diff --git a/package.json b/package.json index adab242..c1186e9 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,6 @@ "vitest": "^4.0.18" }, "dependencies": { - "playwright": "^1.59.0-alpha-1771104257000", - "playwright-core": "^1.58.2" + "playwright": "^1.59.0-alpha-1771104257000" } } diff --git a/packages/cli/src/repl.mjs b/packages/cli/src/repl.mjs index b696f4c..8d8ae1f 100644 --- a/packages/cli/src/repl.mjs +++ b/packages/cli/src/repl.mjs @@ -508,7 +508,7 @@ export async function startRepl(opts = {}) { // ─── Start engine ──────────────────────────────────────────────── if (opts.extension) { - log(`${c.dim}Extension mode: starting MCP Bridge (will open Chrome)...${c.reset}`); + log(`${c.dim}Extension mode: starting CDP relay server...${c.reset}`); log(''); } else { log(`${c.dim}Type .help for commands${c.reset}\n`); @@ -518,7 +518,7 @@ export async function startRepl(opts = {}) { try { await conn.start(opts); if (opts.extension) - log(`${c.green}✓${c.reset} Extension mode ready (MCP Bridge connected)\n`); + log(`${c.green}✓${c.reset} Extension connected, ready for commands\n`); else log(`${c.green}✓${c.reset} Browser ready\n`); } catch (err) { diff --git a/packages/core/src/engine.mjs b/packages/core/src/engine.mjs index 617d024..a65260c 100644 --- a/packages/core/src/engine.mjs +++ b/packages/core/src/engine.mjs @@ -28,7 +28,9 @@ function loadDeps() { _deps = { BrowserServerBackend: pwReq('lib/mcp/browser/browserServerBackend.js').BrowserServerBackend, contextFactory: pwReq('lib/mcp/browser/browserContextFactory.js').contextFactory, - ExtensionContextFactory: pwReq('lib/mcp/extension/extensionContextFactory.js').ExtensionContextFactory, + CDPRelayServer: pwReq('lib/mcp/extension/cdpRelay.js').CDPRelayServer, + playwright: pwReq('node_modules/playwright-core'), + registry: pwReq('node_modules/playwright-core/lib/server/registry/index.js').registry, resolveConfig: pwReq('lib/mcp/browser/config.js').resolveConfig, commands: pwReq('lib/cli/daemon/commands.js').commands, parseCommand: pwReq('lib/cli/daemon/command.js').parseCommand, @@ -72,18 +74,51 @@ export class Engine { // Choose context factory based on mode. let factory; if (opts.extension) { - // Phase 1: ExtensionContextFactory (MCP Bridge) handles the CDP relay. - // CommandServer only provides HTTP /run for panel commands. + // Start CommandServer for panel HTTP commands. const { CommandServer } = await import('./extension-server.mjs'); this._commandServer = new CommandServer(this); await this._commandServer.start(opts.port || 3000); - // ExtensionContextFactory spawns Chrome with MCP Bridge extension, - // creates CDPRelayServer, and connects Playwright through it. - const extFactory = new deps.ExtensionContextFactory('chrome', undefined, undefined); - const { browserContext, close } = await extFactory.createContext( - clientInfo, new AbortController().signal, {}, - ); + // Use Playwright's own CDPRelayServer (proven to work). + const { createServer } = await import('node:http'); + const relayHttp = createServer(); + const relayPort = (opts.port || 3000) + 1; + await new Promise(r => relayHttp.listen(relayPort, '127.0.0.1', r)); + const relay = new deps.CDPRelayServer(relayHttp, opts.browser || 'chrome'); + this._relayHttp = relayHttp; + + // Spawn Chrome with our extension's connect.html pointing at CDPRelayServer. + const extensionId = opts.extensionId || 'hofgdkanlhhkikiomnnndihbefnjhlmp'; + const connectUrl = new URL(`chrome-extension://${extensionId}/connect.html`); + connectUrl.searchParams.set('mcpRelayUrl', relay.extensionEndpoint()); + connectUrl.searchParams.set('client', JSON.stringify({ name: 'playwright-repl', version: replVersion })); + + const execInfo = deps.registry.findExecutable(opts.browser || 'chrome'); + const execPath = execInfo?.executablePath(); + if (!execPath) + throw new Error('Chrome executable not found. Make sure Chrome is installed.'); + + const { spawn } = await import('node:child_process'); + spawn(execPath, [connectUrl.toString()], { + detached: true, stdio: 'ignore', windowsHide: true, + }); + + // Wait for extension to connect to CDPRelayServer. + console.log('Waiting for extension to connect...'); + await Promise.race([ + relay._extensionConnectionPromise, + new Promise((_, reject) => setTimeout(() => reject(new Error('Extension connection timeout (30s)')), 30000)), + ]); + console.log('Extension connected. Connecting Playwright...'); + + // Connect Playwright through CDPRelayServer — exactly like ExtensionContextFactory. + const browser = await deps.playwright.chromium.connectOverCDP(relay.cdpEndpoint(), { isLocal: true }); + const browserContext = browser.contexts()[0]; + const close = async () => { + await browser.close(); + relay.stop(); + relayHttp.close(); + }; this._close = close; const existingContextFactory = { diff --git a/packages/core/src/extension-server.mjs b/packages/core/src/extension-server.mjs index 22c096a..371fac5 100644 --- a/packages/core/src/extension-server.mjs +++ b/packages/core/src/extension-server.mjs @@ -1,15 +1,19 @@ /** - * CommandServer — HTTP server for the DevTools panel extension. + * CommandServer — HTTP + WebSocket server for the DevTools panel extension. * - * Provides the POST /run endpoint so the panel can send commands - * to the engine. The CDP relay is handled by Playwright's - * ExtensionContextFactory + MCP Bridge extension. + * Endpoints: + * POST /run Panel commands → engine.run() + * GET /json/version CDP discovery (webSocketDebuggerUrl) + * WS /extension background.js connects here + * WS /devtools/browser/* Playwright connects via connectOverCDP * - * HTTP endpoints: - * POST /run { "raw": "click e5" } → { "text": "Clicked", "isError": false } + * CDP relay logic copied from Playwright's CDPRelayServer + * (playwright/lib/mcp/extension/cdpRelay.js). */ import { createServer } from 'node:http'; +import { randomUUID } from 'node:crypto'; +import { WebSocketServer, WebSocket } from 'ws'; import { parseInput } from './parser.mjs'; import { buildRunCode, verifyText, verifyElement, verifyValue, verifyList, @@ -23,21 +27,53 @@ export class CommandServer { this._engine = engine; this._server = null; this._port = null; + + // CDP relay state (matches CDPRelayServer) + this._playwrightConnection = null; + this._extensionConnection = null; + this._connectedTabInfo = undefined; + this._nextSessionId = 1; + + // WebSocket paths + const uuid = randomUUID(); + this._cdpPath = `/devtools/browser/${uuid}`; + this._extensionPath = '/extension'; + + // Extension connection promise + this._resetExtensionConnection(); } get port() { return this._port; } + get cdpPath() { return this._cdpPath; } async start(port = 3000) { this._port = port; this._server = createServer((req, res) => this._handleHttp(req, res)); + // WebSocket server + this._wss = new WebSocketServer({ server: this._server }); + this._wss.on('connection', (ws, req) => this._onConnection(ws, req)); + return new Promise((resolve, reject) => { this._server.listen(port, () => resolve()); this._server.on('error', reject); }); } + /** + * Wait for the extension's background.js to connect via WebSocket. + */ + async waitForExtension() { + if (this._extensionConnection) return; + await this._extensionConnectionPromise; + } + async close() { + this._closeConnections('Server stopped'); + if (this._wss) { + this._wss.close(); + this._wss = null; + } if (this._server) { await new Promise((resolve) => this._server.close(resolve)); this._server = null; @@ -58,6 +94,20 @@ export class CommandServer { return; } + // CDP discovery endpoint + const urlPath = req.url.replace(/\/+$/, ''); + if (req.method === 'GET' && urlPath === '/json/version') { + const wsUrl = `ws://127.0.0.1:${this._port}${this._cdpPath}`; + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ + 'Browser': 'Chrome/Extension-Bridge', + 'Protocol-Version': '1.3', + 'User-Agent': 'CDP-Bridge-Server/1.0.0', + 'webSocketDebuggerUrl': wsUrl, + })); + return; + } + // Panel command endpoint if (req.method === 'POST' && req.url === '/run') { try { @@ -83,6 +133,277 @@ export class CommandServer { res.writeHead(404); res.end('Not found'); } + + // ─── WebSocket connection routing ─────────────────────────────────────── + + _onConnection(ws, req) { + const url = new URL(`http://localhost${req.url}`); + debugLog(`New connection to ${url.pathname}`); + + if (url.pathname === this._cdpPath) { + this._handlePlaywrightConnection(ws); + } else if (url.pathname === this._extensionPath) { + this._handleExtensionConnection(ws); + } else { + debugLog(`Invalid path: ${url.pathname}`); + ws.close(4004, 'Invalid path'); + } + } + + // ─── Playwright connection ────────────────────────────────────────────── + + _handlePlaywrightConnection(ws) { + if (this._playwrightConnection) { + debugLog('Rejecting second Playwright connection'); + ws.close(1000, 'Another CDP client already connected'); + return; + } + + this._playwrightConnection = ws; + + ws.on('message', async (data) => { + try { + const message = JSON.parse(data.toString()); + await this._handlePlaywrightMessage(message); + } catch (error) { + debugLog(`Error while handling Playwright message\n${data.toString()}\n`, error); + } + }); + + ws.on('close', () => { + if (this._playwrightConnection !== ws) return; + this._playwrightConnection = null; + this._closeExtensionConnection('Playwright client disconnected'); + debugLog('Playwright WebSocket closed'); + }); + + ws.on('error', (error) => { + debugLog('Playwright WebSocket error:', error); + }); + + debugLog('Playwright MCP connected'); + } + + async _handlePlaywrightMessage(message) { + debugLog('← Playwright:', `${message.method} (id=${message.id})`); + const { id, sessionId, method, params } = message; + try { + const result = await this._handleCDPCommand(method, params, sessionId); + this._sendToPlaywright({ id, sessionId, result }); + } catch (e) { + debugLog('Error in the extension:', e); + this._sendToPlaywright({ + id, + sessionId, + error: { message: e.message }, + }); + } + } + + async _handleCDPCommand(method, params, sessionId) { + switch (method) { + case 'Browser.getVersion': { + return { + protocolVersion: '1.3', + product: 'Chrome/Extension-Bridge', + userAgent: 'CDP-Bridge-Server/1.0.0', + }; + } + case 'Browser.setDownloadBehavior': { + return {}; + } + case 'Target.setAutoAttach': { + if (sessionId) break; + const { targetInfo } = await this._extensionConnection.send('attachToTab', {}); + this._connectedTabInfo = { + targetInfo, + sessionId: `pw-tab-${this._nextSessionId++}`, + }; + debugLog('Simulating auto-attach'); + this._sendToPlaywright({ + method: 'Target.attachedToTarget', + params: { + sessionId: this._connectedTabInfo.sessionId, + targetInfo: { + ...this._connectedTabInfo.targetInfo, + attached: true, + }, + waitingForDebugger: false, + }, + }); + return {}; + } + case 'Target.getTargetInfo': { + return this._connectedTabInfo?.targetInfo; + } + } + return await this._forwardToExtension(method, params, sessionId); + } + + async _forwardToExtension(method, params, sessionId) { + if (!this._extensionConnection) + throw new Error('Extension not connected'); + if (this._connectedTabInfo?.sessionId === sessionId) + sessionId = undefined; + return await this._extensionConnection.send('forwardCDPCommand', { sessionId, method, params }); + } + + _sendToPlaywright(message) { + debugLog('→ Playwright:', `${message.method ?? `response(id=${message.id})`}`); + this._playwrightConnection?.send(JSON.stringify(message)); + } + + // ─── Extension connection ─────────────────────────────────────────────── + + _handleExtensionConnection(ws) { + if (this._extensionConnection) { + ws.close(1000, 'Another extension connection already established'); + return; + } + + this._extensionConnection = new ExtensionConnection(ws); + + this._extensionConnection.onclose = (c, reason) => { + debugLog('Extension WebSocket closed:', reason, c === this._extensionConnection); + if (this._extensionConnection !== c) return; + this._resetExtensionConnection(); + this._closePlaywrightConnection(`Extension disconnected: ${reason}`); + }; + + this._extensionConnection.onmessage = (method, params) => { + this._handleExtensionMessage(method, params); + }; + + this._extensionConnectionResolve?.(); + debugLog('Extension connected'); + } + + _handleExtensionMessage(method, params) { + switch (method) { + case 'forwardCDPEvent': { + const sessionId = params.sessionId || this._connectedTabInfo?.sessionId; + this._sendToPlaywright({ + sessionId, + method: params.method, + params: params.params, + }); + break; + } + } + } + + // ─── Connection lifecycle ─────────────────────────────────────────────── + + _closeConnections(reason) { + this._closePlaywrightConnection(reason); + this._closeExtensionConnection(reason); + } + + _closeExtensionConnection(reason) { + this._extensionConnection?.close(reason); + this._extensionConnectionReject?.(new Error(reason)); + this._resetExtensionConnection(); + } + + _resetExtensionConnection() { + this._connectedTabInfo = undefined; + this._extensionConnection = null; + this._extensionConnectionPromise = new Promise((resolve, reject) => { + this._extensionConnectionResolve = resolve; + this._extensionConnectionReject = reject; + }); + // Prevent unhandled rejection + this._extensionConnectionPromise.catch(() => {}); + } + + _closePlaywrightConnection(reason) { + if (this._playwrightConnection?.readyState === WebSocket.OPEN) + this._playwrightConnection.close(1000, reason); + this._playwrightConnection = null; + } +} + +// ─── ExtensionConnection (matches CDPRelayServer's inner class) ────────── + +class ExtensionConnection { + constructor(ws) { + this._callbacks = new Map(); + this._lastId = 0; + this._ws = ws; + this._ws.on('message', (data) => this._onMessage(data)); + this._ws.on('close', (code, reason) => this._onClose(code, reason)); + this._ws.on('error', (error) => this._onError(error)); + } + + async send(method, params) { + if (this._ws.readyState !== WebSocket.OPEN) + throw new Error(`Unexpected WebSocket state: ${this._ws.readyState}`); + const id = ++this._lastId; + this._ws.send(JSON.stringify({ id, method, params })); + const error = new Error(`Protocol error: ${method}`); + return new Promise((resolve, reject) => { + this._callbacks.set(id, { resolve, reject, error }); + }); + } + + close(message) { + debugLog('closing extension connection:', message); + if (this._ws.readyState === WebSocket.OPEN) + this._ws.close(1000, message); + } + + _onMessage(data) { + const eventData = data.toString(); + let parsedJson; + try { + parsedJson = JSON.parse(eventData); + } catch (e) { + debugLog(` Closing websocket due to malformed JSON. eventData=${eventData} e=${e?.message}`); + this._ws.close(); + return; + } + try { + this._handleParsedMessage(parsedJson); + } catch (e) { + debugLog(` Closing websocket due to failed onmessage callback. eventData=${eventData} e=${e?.message}`); + this._ws.close(); + } + } + + _handleParsedMessage(object) { + if (object.id && this._callbacks.has(object.id)) { + const callback = this._callbacks.get(object.id); + this._callbacks.delete(object.id); + if (object.error) { + const error = callback.error; + error.message = object.error; + callback.reject(error); + } else { + callback.resolve(object.result); + } + } else if (object.id) { + debugLog('← Extension: unexpected response', object); + } else { + this.onmessage?.(object.method, object.params); + } + } + + _onClose(code, reason) { + debugLog(` code=${code} reason=${reason}`); + this._dispose(); + this.onclose?.(this, reason?.toString() || ''); + } + + _onError(error) { + debugLog(` message=${error.message}`); + this._dispose(); + } + + _dispose() { + for (const callback of this._callbacks.values()) + callback.reject(new Error('WebSocket closed')); + this._callbacks.clear(); + } } // ─── REPL-level argument transformations ──────────────────────────────────── @@ -152,3 +473,7 @@ function readBody(req) { req.on('end', () => resolve(data)); }); } + +function debugLog(...args) { + console.log('[relay]', ...args); +} diff --git a/packages/extension/background.js b/packages/extension/background.js index dbfb38e..bfd53c7 100644 --- a/packages/extension/background.js +++ b/packages/extension/background.js @@ -301,18 +301,62 @@ chrome.debugger.onEvent.addListener((source, method, params) => { } }); -// ─── Panel port management ────────────────────────────────────────────────── +// ─── Panel port management + auto-connect relay ───────────────────────────── chrome.runtime.onConnect.addListener((port) => { if (!port.name.startsWith('pw-panel-')) return; const tabId = parseInt(port.name.replace('pw-panel-', ''), 10); panelPorts[tabId] = port; + // Auto-connect CDP relay to CommandServer when panel opens. + // This enables Phase 2: Playwright controls the inspected tab directly. + autoConnectRelay(tabId); + port.onDisconnect.addListener(() => { delete panelPorts[tabId]; }); }); +/** + * Auto-connect a CDP relay WebSocket to the CommandServer's /extension endpoint. + * Called when a DevTools panel opens for a tab. + */ +async function autoConnectRelay(tabId) { + try { + // Close existing relay if any + if (activeConnection) { + activeConnection.close('New panel opened'); + activeConnection = null; + await setConnectedTabId(null); + } + + const wsUrl = `ws://127.0.0.1:${serverPort}/extension`; + debugLog(`Auto-connecting relay for tab ${tabId} to ${wsUrl}`); + + const socket = new WebSocket(wsUrl); + await new Promise((resolve, reject) => { + socket.onopen = () => resolve(); + socket.onerror = () => reject(new Error('WebSocket connection failed')); + setTimeout(() => reject(new Error('Connection timeout')), 5000); + }); + + activeConnection = new RelayConnection(socket); + activeConnection.setTabId(tabId); + activeConnection.onclose = () => { + debugLog('Auto-connect relay closed'); + activeConnection = null; + void setConnectedTabId(null); + }; + + await setConnectedTabId(tabId); + debugLog(`Auto-connected relay for tab ${tabId}`); + } catch (e) { + debugLog(`Auto-connect relay failed: ${e.message}`); + // Not fatal — the server might not be running yet. + // User can manually connect later or restart. + } +} + // ─── Exports (for testing) ────────────────────────────────────────────────── export { diff --git a/packages/extension/connect.html b/packages/extension/connect.html index 1f0cf61..542053b 100644 --- a/packages/extension/connect.html +++ b/packages/extension/connect.html @@ -25,137 +25,6 @@
- - + diff --git a/packages/extension/connect.js b/packages/extension/connect.js new file mode 100644 index 0000000..00d36ff --- /dev/null +++ b/packages/extension/connect.js @@ -0,0 +1,137 @@ +const params = new URLSearchParams(window.location.search); +const mcpRelayUrl = params.get('mcpRelayUrl'); +const clientRaw = params.get('client') || '{}'; +const newTab = params.get('newTab') === 'true'; +const token = params.get('token'); + +const statusEl = document.getElementById('status'); +const buttonsEl = document.getElementById('buttons'); +const tabSectionEl = document.getElementById('tab-section'); + +let clientInfo = 'unknown'; +try { + const client = JSON.parse(clientRaw); + clientInfo = `${client.name}/${client.version}`; +} catch (e) {} + +function showStatus(type, message) { + statusEl.className = `status ${type}`; + statusEl.textContent = message; +} + +function showError(message) { + showStatus('error', message); + buttonsEl.innerHTML = ''; + tabSectionEl.innerHTML = ''; +} + +async function connectToMCPRelay() { + const response = await chrome.runtime.sendMessage({ type: 'connectToMCPRelay', mcpRelayUrl }); + if (!response.success) { + showError(response.error); + return false; + } + return true; +} + +async function connectToTab(tabId, windowId) { + buttonsEl.innerHTML = ''; + tabSectionEl.innerHTML = ''; + + try { + const response = await chrome.runtime.sendMessage({ + type: 'connectToTab', + mcpRelayUrl, + tabId, + windowId, + }); + + if (response?.success) { + showStatus('connected', `MCP client "${clientInfo}" connected.`); + } else { + showError(response?.error || `MCP client "${clientInfo}" failed to connect.`); + } + } catch (e) { + showError(`MCP client "${clientInfo}" failed to connect: ${e}`); + } +} + +async function loadTabs() { + const response = await chrome.runtime.sendMessage({ type: 'getTabs' }); + if (!response.success) { + showError('Failed to load tabs: ' + response.error); + return; + } + + tabSectionEl.innerHTML = '

Select page to expose to MCP server:

'; + for (const tab of response.tabs) { + const item = document.createElement('div'); + item.className = 'tab-item'; + const titleDiv = document.createElement('div'); + titleDiv.style.cssText = 'flex:1;min-width:0'; + const titleText = document.createElement('div'); + titleText.className = 'tab-title'; + titleText.textContent = tab.title || ''; + const urlText = document.createElement('div'); + urlText.className = 'tab-url'; + urlText.textContent = tab.url || ''; + titleDiv.append(titleText, urlText); + const btn = document.createElement('button'); + btn.className = 'btn-connect'; + btn.textContent = 'Connect'; + btn.onclick = () => connectToTab(tab.id, tab.windowId); + item.append(titleDiv, btn); + tabSectionEl.appendChild(item); + } +} + +// Listen for connection timeout +chrome.runtime.onMessage.addListener((message) => { + if (message.type === 'connectionTimeout') + showError('Connection timed out.'); +}); + +// ── Main flow ── +async function main() { + if (!mcpRelayUrl) { + showError('Missing mcpRelayUrl parameter in URL.'); + return; + } + + try { + const host = new URL(mcpRelayUrl).hostname; + if (host !== '127.0.0.1' && host !== '[::1]') { + showError(`Only loopback connections allowed. Received host: ${host}`); + return; + } + } catch (e) { + showError(`Invalid mcpRelayUrl: ${mcpRelayUrl}`); + return; + } + + showStatus('connecting', `Playwright MCP started from "${clientInfo}" is trying to connect.`); + + const ok = await connectToMCPRelay(); + if (!ok) return; + + if (newTab) { + const allowBtn = document.createElement('button'); + allowBtn.className = 'btn-allow'; + allowBtn.textContent = 'Allow'; + allowBtn.onclick = () => connectToTab(); + const rejectBtn = document.createElement('button'); + rejectBtn.className = 'btn-reject'; + rejectBtn.textContent = 'Reject'; + rejectBtn.onclick = () => showError('Connection rejected. This tab can be closed.'); + buttonsEl.append(allowBtn, rejectBtn); + } else { + const rejectBtn = document.createElement('button'); + rejectBtn.className = 'btn-reject'; + rejectBtn.textContent = 'Reject'; + rejectBtn.onclick = () => showError('Connection rejected. This tab can be closed.'); + buttonsEl.appendChild(rejectBtn); + await loadTabs(); + } +} + +main(); From 6e3312ef360399620ae26b27e47579532226b183 Mon Sep 17 00:00:00 2001 From: Steve Zhang Date: Thu, 19 Feb 2026 23:30:50 -0500 Subject: [PATCH 04/27] extension: --no-spawn mode with auto-connect relay via blank tab Add --no-spawn flag for extension mode: instead of spawning a new Chrome window, the engine waits for a DevTools panel to connect. When the panel opens, autoConnectRelay creates a blank control tab and connects it to CDPRelayServer, avoiding the chrome.debugger + DevTools CDP conflict. - CLI: add --no-spawn boolean flag, pass spawn option to engine - Engine: split extension branch into spawn/no-spawn paths (30s/120s timeout) - Engine: expose relay reference on CommandServer for /relay-info endpoint - CommandServer: add GET /relay-info returning CDPRelayServer WS endpoint - background.js: autoConnectRelay fetches /relay-info, creates blank tab, wires RelayConnection to CDPRelayServer (same protocol as connect.html) Co-Authored-By: Claude Opus 4.6 --- packages/cli/bin/playwright-repl.mjs | 2 ++ packages/core/src/engine.mjs | 40 +++++++++++++++----------- packages/core/src/extension-server.mjs | 15 +++++++++- packages/extension/background.js | 38 +++++++++++++++++------- 4 files changed, 68 insertions(+), 27 deletions(-) diff --git a/packages/cli/bin/playwright-repl.mjs b/packages/cli/bin/playwright-repl.mjs index 355b420..00ecb27 100644 --- a/packages/cli/bin/playwright-repl.mjs +++ b/packages/cli/bin/playwright-repl.mjs @@ -39,6 +39,7 @@ Options: --profile Persistent profile directory --connect [port] Connect to existing Chrome via CDP (default: 9222) --extension Start WebSocket server for Chrome extension + --no-spawn Don't spawn Chrome (wait for DevTools panel to connect) --port Extension server port (default: 3000) --config Path to config file --replay Replay a .pw session file @@ -81,6 +82,7 @@ startRepl({ profile: args.profile, connect: args.connect, extension: args.extension, + spawn: args.spawn, port: args.port ? parseInt(args.port, 10) : undefined, config: args.config, replay: args.replay, diff --git a/packages/core/src/engine.mjs b/packages/core/src/engine.mjs index a65260c..6b88999 100644 --- a/packages/core/src/engine.mjs +++ b/packages/core/src/engine.mjs @@ -86,6 +86,7 @@ export class Engine { await new Promise(r => relayHttp.listen(relayPort, '127.0.0.1', r)); const relay = new deps.CDPRelayServer(relayHttp, opts.browser || 'chrome'); this._relayHttp = relayHttp; + this._commandServer.relay = relay; // Spawn Chrome with our extension's connect.html pointing at CDPRelayServer. const extensionId = opts.extensionId || 'hofgdkanlhhkikiomnnndihbefnjhlmp'; @@ -93,22 +94,29 @@ export class Engine { connectUrl.searchParams.set('mcpRelayUrl', relay.extensionEndpoint()); connectUrl.searchParams.set('client', JSON.stringify({ name: 'playwright-repl', version: replVersion })); - const execInfo = deps.registry.findExecutable(opts.browser || 'chrome'); - const execPath = execInfo?.executablePath(); - if (!execPath) - throw new Error('Chrome executable not found. Make sure Chrome is installed.'); - - const { spawn } = await import('node:child_process'); - spawn(execPath, [connectUrl.toString()], { - detached: true, stdio: 'ignore', windowsHide: true, - }); - - // Wait for extension to connect to CDPRelayServer. - console.log('Waiting for extension to connect...'); - await Promise.race([ - relay._extensionConnectionPromise, - new Promise((_, reject) => setTimeout(() => reject(new Error('Extension connection timeout (30s)')), 30000)), - ]); + if (opts.spawn !== false) { + const execInfo = deps.registry.findExecutable(opts.browser || 'chrome'); + const execPath = execInfo?.executablePath(); + if (!execPath) + throw new Error('Chrome executable not found. Make sure Chrome is installed.'); + + const { spawn } = await import('node:child_process'); + spawn(execPath, [connectUrl.toString()], { + detached: true, stdio: 'ignore', windowsHide: true, + }); + + console.log('Waiting for extension to connect...'); + await Promise.race([ + relay._extensionConnectionPromise, + new Promise((_, reject) => setTimeout(() => reject(new Error('Extension connection timeout (30s)')), 30000)), + ]); + } else { + console.log('Waiting for DevTools panel to connect... Open DevTools on any tab.'); + await Promise.race([ + relay._extensionConnectionPromise, + new Promise((_, reject) => setTimeout(() => reject(new Error('Extension connection timeout (120s). No DevTools panel connected.')), 120000)), + ]); + } console.log('Extension connected. Connecting Playwright...'); // Connect Playwright through CDPRelayServer — exactly like ExtensionContextFactory. diff --git a/packages/core/src/extension-server.mjs b/packages/core/src/extension-server.mjs index 371fac5..c221cfe 100644 --- a/packages/core/src/extension-server.mjs +++ b/packages/core/src/extension-server.mjs @@ -94,8 +94,21 @@ export class CommandServer { return; } - // CDP discovery endpoint const urlPath = req.url.replace(/\/+$/, ''); + + // Relay info endpoint — background.js uses this to discover the CDPRelayServer WS URL. + if (req.method === 'GET' && urlPath === '/relay-info') { + if (!this.relay) { + res.writeHead(503, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Relay not ready' })); + return; + } + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ extensionEndpoint: this.relay.extensionEndpoint() })); + return; + } + + // CDP discovery endpoint if (req.method === 'GET' && urlPath === '/json/version') { const wsUrl = `ws://127.0.0.1:${this._port}${this._cdpPath}`; res.writeHead(200, { 'Content-Type': 'application/json' }); diff --git a/packages/extension/background.js b/packages/extension/background.js index bfd53c7..846f6e8 100644 --- a/packages/extension/background.js +++ b/packages/extension/background.js @@ -318,10 +318,16 @@ chrome.runtime.onConnect.addListener((port) => { }); /** - * Auto-connect a CDP relay WebSocket to the CommandServer's /extension endpoint. - * Called when a DevTools panel opens for a tab. + * Auto-connect relay when a DevTools panel opens. + * Mimics the spawn-mode flow (connectToMCPRelay + connectToTab) without + * opening connect.html or requiring user interaction: + * 1. Fetch /relay-info to discover CDPRelayServer's WS endpoint + * 2. Create WebSocket + RelayConnection (same as connectToMCPRelay) + * 3. Create a new blank tab for Playwright to control (avoids DevTools + * conflict — chrome.debugger can't share a tab with open DevTools) + * 4. setTabId on the connection (same as connectToTab) */ -async function autoConnectRelay(tabId) { +async function autoConnectRelay(inspectedTabId) { try { // Close existing relay if any if (activeConnection) { @@ -330,30 +336,42 @@ async function autoConnectRelay(tabId) { await setConnectedTabId(null); } - const wsUrl = `ws://127.0.0.1:${serverPort}/extension`; - debugLog(`Auto-connecting relay for tab ${tabId} to ${wsUrl}`); + // 1. Discover the CDPRelayServer's WebSocket endpoint. + const infoRes = await fetch(`http://127.0.0.1:${serverPort}/relay-info`); + if (!infoRes.ok) throw new Error(`/relay-info returned ${infoRes.status}`); + const { extensionEndpoint } = await infoRes.json(); + if (!extensionEndpoint) throw new Error('/relay-info missing extensionEndpoint'); - const socket = new WebSocket(wsUrl); + debugLog(`Auto-connecting relay to ${extensionEndpoint}`); + + // 2. Connect WebSocket to CDPRelayServer (same as connectToMCPRelay). + const socket = new WebSocket(extensionEndpoint); await new Promise((resolve, reject) => { socket.onopen = () => resolve(); socket.onerror = () => reject(new Error('WebSocket connection failed')); setTimeout(() => reject(new Error('Connection timeout')), 5000); }); + // 3. Create a new blank tab for Playwright to control. + // We can't use inspectedTabId because DevTools is open on it, + // and chrome.debugger conflicts with an active DevTools session. + const controlTab = await chrome.tabs.create({ active: false, url: 'about:blank' }); + debugLog(`Created control tab ${controlTab.id} for Playwright`); + + // 4. Wire up RelayConnection and set the tab ID (same as connectToTab). activeConnection = new RelayConnection(socket); - activeConnection.setTabId(tabId); + activeConnection.setTabId(controlTab.id); activeConnection.onclose = () => { debugLog('Auto-connect relay closed'); activeConnection = null; void setConnectedTabId(null); }; - await setConnectedTabId(tabId); - debugLog(`Auto-connected relay for tab ${tabId}`); + await setConnectedTabId(controlTab.id); + debugLog(`Auto-connected relay for control tab ${controlTab.id}`); } catch (e) { debugLog(`Auto-connect relay failed: ${e.message}`); // Not fatal — the server might not be running yet. - // User can manually connect later or restart. } } From 14b4e38a60f380a37b2d8e756fe3c9d8029dfc96 Mon Sep 17 00:00:00 2001 From: Steve Zhang Date: Thu, 19 Feb 2026 23:59:48 -0500 Subject: [PATCH 05/27] chore: gitignore .playwright-mcp and remove cached screenshots Co-Authored-By: Claude Opus 4.6 --- .gitignore | 1 + .../page-2026-02-19T12-08-58-172Z.png | Bin 99400 -> 0 bytes .../page-2026-02-19T12-09-50-744Z.png | Bin 109193 -> 0 bytes .../page-2026-02-19T12-49-02-980Z.png | Bin 56027 -> 0 bytes .../page-2026-02-19T12-53-41-800Z.png | Bin 46737 -> 0 bytes 5 files changed, 1 insertion(+) delete mode 100644 .playwright-mcp/page-2026-02-19T12-08-58-172Z.png delete mode 100644 .playwright-mcp/page-2026-02-19T12-09-50-744Z.png delete mode 100644 .playwright-mcp/page-2026-02-19T12-49-02-980Z.png delete mode 100644 .playwright-mcp/page-2026-02-19T12-53-41-800Z.png diff --git a/.gitignore b/.gitignore index cc832be..b9d2b3c 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ node_modules/ .claude/ .playwright-cli/ coverage/ +.playwright-mcp/ diff --git a/.playwright-mcp/page-2026-02-19T12-08-58-172Z.png b/.playwright-mcp/page-2026-02-19T12-08-58-172Z.png deleted file mode 100644 index 62e71f917864b42224a951d6aaee7979d7706ded..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 99400 zcmeFZWmH_>_AN++2oiz^5AH67LlWHG-JRf2SO@`v2X~i3f)oyg1$TFMcZWjW$-Vb? z|J`GBe|+yt_xV(#WbbqKUVE*%=9;U5739QGk?@fa5D-u$B}9}E5D>=^5T4J!c@Dgj z{uuES0pUG@q{t@~_tb+$#ME&!lGi5_o=2}1R*#PC+I53$SU!B|nlbQyTMm6@OyJq= zh4Ko;jjE0h#clhSzf%Hu`AIi3maDhA>FTA=@?ubR6qoE6$1t;ey0{ewJ{~Z~zpnCd zy|P+wBia}Lyiw}6f%u=-t*XBo|9QJEB=OmQUVm#04h~)=jNoPd=R=RP^++LL)Fhd! ztrYvQmaQCx?f(wqpj~5=H4{K=Q9Z|LJ*5#QdiM7L|6VJZ@ayB{dZ+FS4ko6fy~*M& z%#R-b%<}bzR>|XbhA+dbqlJ2Qa`N^ItX|}Q{|@0Bx$D8qr`6C-VgEnnmg7|8$`t>- z7uWv2z6NhN*LFc&U0ru1NoC|{E&4ydTU=OJC{ioA+ZiR_SM>AqGc+_jFpe6vF!|3H zT0II1N+zu)wbJw;pbr@aAN7BBl9AzrZn72XP{l~3`obdrwOs$5PA+GffQ_w^LyPD| zzzb29BRizL&qLg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w`6<1Y*_oVFSPpDcW-fyzM|BZ@F)g?-On!!7G%yr5LrO2D57mguDl%?G>|a<)bK& zJO8K)1$3ocknB(<{I$J7vxkL8%1dmcr3n^VX zc-R*S-d>E@#zkr4*uwnEkx*v6PLp{q<*`L^q$L8G>G#F|jia-G>|wqhe?FZw5_M`VF_l4=uaQJ|lZjAjAF2iKgg|*|!tY z%Zq!ndYb*D>(7H+3qW8Z51do7v8M!A65>jID}qtk#wG4L((>!NJjs;H#<-kVA4l?+ zK$+T{Vr?eZ?!=Y9_!ZDBgg)E)mPTR$axY)JXx~lVa%iLV%$3clCrJPQ+D+$jmsV$M zYv}P|TO32w-jBZ2YtU*t+Ef6W64c)jh)Dk#e67!rguz(n$B%m}BgumMjDLrnQ56;b zX+j#@W-~E+Gkdd0O|`^-S267T*RP811m-RX^)lo2;ciZOhHJF18nBTt4%JT+Lj3g9 z(z=(Im-mOm_b*y@?klo*8IFWtWu4sI-1dR_P@47JIw@P(Y%3#9!-Uq|1drn+aM{ZK zI87vOKjYh+%h`WHbohCSFM(-)SDj{6l$|Q5OaHh5|*Y6zK3pFNED+(Xk9v$pg&1}iVDP69pw}EH( zOXI}JR|wy8>2VUYAmQizBC?Kz0f6JL0Lj{#7b*)^p<|GklBbW_h%w_NAW G{eJ)tyDz)| diff --git a/.playwright-mcp/page-2026-02-19T12-53-41-800Z.png b/.playwright-mcp/page-2026-02-19T12-53-41-800Z.png deleted file mode 100644 index 7fa348cfdf5492ae56bc45e3712af962e9d6eccf..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 46737 zcmc$_WmH_j_a#a~0>Kl41PBn^A-Dxdg1bZT1b2cvBoH732<{GzH0}-!!QEXtxYKx} z-E+xr=B@RAYu0>tvu550Rg2Um;v6$;986j_N68Xjo}%NY6un@IHIc}GOgao?FSuuy>=})$#FibWefLewN3?!cxp^;Ci@tWB$_|_<6tdd>Huo)*#CS{Gf0) zc*D#7dQAPh_pC&>mRU>;Ix=E^cXhI1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IP: repl-ext package using playwright-crx (side panel extension) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New packages/repl-ext/ built with playwright-crx v0.15 (Playwright 1.53). Runs Playwright directly in extension service worker via CrxTransport. Working: - Side panel UI (editor, console, toolbar, pw> prompt) - snapshot: accessibility tree with ref system (e1, e2...) - click/fill/type/press/hover/select/check/uncheck via refs - goto/back/forward/reload via chrome.tabs API (bypasses CDP lifecycle) - screenshot, wait, title, url, help commands - Auto-attach to active tab, about:blank bootstrap for cold start Known limitations: - crxApp.attach() is unreliable ("Frame has been detached") — upstream playwright-crx issue (#93/#104), attach sometimes needs retry - page.goto() times out on service worker sites — workaround: use chrome.tabs.update() for all navigation - Toolbar buttons (Record, Open, Save, Export) are visual only Co-Authored-By: Claude Opus 4.6 --- package-lock.json | 1011 +- packages/repl-ext/dist/background.js | 143614 ++++++++++++++++++++ packages/repl-ext/dist/background.js.map | 1 + packages/repl-ext/dist/manifest.json | 17 + packages/repl-ext/dist/panel.css | 233 + packages/repl-ext/dist/panel.html | 57 + packages/repl-ext/dist/panel.js | 174 + packages/repl-ext/dist/panel.js.map | 1 + packages/repl-ext/package.json | 18 + packages/repl-ext/panel.html | 57 + packages/repl-ext/public/manifest.json | 17 + packages/repl-ext/src/background.ts | 150 + packages/repl-ext/src/commands.ts | 122 + packages/repl-ext/src/panel/panel.css | 233 + packages/repl-ext/src/panel/panel.ts | 174 + packages/repl-ext/src/snapshot.ts | 96 + packages/repl-ext/tsconfig.json | 23 + packages/repl-ext/vite.config.ts | 23 + 18 files changed, 145913 insertions(+), 108 deletions(-) create mode 100644 packages/repl-ext/dist/background.js create mode 100644 packages/repl-ext/dist/background.js.map create mode 100644 packages/repl-ext/dist/manifest.json create mode 100644 packages/repl-ext/dist/panel.css create mode 100644 packages/repl-ext/dist/panel.html create mode 100644 packages/repl-ext/dist/panel.js create mode 100644 packages/repl-ext/dist/panel.js.map create mode 100644 packages/repl-ext/package.json create mode 100644 packages/repl-ext/panel.html create mode 100644 packages/repl-ext/public/manifest.json create mode 100644 packages/repl-ext/src/background.ts create mode 100644 packages/repl-ext/src/commands.ts create mode 100644 packages/repl-ext/src/panel/panel.css create mode 100644 packages/repl-ext/src/panel/panel.ts create mode 100644 packages/repl-ext/src/snapshot.ts create mode 100644 packages/repl-ext/tsconfig.json create mode 100644 packages/repl-ext/vite.config.ts diff --git a/package-lock.json b/package-lock.json index 1ae68f9..d026453 100644 --- a/package-lock.json +++ b/package-lock.json @@ -550,14 +550,63 @@ "resolved": "packages/core", "link": true }, + "node_modules/@playwright-repl/crx": { + "resolved": "packages/crx", + "link": true + }, "node_modules/@playwright-repl/extension": { "resolved": "packages/extension", "link": true }, + "node_modules/@rollup/pluginutils": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-3.1.0.tgz", + "integrity": "sha512-GksZ6pr6TpIjHm8h9lSQ8pi8BE9VeubNT0OMJ3B5uZJ8pz73NPiqOtCog/x2/QzM1ENChPKxMDhiQuRHsqc+lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "0.0.39", + "estree-walker": "^1.0.1", + "picomatch": "^2.2.2" + }, + "engines": { + "node": ">= 8.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0" + } + }, + "node_modules/@rollup/pluginutils/node_modules/@types/estree": { + "version": "0.0.39", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.39.tgz", + "integrity": "sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/pluginutils/node_modules/estree-walker": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-1.0.1.tgz", + "integrity": "sha512-1fMXF3YP4pZZVozF8j/ZLfvnR8NSIljt56UhbZ5PeeDmmGHpgpdwQt7ITlGvYaQukCvuBRMLEiKiYC+oeIg4cg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/pluginutils/node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.57.1.tgz", - "integrity": "sha512-A6ehUVSiSaaliTxai040ZpZ2zTevHYbvu/lDoeAteHI8QnaosIzm4qwtezfRg1jOYaUmnzLX1AOD6Z+UJjtifg==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.58.0.tgz", + "integrity": "sha512-mr0tmS/4FoVk1cnaeN244A/wjvGDNItZKR8hRhnmCzygyRXYtKF5jVDSIILR1U97CTzAYmbgIj/Dukg62ggG5w==", "cpu": [ "arm" ], @@ -569,9 +618,9 @@ ] }, "node_modules/@rollup/rollup-android-arm64": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.57.1.tgz", - "integrity": "sha512-dQaAddCY9YgkFHZcFNS/606Exo8vcLHwArFZ7vxXq4rigo2bb494/xKMMwRRQW6ug7Js6yXmBZhSBRuBvCCQ3w==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.58.0.tgz", + "integrity": "sha512-+s++dbp+/RTte62mQD9wLSbiMTV+xr/PeRJEc/sFZFSBRlHPNPVaf5FXlzAL77Mr8FtSfQqCN+I598M8U41ccQ==", "cpu": [ "arm64" ], @@ -583,9 +632,9 @@ ] }, "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.57.1.tgz", - "integrity": "sha512-crNPrwJOrRxagUYeMn/DZwqN88SDmwaJ8Cvi/TN1HnWBU7GwknckyosC2gd0IqYRsHDEnXf328o9/HC6OkPgOg==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.58.0.tgz", + "integrity": "sha512-MFWBwTcYs0jZbINQBXHfSrpSQJq3IUOakcKPzfeSznONop14Pxuqa0Kg19GD0rNBMPQI2tFtu3UzapZpH0Uc1Q==", "cpu": [ "arm64" ], @@ -597,9 +646,9 @@ ] }, "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.57.1.tgz", - "integrity": "sha512-Ji8g8ChVbKrhFtig5QBV7iMaJrGtpHelkB3lsaKzadFBe58gmjfGXAOfI5FV0lYMH8wiqsxKQ1C9B0YTRXVy4w==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.58.0.tgz", + "integrity": "sha512-yiKJY7pj9c9JwzuKYLFaDZw5gma3fI9bkPEIyofvVfsPqjCWPglSHdpdwXpKGvDeYDms3Qal8qGMEHZ1M/4Udg==", "cpu": [ "x64" ], @@ -611,9 +660,9 @@ ] }, "node_modules/@rollup/rollup-freebsd-arm64": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.57.1.tgz", - "integrity": "sha512-R+/WwhsjmwodAcz65guCGFRkMb4gKWTcIeLy60JJQbXrJ97BOXHxnkPFrP+YwFlaS0m+uWJTstrUA9o+UchFug==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.58.0.tgz", + "integrity": "sha512-x97kCoBh5MOevpn/CNK9W1x8BEzO238541BGWBc315uOlN0AD/ifZ1msg+ZQB05Ux+VF6EcYqpiagfLJ8U3LvQ==", "cpu": [ "arm64" ], @@ -625,9 +674,9 @@ ] }, "node_modules/@rollup/rollup-freebsd-x64": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.57.1.tgz", - "integrity": "sha512-IEQTCHeiTOnAUC3IDQdzRAGj3jOAYNr9kBguI7MQAAZK3caezRrg0GxAb6Hchg4lxdZEI5Oq3iov/w/hnFWY9Q==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.58.0.tgz", + "integrity": "sha512-Aa8jPoZ6IQAG2eIrcXPpjRcMjROMFxCt1UYPZZtCxRV68WkuSigYtQ/7Zwrcr2IvtNJo7T2JfDXyMLxq5L4Jlg==", "cpu": [ "x64" ], @@ -639,9 +688,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.57.1.tgz", - "integrity": "sha512-F8sWbhZ7tyuEfsmOxwc2giKDQzN3+kuBLPwwZGyVkLlKGdV1nvnNwYD0fKQ8+XS6hp9nY7B+ZeK01EBUE7aHaw==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.58.0.tgz", + "integrity": "sha512-Ob8YgT5kD/lSIYW2Rcngs5kNB/44Q2RzBSPz9brf2WEtcGR7/f/E9HeHn1wYaAwKBni+bdXEwgHvUd0x12lQSA==", "cpu": [ "arm" ], @@ -653,9 +702,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.57.1.tgz", - "integrity": "sha512-rGfNUfn0GIeXtBP1wL5MnzSj98+PZe/AXaGBCRmT0ts80lU5CATYGxXukeTX39XBKsxzFpEeK+Mrp9faXOlmrw==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.58.0.tgz", + "integrity": "sha512-K+RI5oP1ceqoadvNt1FecL17Qtw/n9BgRSzxif3rTL2QlIu88ccvY+Y9nnHe/cmT5zbH9+bpiJuG1mGHRVwF4Q==", "cpu": [ "arm" ], @@ -667,9 +716,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.57.1.tgz", - "integrity": "sha512-MMtej3YHWeg/0klK2Qodf3yrNzz6CGjo2UntLvk2RSPlhzgLvYEB3frRvbEF2wRKh1Z2fDIg9KRPe1fawv7C+g==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.58.0.tgz", + "integrity": "sha512-T+17JAsCKUjmbopcKepJjHWHXSjeW7O5PL7lEFaeQmiVyw4kkc5/lyYKzrv6ElWRX/MrEWfPiJWqbTvfIvjM1Q==", "cpu": [ "arm64" ], @@ -681,9 +730,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.57.1.tgz", - "integrity": "sha512-1a/qhaaOXhqXGpMFMET9VqwZakkljWHLmZOX48R0I/YLbhdxr1m4gtG1Hq7++VhVUmf+L3sTAf9op4JlhQ5u1Q==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.58.0.tgz", + "integrity": "sha512-cCePktb9+6R9itIJdeCFF9txPU7pQeEHB5AbHu/MKsfH/k70ZtOeq1k4YAtBv9Z7mmKI5/wOLYjQ+B9QdxR6LA==", "cpu": [ "arm64" ], @@ -695,9 +744,9 @@ ] }, "node_modules/@rollup/rollup-linux-loong64-gnu": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.57.1.tgz", - "integrity": "sha512-QWO6RQTZ/cqYtJMtxhkRkidoNGXc7ERPbZN7dVW5SdURuLeVU7lwKMpo18XdcmpWYd0qsP1bwKPf7DNSUinhvA==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.58.0.tgz", + "integrity": "sha512-iekUaLkfliAsDl4/xSdoCJ1gnnIXvoNz85C8U8+ZxknM5pBStfZjeXgB8lXobDQvvPRCN8FPmmuTtH+z95HTmg==", "cpu": [ "loong64" ], @@ -709,9 +758,9 @@ ] }, "node_modules/@rollup/rollup-linux-loong64-musl": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.57.1.tgz", - "integrity": "sha512-xpObYIf+8gprgWaPP32xiN5RVTi/s5FCR+XMXSKmhfoJjrpRAjCuuqQXyxUa/eJTdAE6eJ+KDKaoEqjZQxh3Gw==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.58.0.tgz", + "integrity": "sha512-68ofRgJNl/jYJbxFjCKE7IwhbfxOl1muPN4KbIqAIe32lm22KmU7E8OPvyy68HTNkI2iV/c8y2kSPSm2mW/Q9Q==", "cpu": [ "loong64" ], @@ -723,9 +772,9 @@ ] }, "node_modules/@rollup/rollup-linux-ppc64-gnu": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.57.1.tgz", - "integrity": "sha512-4BrCgrpZo4hvzMDKRqEaW1zeecScDCR+2nZ86ATLhAoJ5FQ+lbHVD3ttKe74/c7tNT9c6F2viwB3ufwp01Oh2w==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.58.0.tgz", + "integrity": "sha512-dpz8vT0i+JqUKuSNPCP5SYyIV2Lh0sNL1+FhM7eLC457d5B9/BC3kDPp5BBftMmTNsBarcPcoz5UGSsnCiw4XQ==", "cpu": [ "ppc64" ], @@ -737,9 +786,9 @@ ] }, "node_modules/@rollup/rollup-linux-ppc64-musl": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.57.1.tgz", - "integrity": "sha512-NOlUuzesGauESAyEYFSe3QTUguL+lvrN1HtwEEsU2rOwdUDeTMJdO5dUYl/2hKf9jWydJrO9OL/XSSf65R5+Xw==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.58.0.tgz", + "integrity": "sha512-4gdkkf9UJ7tafnweBCR/mk4jf3Jfl0cKX9Np80t5i78kjIH0ZdezUv/JDI2VtruE5lunfACqftJ8dIMGN4oHew==", "cpu": [ "ppc64" ], @@ -751,9 +800,9 @@ ] }, "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.57.1.tgz", - "integrity": "sha512-ptA88htVp0AwUUqhVghwDIKlvJMD/fmL/wrQj99PRHFRAG6Z5nbWoWG4o81Nt9FT+IuqUQi+L31ZKAFeJ5Is+A==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.58.0.tgz", + "integrity": "sha512-YFS4vPnOkDTD/JriUeeZurFYoJhPf9GQQEF/v4lltp3mVcBmnsAdjEWhr2cjUCZzZNzxCG0HZOvJU44UGHSdzw==", "cpu": [ "riscv64" ], @@ -765,9 +814,9 @@ ] }, "node_modules/@rollup/rollup-linux-riscv64-musl": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.57.1.tgz", - "integrity": "sha512-S51t7aMMTNdmAMPpBg7OOsTdn4tySRQvklmL3RpDRyknk87+Sp3xaumlatU+ppQ+5raY7sSTcC2beGgvhENfuw==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.58.0.tgz", + "integrity": "sha512-x2xgZlFne+QVNKV8b4wwaCS8pwq3y14zedZ5DqLzjdRITvreBk//4Knbcvm7+lWmms9V9qFp60MtUd0/t/PXPw==", "cpu": [ "riscv64" ], @@ -779,9 +828,9 @@ ] }, "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.57.1.tgz", - "integrity": "sha512-Bl00OFnVFkL82FHbEqy3k5CUCKH6OEJL54KCyx2oqsmZnFTR8IoNqBF+mjQVcRCT5sB6yOvK8A37LNm/kPJiZg==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.58.0.tgz", + "integrity": "sha512-jIhrujyn4UnWF8S+DHSkAkDEO3hLX0cjzxJZPLF80xFyzyUIYgSMRcYQ3+uqEoyDD2beGq7Dj7edi8OnJcS/hg==", "cpu": [ "s390x" ], @@ -793,9 +842,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.57.1.tgz", - "integrity": "sha512-ABca4ceT4N+Tv/GtotnWAeXZUZuM/9AQyCyKYyKnpk4yoA7QIAuBt6Hkgpw8kActYlew2mvckXkvx0FfoInnLg==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.58.0.tgz", + "integrity": "sha512-+410Srdoh78MKSJxTQ+hZ/Mx+ajd6RjjPwBPNd0R3J9FtL6ZA0GqiiyNjCO9In0IzZkCNrpGymSfn+kgyPQocg==", "cpu": [ "x64" ], @@ -807,9 +856,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.57.1.tgz", - "integrity": "sha512-HFps0JeGtuOR2convgRRkHCekD7j+gdAuXM+/i6kGzQtFhlCtQkpwtNzkNj6QhCDp7DRJ7+qC/1Vg2jt5iSOFw==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.58.0.tgz", + "integrity": "sha512-ZjMyby5SICi227y1MTR3VYBpFTdZs823Rs/hpakufleBoufoOIB6jtm9FEoxn/cgO7l6PM2rCEl5Kre5vX0QrQ==", "cpu": [ "x64" ], @@ -821,9 +870,9 @@ ] }, "node_modules/@rollup/rollup-openbsd-x64": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.57.1.tgz", - "integrity": "sha512-H+hXEv9gdVQuDTgnqD+SQffoWoc0Of59AStSzTEj/feWTBAnSfSD3+Dql1ZruJQxmykT/JVY0dE8Ka7z0DH1hw==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.58.0.tgz", + "integrity": "sha512-ds4iwfYkSQ0k1nb8LTcyXw//ToHOnNTJtceySpL3fa7tc/AsE+UpUFphW126A6fKBGJD5dhRvg8zw1rvoGFxmw==", "cpu": [ "x64" ], @@ -835,9 +884,9 @@ ] }, "node_modules/@rollup/rollup-openharmony-arm64": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.57.1.tgz", - "integrity": "sha512-4wYoDpNg6o/oPximyc/NG+mYUejZrCU2q+2w6YZqrAs2UcNUChIZXjtafAiiZSUc7On8v5NyNj34Kzj/Ltk6dQ==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.58.0.tgz", + "integrity": "sha512-fd/zpJniln4ICdPkjWFhZYeY/bpnaN9pGa6ko+5WD38I0tTqk9lXMgXZg09MNdhpARngmxiCg0B0XUamNw/5BQ==", "cpu": [ "arm64" ], @@ -849,9 +898,9 @@ ] }, "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.57.1.tgz", - "integrity": "sha512-O54mtsV/6LW3P8qdTcamQmuC990HDfR71lo44oZMZlXU4tzLrbvTii87Ni9opq60ds0YzuAlEr/GNwuNluZyMQ==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.58.0.tgz", + "integrity": "sha512-YpG8dUOip7DCz3nr/JUfPbIUo+2d/dy++5bFzgi4ugOGBIox+qMbbqt/JoORwvI/C9Kn2tz6+Bieoqd5+B1CjA==", "cpu": [ "arm64" ], @@ -863,9 +912,9 @@ ] }, "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.57.1.tgz", - "integrity": "sha512-P3dLS+IerxCT/7D2q2FYcRdWRl22dNbrbBEtxdWhXrfIMPP9lQhb5h4Du04mdl5Woq05jVCDPCMF7Ub0NAjIew==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.58.0.tgz", + "integrity": "sha512-b9DI8jpFQVh4hIXFr0/+N/TzLdpBIoPzjt0Rt4xJbW3mzguV3mduR9cNgiuFcuL/TeORejJhCWiAXe3E/6PxWA==", "cpu": [ "ia32" ], @@ -877,9 +926,9 @@ ] }, "node_modules/@rollup/rollup-win32-x64-gnu": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.57.1.tgz", - "integrity": "sha512-VMBH2eOOaKGtIJYleXsi2B8CPVADrh+TyNxJ4mWPnKfLB/DBUmzW+5m1xUrcwWoMfSLagIRpjUFeW5CO5hyciQ==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.58.0.tgz", + "integrity": "sha512-CSrVpmoRJFN06LL9xhkitkwUcTZtIotYAF5p6XOR2zW0Zz5mzb3IPpcoPhB02frzMHFNo1reQ9xSF5fFm3hUsQ==", "cpu": [ "x64" ], @@ -891,9 +940,9 @@ ] }, "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.57.1.tgz", - "integrity": "sha512-mxRFDdHIWRxg3UfIIAwCm6NzvxG0jDX/wBN6KsQFTvKFqqg9vTrWUE68qEjHt19A5wwx5X5aUi2zuZT7YR0jrA==", + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.58.0.tgz", + "integrity": "sha512-QFsBgQNTnh5K0t/sBsjJLq24YVqEIVkGpfN2VHsnN90soZyhaiA9UUHufcctVNL4ypJY0wrwad0wslx2KJQ1/w==", "cpu": [ "x64" ], @@ -1162,6 +1211,19 @@ "js-tokens": "^10.0.0" } }, + "node_modules/atob": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz", + "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==", + "dev": true, + "license": "(MIT OR Apache-2.0)", + "bin": { + "atob": "bin/atob.js" + }, + "engines": { + "node": ">= 4.5.0" + } + }, "node_modules/chai": { "version": "6.2.2", "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", @@ -1172,6 +1234,16 @@ "node": ">=18" } }, + "node_modules/decode-uri-component": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.2.tgz", + "integrity": "sha512-FqUYQ+8o158GyGTrMFJms9qh3CqTKvAqgqsTnkLI8sKu0028orqBhxNMFkFen0zGyg6epACD32pjVk58ngIErQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10" + } + }, "node_modules/entities": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", @@ -1489,6 +1561,20 @@ "fsevents": "2.3.2" } }, + "node_modules/playwright-crx": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/playwright-crx/-/playwright-crx-0.15.0.tgz", + "integrity": "sha512-yIz2AchvFOKj+oiGz5AAonMCPK5l6ttt4Xijd7Ggjm6D4OUNdVg+R2dnAnKIoBnvjoOBihlL1lyQVYPswV4Xow==", + "license": "Apache-2.0", + "workspaces": [ + "examples/recorder-crx", + "examples/todomvc-crx", + "tests" + ], + "engines": { + "node": ">=18" + } + }, "node_modules/playwright-repl": { "resolved": "packages/cli", "link": true @@ -1535,50 +1621,45 @@ } }, "node_modules/rollup": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.57.1.tgz", - "integrity": "sha512-oQL6lgK3e2QZeQ7gcgIkS2YZPg5slw37hYufJ3edKlfQSGGm8ICoxswK15ntSzF/a8+h7ekRy7k7oWc3BQ7y8A==", + "version": "2.79.2", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.79.2.tgz", + "integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==", "dev": true, "license": "MIT", - "dependencies": { - "@types/estree": "1.0.8" - }, + "peer": true, "bin": { "rollup": "dist/bin/rollup" }, "engines": { - "node": ">=18.0.0", - "npm": ">=8.0.0" + "node": ">=10.0.0" }, "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.57.1", - "@rollup/rollup-android-arm64": "4.57.1", - "@rollup/rollup-darwin-arm64": "4.57.1", - "@rollup/rollup-darwin-x64": "4.57.1", - "@rollup/rollup-freebsd-arm64": "4.57.1", - "@rollup/rollup-freebsd-x64": "4.57.1", - "@rollup/rollup-linux-arm-gnueabihf": "4.57.1", - "@rollup/rollup-linux-arm-musleabihf": "4.57.1", - "@rollup/rollup-linux-arm64-gnu": "4.57.1", - "@rollup/rollup-linux-arm64-musl": "4.57.1", - "@rollup/rollup-linux-loong64-gnu": "4.57.1", - "@rollup/rollup-linux-loong64-musl": "4.57.1", - "@rollup/rollup-linux-ppc64-gnu": "4.57.1", - "@rollup/rollup-linux-ppc64-musl": "4.57.1", - "@rollup/rollup-linux-riscv64-gnu": "4.57.1", - "@rollup/rollup-linux-riscv64-musl": "4.57.1", - "@rollup/rollup-linux-s390x-gnu": "4.57.1", - "@rollup/rollup-linux-x64-gnu": "4.57.1", - "@rollup/rollup-linux-x64-musl": "4.57.1", - "@rollup/rollup-openbsd-x64": "4.57.1", - "@rollup/rollup-openharmony-arm64": "4.57.1", - "@rollup/rollup-win32-arm64-msvc": "4.57.1", - "@rollup/rollup-win32-ia32-msvc": "4.57.1", - "@rollup/rollup-win32-x64-gnu": "4.57.1", - "@rollup/rollup-win32-x64-msvc": "4.57.1", "fsevents": "~2.3.2" } }, + "node_modules/rollup-plugin-sourcemaps": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/rollup-plugin-sourcemaps/-/rollup-plugin-sourcemaps-0.6.3.tgz", + "integrity": "sha512-paFu+nT1xvuO1tPFYXGe+XnQvg4Hjqv/eIhG8i5EspfYYPBKL57X7iVbfv55aNVASg3dzWvES9dmWsL2KhfByw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^3.0.9", + "source-map-resolve": "^0.6.0" + }, + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "@types/node": ">=10.0.0", + "rollup": ">=0.31.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, "node_modules/semver": { "version": "7.7.4", "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", @@ -1609,6 +1690,18 @@ "node": ">=0.10.0" } }, + "node_modules/source-map-resolve": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.6.0.tgz", + "integrity": "sha512-KXBr9d/fO/bWo97NXsPIAW1bFSBOuCnjbNTBMO7N59hsv5i9yzRDfcYwwt0l04+VqnKC+EwzvJZIP/qkuMgR/w==", + "deprecated": "See https://github.com/lydell/source-map-resolve#deprecated", + "dev": true, + "license": "MIT", + "dependencies": { + "atob": "^2.1.2", + "decode-uri-component": "^0.2.0" + } + }, "node_modules/stackback": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", @@ -1680,6 +1773,20 @@ "node": ">=14.0.0" } }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, "node_modules/undici-types": { "version": "7.16.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", @@ -1777,6 +1884,51 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/vite/node_modules/rollup": { + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.58.0.tgz", + "integrity": "sha512-wbT0mBmWbIvvq8NeEYWWvevvxnOyhKChir47S66WCxw1SXqhw7ssIYejnQEVt7XYQpsj2y8F9PM+Cr3SNEa0gw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.58.0", + "@rollup/rollup-android-arm64": "4.58.0", + "@rollup/rollup-darwin-arm64": "4.58.0", + "@rollup/rollup-darwin-x64": "4.58.0", + "@rollup/rollup-freebsd-arm64": "4.58.0", + "@rollup/rollup-freebsd-x64": "4.58.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.58.0", + "@rollup/rollup-linux-arm-musleabihf": "4.58.0", + "@rollup/rollup-linux-arm64-gnu": "4.58.0", + "@rollup/rollup-linux-arm64-musl": "4.58.0", + "@rollup/rollup-linux-loong64-gnu": "4.58.0", + "@rollup/rollup-linux-loong64-musl": "4.58.0", + "@rollup/rollup-linux-ppc64-gnu": "4.58.0", + "@rollup/rollup-linux-ppc64-musl": "4.58.0", + "@rollup/rollup-linux-riscv64-gnu": "4.58.0", + "@rollup/rollup-linux-riscv64-musl": "4.58.0", + "@rollup/rollup-linux-s390x-gnu": "4.58.0", + "@rollup/rollup-linux-x64-gnu": "4.58.0", + "@rollup/rollup-linux-x64-musl": "4.58.0", + "@rollup/rollup-openbsd-x64": "4.58.0", + "@rollup/rollup-openharmony-arm64": "4.58.0", + "@rollup/rollup-win32-arm64-msvc": "4.58.0", + "@rollup/rollup-win32-ia32-msvc": "4.58.0", + "@rollup/rollup-win32-x64-gnu": "4.58.0", + "@rollup/rollup-win32-x64-msvc": "4.58.0", + "fsevents": "~2.3.2" + } + }, "node_modules/vitest": { "version": "4.0.18", "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.0.18.tgz", @@ -1972,6 +2124,649 @@ "vitest": "^4.0.18" } }, + "packages/crx": { + "name": "@playwright-repl/crx", + "version": "0.1.0", + "dependencies": { + "playwright-crx": "^0.15.0" + }, + "devDependencies": { + "@types/chrome": "^0.0.281", + "rollup-plugin-sourcemaps": "^0.6.3", + "typescript": "^5.7.3", + "vite": "^6.1.0" + } + }, + "packages/crx/node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "packages/crx/node_modules/@types/chrome": { + "version": "0.0.281", + "resolved": "https://registry.npmjs.org/@types/chrome/-/chrome-0.0.281.tgz", + "integrity": "sha512-MH+8FFrJ1POZwKnKRBa+jZcVp+yCFxes6PYKvgFd0qLTzoQe+TdejC3dkA8gSs8UGjFKrKzu4AkZypmswv0NOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/filesystem": "*", + "@types/har-format": "*" + } + }, + "packages/crx/node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "packages/crx/node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "packages/crx/node_modules/rollup": { + "version": "4.58.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.58.0.tgz", + "integrity": "sha512-wbT0mBmWbIvvq8NeEYWWvevvxnOyhKChir47S66WCxw1SXqhw7ssIYejnQEVt7XYQpsj2y8F9PM+Cr3SNEa0gw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.58.0", + "@rollup/rollup-android-arm64": "4.58.0", + "@rollup/rollup-darwin-arm64": "4.58.0", + "@rollup/rollup-darwin-x64": "4.58.0", + "@rollup/rollup-freebsd-arm64": "4.58.0", + "@rollup/rollup-freebsd-x64": "4.58.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.58.0", + "@rollup/rollup-linux-arm-musleabihf": "4.58.0", + "@rollup/rollup-linux-arm64-gnu": "4.58.0", + "@rollup/rollup-linux-arm64-musl": "4.58.0", + "@rollup/rollup-linux-loong64-gnu": "4.58.0", + "@rollup/rollup-linux-loong64-musl": "4.58.0", + "@rollup/rollup-linux-ppc64-gnu": "4.58.0", + "@rollup/rollup-linux-ppc64-musl": "4.58.0", + "@rollup/rollup-linux-riscv64-gnu": "4.58.0", + "@rollup/rollup-linux-riscv64-musl": "4.58.0", + "@rollup/rollup-linux-s390x-gnu": "4.58.0", + "@rollup/rollup-linux-x64-gnu": "4.58.0", + "@rollup/rollup-linux-x64-musl": "4.58.0", + "@rollup/rollup-openbsd-x64": "4.58.0", + "@rollup/rollup-openharmony-arm64": "4.58.0", + "@rollup/rollup-win32-arm64-msvc": "4.58.0", + "@rollup/rollup-win32-ia32-msvc": "4.58.0", + "@rollup/rollup-win32-x64-gnu": "4.58.0", + "@rollup/rollup-win32-x64-msvc": "4.58.0", + "fsevents": "~2.3.2" + } + }, + "packages/crx/node_modules/vite": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz", + "integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, "packages/extension": { "name": "@playwright-repl/extension", "version": "1.0.0", diff --git a/packages/repl-ext/dist/background.js b/packages/repl-ext/dist/background.js new file mode 100644 index 0000000..f389a28 --- /dev/null +++ b/packages/repl-ext/dist/background.js @@ -0,0 +1,143614 @@ +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$1(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$1) { + const base64 = requireBase64Js(); + const ieee7542 = requireIeee754(); + const customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; + exports$1.Buffer = Buffer2; + exports$1.SlowBuffer = SlowBuffer; + exports$1.INSPECT_MAX_BYTES = 50; + const K_MAX_LENGTH = 2147483647; + exports$1.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$1.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$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.bufferFrom = exports$1.bufferAllocUnsafe = exports$1.Buffer = void 0; + const buffer_1 = requireBuffer$2(); + Object.defineProperty(exports$1, "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$1.bufferAllocUnsafe = bufferAllocUnsafe; + const bufferFrom = buffer_1.Buffer.from || bufferV0P12Ponyfill; + exports$1.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$1) { + 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$1.isArgumentsObject = isArgumentsObject; + exports$1.isGeneratorFunction = isGeneratorFunction2; + exports$1.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$1.isPromise = isPromise; + function isArrayBufferView(value) { + if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { + return ArrayBuffer.isView(value); + } + return isTypedArray2(value) || isDataView(value); + } + exports$1.isArrayBufferView = isArrayBufferView; + function isUint8Array(value) { + return whichTypedArray2(value) === "Uint8Array"; + } + exports$1.isUint8Array = isUint8Array; + function isUint8ClampedArray(value) { + return whichTypedArray2(value) === "Uint8ClampedArray"; + } + exports$1.isUint8ClampedArray = isUint8ClampedArray; + function isUint16Array(value) { + return whichTypedArray2(value) === "Uint16Array"; + } + exports$1.isUint16Array = isUint16Array; + function isUint32Array(value) { + return whichTypedArray2(value) === "Uint32Array"; + } + exports$1.isUint32Array = isUint32Array; + function isInt8Array(value) { + return whichTypedArray2(value) === "Int8Array"; + } + exports$1.isInt8Array = isInt8Array; + function isInt16Array(value) { + return whichTypedArray2(value) === "Int16Array"; + } + exports$1.isInt16Array = isInt16Array; + function isInt32Array(value) { + return whichTypedArray2(value) === "Int32Array"; + } + exports$1.isInt32Array = isInt32Array; + function isFloat32Array(value) { + return whichTypedArray2(value) === "Float32Array"; + } + exports$1.isFloat32Array = isFloat32Array; + function isFloat64Array(value) { + return whichTypedArray2(value) === "Float64Array"; + } + exports$1.isFloat64Array = isFloat64Array; + function isBigInt64Array(value) { + return whichTypedArray2(value) === "BigInt64Array"; + } + exports$1.isBigInt64Array = isBigInt64Array; + function isBigUint64Array(value) { + return whichTypedArray2(value) === "BigUint64Array"; + } + exports$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.isSharedArrayBuffer = isSharedArrayBuffer; + function isAsyncFunction(value) { + return ObjectToString(value) === "[object AsyncFunction]"; + } + exports$1.isAsyncFunction = isAsyncFunction; + function isMapIterator(value) { + return ObjectToString(value) === "[object Map Iterator]"; + } + exports$1.isMapIterator = isMapIterator; + function isSetIterator(value) { + return ObjectToString(value) === "[object Set Iterator]"; + } + exports$1.isSetIterator = isSetIterator; + function isGeneratorObject(value) { + return ObjectToString(value) === "[object Generator]"; + } + exports$1.isGeneratorObject = isGeneratorObject; + function isWebAssemblyCompiledModule(value) { + return ObjectToString(value) === "[object WebAssembly.Module]"; + } + exports$1.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; + function isNumberObject(value) { + return checkBoxedPrimitive(value, numberValue); + } + exports$1.isNumberObject = isNumberObject; + function isStringObject(value) { + return checkBoxedPrimitive(value, stringValue); + } + exports$1.isStringObject = isStringObject; + function isBooleanObject(value) { + return checkBoxedPrimitive(value, booleanValue); + } + exports$1.isBooleanObject = isBooleanObject; + function isBigIntObject(value) { + return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); + } + exports$1.isBigIntObject = isBigIntObject; + function isSymbolObject(value) { + return SymbolSupported && checkBoxedPrimitive(value, symbolValue); + } + exports$1.isSymbolObject = isSymbolObject; + function isBoxedPrimitive(value) { + return isNumberObject(value) || isStringObject(value) || isBooleanObject(value) || isBigIntObject(value) || isSymbolObject(value); + } + exports$1.isBoxedPrimitive = isBoxedPrimitive; + function isAnyArrayBuffer(value) { + return typeof Uint8Array !== "undefined" && (isArrayBuffer(value) || isSharedArrayBuffer(value)); + } + exports$1.isAnyArrayBuffer = isAnyArrayBuffer; + ["isProxy", "isExternal", "isModuleNamespaceObject"].forEach(function(method) { + Object.defineProperty(exports$1, 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$1) { + 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$1.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$1.deprecate = function(fn, msg) { + if (typeof process !== "undefined" && process.noDeprecation === true) { + return fn; + } + if (typeof process === "undefined") { + return function() { + return exports$1.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$1.debuglog = function(set2) { + set2 = set2.toUpperCase(); + if (!debugs[set2]) { + if (debugEnvRegex.test(set2)) { + var pid = process.pid; + debugs[set2] = function() { + var msg = exports$1.format.apply(exports$1, 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$1._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$1.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$1.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$1.types = requireTypes(); + function isArray2(ar) { + return Array.isArray(ar); + } + exports$1.isArray = isArray2; + function isBoolean(arg) { + return typeof arg === "boolean"; + } + exports$1.isBoolean = isBoolean; + function isNull(arg) { + return arg === null; + } + exports$1.isNull = isNull; + function isNullOrUndefined(arg) { + return arg == null; + } + exports$1.isNullOrUndefined = isNullOrUndefined; + function isNumber(arg) { + return typeof arg === "number"; + } + exports$1.isNumber = isNumber; + function isString2(arg) { + return typeof arg === "string"; + } + exports$1.isString = isString2; + function isSymbol(arg) { + return typeof arg === "symbol"; + } + exports$1.isSymbol = isSymbol; + function isUndefined(arg) { + return arg === void 0; + } + exports$1.isUndefined = isUndefined; + function isRegExp2(re2) { + return isObject2(re2) && objectToString(re2) === "[object RegExp]"; + } + exports$1.isRegExp = isRegExp2; + exports$1.types.isRegExp = isRegExp2; + function isObject2(arg) { + return typeof arg === "object" && arg !== null; + } + exports$1.isObject = isObject2; + function isDate2(d) { + return isObject2(d) && objectToString(d) === "[object Date]"; + } + exports$1.isDate = isDate2; + exports$1.types.isDate = isDate2; + function isError2(e) { + return isObject2(e) && (objectToString(e) === "[object Error]" || e instanceof Error); + } + exports$1.isError = isError2; + exports$1.types.isNativeError = isError2; + function isFunction(arg) { + return typeof arg === "function"; + } + exports$1.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$1.isPrimitive = isPrimitive; + exports$1.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$1.log = function() { + console.log("%s - %s", timestamp2(), exports$1.format.apply(exports$1, arguments)); + }; + exports$1.inherits = requireInherits_browser$1(); + exports$1._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$1.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$1.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$1.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$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.E = exports$1.AssertionError = exports$1.message = exports$1.RangeError = exports$1.TypeError = exports$1.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$1.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$1.Error.captureStackTrace(this, options2.stackStartFunction); + } + } + exports$1.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$1.message = message; + function E(sym, val) { + messages2[sym] = typeof val === "function" ? val : String(val); + } + exports$1.E = E; + exports$1.Error = makeNodeError(g.Error); + exports$1.TypeError = makeNodeError(g.TypeError); + exports$1.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$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.strToEncoding = exports$1.assertEncoding = exports$1.ENCODING_UTF8 = void 0; + const buffer_1 = requireBuffer$1(); + const errors2 = requireErrors$1(); + exports$1.ENCODING_UTF8 = "utf8"; + function assertEncoding(encoding2) { + if (encoding2 && !buffer_1.Buffer.isEncoding(encoding2)) + throw new errors2.TypeError("ERR_INVALID_OPT_VALUE_ENCODING", encoding2); + } + exports$1.assertEncoding = assertEncoding; + function strToEncoding(str, encoding2) { + if (!encoding2 || encoding2 === exports$1.ENCODING_UTF8) + return str; + if (encoding2 === "buffer") + return new buffer_1.Buffer(str); + return new buffer_1.Buffer(str).toString(encoding2); + } + exports$1.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$1) { + var formatRegExp = /%[sdj%]/g; + exports$1.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$1.deprecate = function(fn, msg) { + if (isUndefined(commonjsGlobal.process)) { + return function() { + return exports$1.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$1.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$1.format.apply(exports$1, 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$1._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$1.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$1.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$1.isArray = isArray2; + function isBoolean(arg) { + return typeof arg === "boolean"; + } + exports$1.isBoolean = isBoolean; + function isNull(arg) { + return arg === null; + } + exports$1.isNull = isNull; + function isNullOrUndefined(arg) { + return arg == null; + } + exports$1.isNullOrUndefined = isNullOrUndefined; + function isNumber(arg) { + return typeof arg === "number"; + } + exports$1.isNumber = isNumber; + function isString2(arg) { + return typeof arg === "string"; + } + exports$1.isString = isString2; + function isSymbol(arg) { + return typeof arg === "symbol"; + } + exports$1.isSymbol = isSymbol; + function isUndefined(arg) { + return arg === void 0; + } + exports$1.isUndefined = isUndefined; + function isRegExp2(re2) { + return isObject2(re2) && objectToString(re2) === "[object RegExp]"; + } + exports$1.isRegExp = isRegExp2; + function isObject2(arg) { + return typeof arg === "object" && arg !== null; + } + exports$1.isObject = isObject2; + function isDate2(d) { + return isObject2(d) && objectToString(d) === "[object Date]"; + } + exports$1.isDate = isDate2; + function isError2(e) { + return isObject2(e) && (objectToString(e) === "[object Error]" || e instanceof Error); + } + exports$1.isError = isError2; + function isFunction(arg) { + return typeof arg === "function"; + } + exports$1.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$1.isPrimitive = isPrimitive; + exports$1.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$1.log = function() { + console.log("%s - %s", timestamp2(), exports$1.format.apply(exports$1, arguments)); + }; + exports$1.inherits = requireInherits_browser(); + exports$1._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$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.File = exports$1.Link = exports$1.Node = exports$1.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$1.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$1.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$1.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$1.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$1.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$1) { + 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$1); + exports$1.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$1) { + (function(root) { + var freeExports = exports$1 && !exports$1.nodeType && exports$1; + 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$1({ + __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$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.unixify = exports$1.bufferToEncoding = exports$1.getWriteSyncArgs = exports$1.getWriteArgs = exports$1.bufToUint8 = exports$1.dataToBuffer = exports$1.validateFd = exports$1.isFd = exports$1.flagsToNumber = exports$1.genRndStr6 = exports$1.createError = exports$1.pathToFilename = exports$1.nullCheck = exports$1.modeToNumber = exports$1.validateCallback = exports$1.promisify = exports$1.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$1.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$1.promisify = promisify2; + function validateCallback(callback) { + if (typeof callback !== "function") + throw TypeError(constants_1.ERRSTR.CB); + return callback; + } + exports$1.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$1.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$1.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$1.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$1.createError = createError; + function genRndStr6() { + const str = (Math.random() + 1).toString(36).substring(2, 8); + if (str.length === 6) + return str; + else + return genRndStr6(); + } + exports$1.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$1.flagsToNumber = flagsToNumber; + function isFd(path2) { + return path2 >>> 0 === path2; + } + exports$1.isFd = isFd; + function validateFd(fd) { + if (!isFd(fd)) + throw TypeError(constants_1.ERRSTR.FD); + } + exports$1.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$1.dataToBuffer = dataToBuffer; + const bufToUint8 = (buf) => new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + exports$1.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$1.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$1.getWriteSyncArgs = getWriteSyncArgs; + function bufferToEncoding(buffer2, encoding2) { + if (!encoding2 || encoding2 === "buffer") + return buffer2; + else + return buffer2.toString(encoding2); + } + exports$1.bufferToEncoding = bufferToEncoding; + const isSeparator = (str, i) => { + let char = str[i]; + return i > 0 && (char === "/" || exports$1.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$1.isWin) { + filepath = normalizePath(filepath, stripTrailing); + return filepath.replace(/^([a-zA-Z]+:|\.\/)/, ""); + } + return filepath; + }; + exports$1.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$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.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$1.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$1.toTreeSync = toTreeSync; + })(print); + return print; +} +var options$1 = {}; +var hasRequiredOptions; +function requireOptions() { + if (hasRequiredOptions) return options$1; + hasRequiredOptions = 1; + (function(exports$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.getWriteFileOptions = exports$1.writeFileDefaults = exports$1.getRealpathOptsAndCb = exports$1.getRealpathOptions = exports$1.getStatOptsAndCb = exports$1.getStatOptions = exports$1.getAppendFileOptsAndCb = exports$1.getAppendFileOpts = exports$1.getReaddirOptsAndCb = exports$1.getReaddirOptions = exports$1.getReadFileOptions = exports$1.getRmOptsAndCb = exports$1.getRmdirOptions = exports$1.getDefaultOptsAndCb = exports$1.getDefaultOpts = exports$1.optsDefaults = exports$1.optsAndCbGenerator = exports$1.optsGenerator = exports$1.getOptions = exports$1.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$1.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$1.getOptions = getOptions2; + function optsGenerator(defaults) { + return (options2) => getOptions2(defaults, options2); + } + exports$1.optsGenerator = optsGenerator; + function optsAndCbGenerator(getOpts) { + return (options2, callback) => typeof options2 === "function" ? [getOpts(), options2] : [getOpts(options2), (0, util_1.validateCallback)(callback)]; + } + exports$1.optsAndCbGenerator = optsAndCbGenerator; + exports$1.optsDefaults = { + encoding: "utf8" + }; + exports$1.getDefaultOpts = optsGenerator(exports$1.optsDefaults); + exports$1.getDefaultOptsAndCb = optsAndCbGenerator(exports$1.getDefaultOpts); + const rmdirDefaults = { + recursive: false + }; + const getRmdirOptions = (options2) => { + return Object.assign({}, rmdirDefaults, options2); + }; + exports$1.getRmdirOptions = getRmdirOptions; + const getRmOpts = optsGenerator(exports$1.optsDefaults); + exports$1.getRmOptsAndCb = optsAndCbGenerator(getRmOpts); + const readFileOptsDefaults = { + flag: "r" + }; + exports$1.getReadFileOptions = optsGenerator(readFileOptsDefaults); + const readdirDefaults = { + encoding: "utf8", + recursive: false, + withFileTypes: false + }; + exports$1.getReaddirOptions = optsGenerator(readdirDefaults); + exports$1.getReaddirOptsAndCb = optsAndCbGenerator(exports$1.getReaddirOptions); + const appendFileDefaults = { + encoding: "utf8", + mode: 438, + flag: constants_1.FLAGS[constants_1.FLAGS.a] + }; + exports$1.getAppendFileOpts = optsGenerator(appendFileDefaults); + exports$1.getAppendFileOptsAndCb = optsAndCbGenerator(exports$1.getAppendFileOpts); + const statDefaults = { + bigint: false + }; + const getStatOptions = (options2 = {}) => Object.assign({}, statDefaults, options2); + exports$1.getStatOptions = getStatOptions; + const getStatOptsAndCb = (options2, callback) => typeof options2 === "function" ? [(0, exports$1.getStatOptions)(), options2] : [(0, exports$1.getStatOptions)(options2), (0, util_1.validateCallback)(callback)]; + exports$1.getStatOptsAndCb = getStatOptsAndCb; + const realpathDefaults = exports$1.optsDefaults; + exports$1.getRealpathOptions = optsGenerator(realpathDefaults); + exports$1.getRealpathOptsAndCb = optsAndCbGenerator(exports$1.getRealpathOptions); + exports$1.writeFileDefaults = { + encoding: "utf8", + mode: 438, + flag: constants_1.FLAGS[constants_1.FLAGS.w] + }; + exports$1.getWriteFileOptions = optsGenerator(exports$1.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$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.memfs = exports$1.fs = exports$1.createFsFromVolume = exports$1.vol = exports$1.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$1.Volume = volume_1.Volume; + exports$1.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$1.createFsFromVolume = createFsFromVolume; + exports$1.fs = createFsFromVolume(exports$1.vol); + const memfs = (json = {}, cwd = "/") => { + const vol = exports$1.Volume.fromNestedJSON(json, cwd); + const fs2 = createFsFromVolume(vol); + return { fs: fs2, vol }; + }; + exports$1.memfs = memfs; + module.exports = Object.assign(Object.assign({}, module.exports), exports$1.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$1) { + var RetryOperation = requireRetry_operation(); + exports$1.operation = function(options2) { + var timeouts = exports$1.timeouts(options2); + return new RetryOperation(timeouts, { + forever: options2 && options2.forever, + unref: options2 && options2.unref, + maxRetryTime: options2 && options2.maxRetryTime + }); + }; + exports$1.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$1.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$1.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$1.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$1) { + exports$1.formatArgs = formatArgs; + exports$1.save = save; + exports$1.load = load; + exports$1.useColors = useColors; + exports$1.storage = localstorage(); + exports$1.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$1.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$1.log = console.debug || console.log || (() => { + }); + function save(namespaces) { + try { + if (namespaces) { + exports$1.storage.setItem("debug", namespaces); + } else { + exports$1.storage.removeItem("debug"); + } + } catch (error2) { + } + } + function load() { + let r; + try { + r = exports$1.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$1); + 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$1) { + exports$1 = module.exports = require_stream_readable$2(); + exports$1.Stream = exports$1; + exports$1.Readable = exports$1; + exports$1.Writable = require_stream_writable$2(); + exports$1.Duplex = require_stream_duplex$2(); + exports$1.Transform = require_stream_transform$2(); + exports$1.PassThrough = require_stream_passthrough$2(); + exports$1.finished = requireEndOfStream$3(); + exports$1.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$1 = sha_js.exports = function SHA(algorithm) { + algorithm = algorithm.toLowerCase(); + var Algorithm = exports$1[algorithm]; + if (!Algorithm) throw new Error(algorithm + " is not supported (we accept pull requests)"); + return new Algorithm(); + }; + exports$1.sha = requireSha$1(); + exports$1.sha1 = requireSha1(); + exports$1.sha224 = requireSha224(); + exports$1.sha256 = requireSha256(); + exports$1.sha384 = requireSha384(); + exports$1.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$1) { + exports$1["des-ecb"] = { + key: 8, + iv: 0 + }; + exports$1["des-cbc"] = exports$1.des = { + key: 8, + iv: 8 + }; + exports$1["des-ede3-cbc"] = exports$1.des3 = { + key: 24, + iv: 8 + }; + exports$1["des-ede3"] = { + key: 24, + iv: 0 + }; + exports$1["des-ede-cbc"] = { + key: 16, + iv: 8 + }; + exports$1["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$1) { + 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$1.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$1) { + 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$1.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$1) { + exports$1 = module.exports = require_stream_readable$1(); + exports$1.Stream = exports$1; + exports$1.Readable = exports$1; + exports$1.Writable = require_stream_writable$1(); + exports$1.Duplex = require_stream_duplex$1(); + exports$1.Transform = require_stream_transform$1(); + exports$1.PassThrough = require_stream_passthrough$1(); + exports$1.finished = requireEndOfStream$2(); + exports$1.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$1) { + 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$1.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$1) { + 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$1.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$1) { + var utils2 = exports$1; + 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$1) { + var utils2 = exports$1; + 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$1) { + var curve2 = exports$1; + 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$1) { + var hash2 = exports$1; + 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$1) { + var curves2 = exports$1; + 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$1) { + var elliptic2 = exports$1; + 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$1) { + 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$1.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$1) { + 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$1.tagClass = { + 0: "universal", + 1: "application", + 2: "context", + 3: "private" + }; + exports$1.tagClassByName = reverse(exports$1.tagClass); + exports$1.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$1.tagByName = reverse(exports$1.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$1) { + const encoders2 = exports$1; + 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$1) { + const decoders2 = exports$1; + decoders2.der = requireDer(); + decoders2.pem = requirePem(); + })(decoders); + return decoders; +} +var hasRequiredApi; +function requireApi() { + if (hasRequiredApi) return api; + hasRequiredApi = 1; + (function(exports$1) { + const encoders2 = requireEncoders(); + const decoders2 = requireDecoders(); + const inherits = requireInherits_browser$1(); + const api2 = exports$1; + 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$1) { + const base2 = exports$1; + 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$1) { + const constants2 = exports$1; + 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$1) { + const asn12 = exports$1; + 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$1) { + 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$1.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$1) { + 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$1.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$1) { + exports$1.publicEncrypt = requirePublicEncrypt(); + exports$1.privateDecrypt = requirePrivateDecrypt(); + exports$1.privateEncrypt = function privateEncrypt(key2, buf) { + return exports$1.publicEncrypt(key2, buf, true); + }; + exports$1.publicDecrypt = function publicDecrypt(key2, buf) { + return exports$1.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$1) { + var TYPED_OK = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Int32Array !== "undefined"; + function _has(obj, key2) { + return Object.prototype.hasOwnProperty.call(obj, key2); + } + exports$1.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$1.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$1.setTyped = function(on) { + if (on) { + exports$1.Buf8 = Uint8Array; + exports$1.Buf16 = Uint16Array; + exports$1.Buf32 = Int32Array; + exports$1.assign(exports$1, fnTyped); + } else { + exports$1.Buf8 = Array; + exports$1.Buf16 = Array; + exports$1.Buf32 = Array; + exports$1.assign(exports$1, fnUntyped); + } + }; + exports$1.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$1) { + var assert2 = requireAssert(); + var Zstream = requireZstream(); + var zlib_deflate = requireDeflate(); + var zlib_inflate = requireInflate(); + var constants2 = requireConstants$4(); + for (var key2 in constants2) { + exports$1[key2] = constants2[key2]; + } + exports$1.NONE = 0; + exports$1.DEFLATE = 1; + exports$1.INFLATE = 2; + exports$1.GZIP = 3; + exports$1.GUNZIP = 4; + exports$1.DEFLATERAW = 5; + exports$1.INFLATERAW = 6; + exports$1.UNZIP = 7; + var GZIP_HEADER_ID1 = 31; + var GZIP_HEADER_ID2 = 139; + function Zlib(mode) { + if (typeof mode !== "number" || mode < exports$1.DEFLATE || mode > exports$1.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$1.UNZIP); + if (this.mode === exports$1.DEFLATE || this.mode === exports$1.GZIP || this.mode === exports$1.DEFLATERAW) { + zlib_deflate.deflateEnd(this.strm); + } else if (this.mode === exports$1.INFLATE || this.mode === exports$1.GUNZIP || this.mode === exports$1.INFLATERAW || this.mode === exports$1.UNZIP) { + zlib_inflate.inflateEnd(this.strm); + } + this.mode = exports$1.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$1.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$1.Z_NO_FLUSH && flush !== exports$1.Z_PARTIAL_FLUSH && flush !== exports$1.Z_SYNC_FLUSH && flush !== exports$1.Z_FULL_FLUSH && flush !== exports$1.Z_FINISH && flush !== exports$1.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$1.DEFLATE: + case exports$1.GZIP: + case exports$1.DEFLATERAW: + this.err = zlib_deflate.deflate(this.strm, this.flush); + break; + case exports$1.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$1.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$1.GUNZIP; + } else { + this.mode = exports$1.INFLATE; + } + break; + default: + throw new Error("invalid number of gzip magic number bytes read"); + } + // fallthrough + case exports$1.INFLATE: + case exports$1.GUNZIP: + case exports$1.INFLATERAW: + this.err = zlib_inflate.inflate( + this.strm, + this.flush + // If data was encoded with dictionary + ); + if (this.err === exports$1.Z_NEED_DICT && this.dictionary) { + this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary); + if (this.err === exports$1.Z_OK) { + this.err = zlib_inflate.inflate(this.strm, this.flush); + } else if (this.err === exports$1.Z_DATA_ERROR) { + this.err = exports$1.Z_NEED_DICT; + } + } + while (this.strm.avail_in > 0 && this.mode === exports$1.GUNZIP && this.err === exports$1.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$1.Z_OK: + case exports$1.Z_BUF_ERROR: + if (this.strm.avail_out !== 0 && this.flush === exports$1.Z_FINISH) { + this._error("unexpected end of file"); + return false; + } + break; + case exports$1.Z_STREAM_END: + break; + case exports$1.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$1.Z_FILTERED || strategy === exports$1.Z_HUFFMAN_ONLY || strategy === exports$1.Z_RLE || strategy === exports$1.Z_FIXED || strategy === exports$1.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$1.Z_NO_FLUSH; + this.err = exports$1.Z_OK; + if (this.mode === exports$1.GZIP || this.mode === exports$1.GUNZIP) { + this.windowBits += 16; + } + if (this.mode === exports$1.UNZIP) { + this.windowBits += 32; + } + if (this.mode === exports$1.DEFLATERAW || this.mode === exports$1.INFLATERAW) { + this.windowBits = -1 * this.windowBits; + } + this.strm = new Zstream(); + switch (this.mode) { + case exports$1.DEFLATE: + case exports$1.GZIP: + case exports$1.DEFLATERAW: + this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports$1.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy); + break; + case exports$1.INFLATE: + case exports$1.GUNZIP: + case exports$1.INFLATERAW: + case exports$1.UNZIP: + this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits); + break; + default: + throw new Error("Unknown mode " + this.mode); + } + if (this.err !== exports$1.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$1.Z_OK; + switch (this.mode) { + case exports$1.DEFLATE: + case exports$1.DEFLATERAW: + this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary); + break; + } + if (this.err !== exports$1.Z_OK) { + this._error("Failed to set dictionary"); + } + }; + Zlib.prototype._reset = function() { + this.err = exports$1.Z_OK; + switch (this.mode) { + case exports$1.DEFLATE: + case exports$1.DEFLATERAW: + case exports$1.GZIP: + this.err = zlib_deflate.deflateReset(this.strm); + break; + case exports$1.INFLATE: + case exports$1.INFLATERAW: + case exports$1.GUNZIP: + this.err = zlib_inflate.inflateReset(this.strm); + break; + } + if (this.err !== exports$1.Z_OK) { + this._error("Failed to reset stream"); + } + }; + exports$1.Zlib = Zlib; + })(binding); + return binding; +} +var hasRequiredLib; +function requireLib() { + if (hasRequiredLib) return lib; + hasRequiredLib = 1; + (function(exports$1) { + 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$1, 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$1, "codes", { + enumerable: true, + value: Object.freeze(codes), + writable: false + }); + exports$1.Deflate = Deflate; + exports$1.Inflate = Inflate; + exports$1.Gzip = Gzip; + exports$1.Gunzip = Gunzip; + exports$1.DeflateRaw = DeflateRaw; + exports$1.InflateRaw = InflateRaw; + exports$1.Unzip = Unzip; + exports$1.createDeflate = function(o) { + return new Deflate(o); + }; + exports$1.createInflate = function(o) { + return new Inflate(o); + }; + exports$1.createDeflateRaw = function(o) { + return new DeflateRaw(o); + }; + exports$1.createInflateRaw = function(o) { + return new InflateRaw(o); + }; + exports$1.createGzip = function(o) { + return new Gzip(o); + }; + exports$1.createGunzip = function(o) { + return new Gunzip(o); + }; + exports$1.createUnzip = function(o) { + return new Unzip(o); + }; + exports$1.deflate = function(buffer2, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + return zlibBuffer(new Deflate(opts), buffer2, callback); + }; + exports$1.deflateSync = function(buffer2, opts) { + return zlibBufferSync(new Deflate(opts), buffer2); + }; + exports$1.gzip = function(buffer2, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + return zlibBuffer(new Gzip(opts), buffer2, callback); + }; + exports$1.gzipSync = function(buffer2, opts) { + return zlibBufferSync(new Gzip(opts), buffer2); + }; + exports$1.deflateRaw = function(buffer2, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + return zlibBuffer(new DeflateRaw(opts), buffer2, callback); + }; + exports$1.deflateRawSync = function(buffer2, opts) { + return zlibBufferSync(new DeflateRaw(opts), buffer2); + }; + exports$1.unzip = function(buffer2, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + return zlibBuffer(new Unzip(opts), buffer2, callback); + }; + exports$1.unzipSync = function(buffer2, opts) { + return zlibBufferSync(new Unzip(opts), buffer2); + }; + exports$1.inflate = function(buffer2, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + return zlibBuffer(new Inflate(opts), buffer2, callback); + }; + exports$1.inflateSync = function(buffer2, opts) { + return zlibBufferSync(new Inflate(opts), buffer2); + }; + exports$1.gunzip = function(buffer2, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + return zlibBuffer(new Gunzip(opts), buffer2, callback); + }; + exports$1.gunzipSync = function(buffer2, opts) { + return zlibBufferSync(new Gunzip(opts), buffer2); + }; + exports$1.inflateRaw = function(buffer2, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + return zlibBuffer(new InflateRaw(opts), buffer2, callback); + }; + exports$1.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$1.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$1.Z_MIN_CHUNK || opts.chunkSize > exports$1.Z_MAX_CHUNK) { + throw new Error("Invalid chunk size: " + opts.chunkSize); + } + } + if (opts.windowBits) { + if (opts.windowBits < exports$1.Z_MIN_WINDOWBITS || opts.windowBits > exports$1.Z_MAX_WINDOWBITS) { + throw new Error("Invalid windowBits: " + opts.windowBits); + } + } + if (opts.level) { + if (opts.level < exports$1.Z_MIN_LEVEL || opts.level > exports$1.Z_MAX_LEVEL) { + throw new Error("Invalid compression level: " + opts.level); + } + } + if (opts.memLevel) { + if (opts.memLevel < exports$1.Z_MIN_MEMLEVEL || opts.memLevel > exports$1.Z_MAX_MEMLEVEL) { + throw new Error("Invalid memLevel: " + opts.memLevel); + } + } + if (opts.strategy) { + if (opts.strategy != exports$1.Z_FILTERED && opts.strategy != exports$1.Z_HUFFMAN_ONLY && opts.strategy != exports$1.Z_RLE && opts.strategy != exports$1.Z_FIXED && opts.strategy != exports$1.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$1.codes[errno]; + self2.emit("error", error2); + }; + var level = exports$1.Z_DEFAULT_COMPRESSION; + if (typeof opts.level === "number") level = opts.level; + var strategy = exports$1.Z_DEFAULT_STRATEGY; + if (typeof opts.strategy === "number") strategy = opts.strategy; + this._handle.init(opts.windowBits || exports$1.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports$1.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$1.Z_MIN_LEVEL || level > exports$1.Z_MAX_LEVEL) { + throw new RangeError("Invalid compression level: " + level); + } + if (strategy != exports$1.Z_FILTERED && strategy != exports$1.Z_HUFFMAN_ONLY && strategy != exports$1.Z_RLE && strategy != exports$1.Z_FIXED && strategy != exports$1.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$1) { + 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$1 = inflateSync; + exports$1.Inflate = Inflate; + exports$1.createInflate = createInflate; + exports$1.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$1) { + const { Argument } = requireArgument(); + const { Command } = requireCommand(); + const { CommanderError, InvalidArgumentError } = requireError(); + const { Help } = requireHelp(); + const { Option } = requireOption(); + exports$1 = module.exports = new Command(); + exports$1.program = exports$1; + exports$1.Argument = Argument; + exports$1.Command = Command; + exports$1.CommanderError = CommanderError; + exports$1.Help = Help; + exports$1.InvalidArgumentError = InvalidArgumentError; + exports$1.InvalidOptionArgumentError = InvalidArgumentError; + exports$1.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$1) { + 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$1) { + (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$1) { + !(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$1["sprintf"] = sprintf2; + exports$1["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$1) { + 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$1, "__esModule", { value: true }); + exports$1.v6 = exports$1.AddressError = exports$1.Address6 = exports$1.Address4 = void 0; + const ipv4_1 = requireIpv4(); + Object.defineProperty(exports$1, "Address4", { enumerable: true, get: function() { + return ipv4_1.Address4; + } }); + const ipv6_1 = requireIpv6(); + Object.defineProperty(exports$1, "Address6", { enumerable: true, get: function() { + return ipv6_1.Address6; + } }); + const address_error_1 = requireAddressError(); + Object.defineProperty(exports$1, "AddressError", { enumerable: true, get: function() { + return address_error_1.AddressError; + } }); + const helpers2 = __importStar(requireHelpers$1()); + exports$1.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$1) { + 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$1, "__esModule", { value: true }); + exports$1.SocksClientError = exports$1.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$1, "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$1.SocksClient = SocksClient; + })(socksclient); + return socksclient; +} +var hasRequiredBuild; +function requireBuild() { + if (hasRequiredBuild) return build; + hasRequiredBuild = 1; + (function(exports$1) { + 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$1, "__esModule", { value: true }); + __exportStar(requireSocksclient(), exports$1); + })(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 = 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.log = (data2) => { + stream2.write(data2.replace(ansiRegex, "")); + stream2.write("\n"); + }; + } + } + log(name, message) { + let cachedDebugger = this._debuggers.get(name); + if (!cachedDebugger) { + cachedDebugger = debug(`pw:${name}`); + this._debuggers.set(name, cachedDebugger); + cachedDebugger.color = debugLoggerColorMap[name] || 0; + } + cachedDebugger(message); + } + isEnabled(name) { + return debug.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$1({ + __proto__: null, + default: index$2 +}, [yazlExports]); +var yauzlExports = requireYauzl(); +const index = /* @__PURE__ */ getDefaultExportFromCjs(yauzlExports); +const index$1 = /* @__PURE__ */ _mergeNamespaces$1({ + __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 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$1) { + exports$1.fetch = isFunction(commonjsGlobal.fetch) && isFunction(commonjsGlobal.ReadableStream); + exports$1.writableStream = isFunction(commonjsGlobal.WritableStream); + exports$1.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$1.arraybuffer = exports$1.fetch || checkTypeSupport("arraybuffer"); + exports$1.msstream = !exports$1.fetch && checkTypeSupport("ms-stream"); + exports$1.mozchunkedarraybuffer = !exports$1.fetch && checkTypeSupport("moz-chunked-arraybuffer"); + exports$1.overrideMimeType = exports$1.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$1) { + exports$1 = module.exports = require_stream_readable(); + exports$1.Stream = exports$1; + exports$1.Readable = exports$1; + exports$1.Writable = require_stream_writable(); + exports$1.Duplex = require_stream_duplex(); + exports$1.Transform = require_stream_transform(); + exports$1.PassThrough = require_stream_passthrough(); + exports$1.finished = requireEndOfStream(); + exports$1.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$1) { + var ClientRequest = requireRequest(); + var response2 = requireResponse(); + var extend2 = requireImmutable(); + var statusCodes = requireBrowser$1(); + var url2 = require$$1$5; + var http2 = exports$1; + 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("pw:android")("Stopping the old driver"); + await this.shell(`am force-stop com.microsoft.playwright.androiddriver`); + if (!this._options.omitDriverInstall) { + debug("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("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("pw:android")("Skipping the driver installation"); + } + debug("pw:android")("Starting the new driver"); + this.shell("am instrument -w com.microsoft.playwright.androiddriver.test/androidx.test.runner.AndroidJUnitRunner").catch((e) => debug("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("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("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("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("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("pw:android")(`exception while removing ${artifactsDir}: ${errors2[i]}`); + }; + gracefullyCloseSet.add(cleanupArtifactsDir); + socket.on("close", async () => { + gracefullyCloseSet.delete(cleanupArtifactsDir); + cleanupArtifactsDir().catch((e) => debug("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("pw:android")("Opening install socket"); + const installSocket = await this._backend.open(`shell:cmd package install ${args.join(" ")} ${content.length}`); + debug("pw:android")("Writing driver bytes: " + content.length); + await installSocket.write(content); + const success = await new Promise((f) => installSocket.on("data", f)); + debug("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("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("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("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("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("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 crxApp2 = from((await this._channel.start(options2 ?? {})).crxApplication); + crxApp2.on("close", onClose); + return crxApp2; + } + 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, "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) + return; + (_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; + } +} +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$1 = /* @__PURE__ */ Object.create(null); + if (!node2.body) { + node2.body = []; + } + while (this.type !== types$1.eof) { + var stmt = this.parseStatement(null, true, exports$1); + 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$1) { + 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$1); + // 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$1) { + if (this.options.ecmaVersion >= 11) { + if (this.eatContextual("as")) { + node2.exported = this.parseModuleExportName(); + this.checkExport(exports$1, 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$1) { + this.next(); + if (this.eat(types$1.star)) { + return this.parseExportAllDeclaration(node2, exports$1); + } + if (this.eat(types$1._default)) { + this.checkExport(exports$1, "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$1, node2.declaration.declarations); + } else { + this.checkExport(exports$1, node2.declaration.id, node2.declaration.id.start); + } + node2.specifiers = []; + node2.source = null; + } else { + node2.declaration = null; + node2.specifiers = this.parseExportSpecifiers(exports$1); + 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$1, name, pos) { + if (!exports$1) { + return; + } + if (typeof name !== "string") { + name = name.type === "Identifier" ? name.name : name.value; + } + if (hasOwn(exports$1, name)) { + this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); + } + exports$1[name] = true; +}; +pp$8.checkPatternExport = function(exports$1, pat) { + var type2 = pat.type; + if (type2 === "Identifier") { + this.checkExport(exports$1, 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$1, 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$1, elt); + } + } + } else if (type2 === "Property") { + this.checkPatternExport(exports$1, pat.value); + } else if (type2 === "AssignmentPattern") { + this.checkPatternExport(exports$1, pat.left); + } else if (type2 === "RestElement") { + this.checkPatternExport(exports$1, pat.argument); + } +}; +pp$8.checkVariableExport = function(exports$1, decls) { + if (!exports$1) { + return; + } + for (var i = 0, list = decls; i < list.length; i += 1) { + var decl = list[i]; + this.checkPatternExport(exports$1, 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$1) { + var node2 = this.startNode(); + node2.local = this.parseModuleExportName(); + node2.exported = this.eatContextual("as") ? this.parseModuleExportName() : node2.local; + this.checkExport( + exports$1, + node2.exported, + node2.exported.start + ); + return this.finishNode(node2, "ExportSpecifier"); +}; +pp$8.parseExportSpecifiers = function(exports$1) { + 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$1)); + } + 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": (snapshot2) => ["assertSnapshot", { snapshot: snapshot2 }] +}; +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 crxApp2 = await this._crx.get({ incognito }) ?? await this._crx.start({ incognito }, serverSideCallMetadata()); + await this._crx.player.run(crxApp2._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 crxApp2 = await this._crx.get({ incognito: false }); + const recorder = crxApp2 == null ? void 0 : crxApp2._recorder(); + if (recorder && crxApp2 && crxApp2._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 crxApp2 = 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 crxApp2._createRecorderApp(recorder); + else + return new EmptyRecorderApp(); + }; + }; + return crxApp2; + } + 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 crxApp2 = new CrxApplication2(this, context, transport); + await crxApp2.attach(incognitoTabId); + return crxApp2; + } + 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(); +browserExports$2.debug; +const INTERACTIVE_ROLES = /* @__PURE__ */ new Set([ + "button", + "link", + "textbox", + "checkbox", + "radio", + "combobox", + "menuitem", + "menuitemcheckbox", + "menuitemradio", + "option", + "slider", + "spinbutton", + "switch", + "tab", + "searchbox", + "treeitem" +]); +let refMap = /* @__PURE__ */ new Map(); +let refCounter = 0; +async function snapshot(page) { + const tree = await page.accessibility.snapshot(); + if (!tree) return "(empty page)"; + refMap.clear(); + refCounter = 0; + return formatNode(tree, 0); +} +function formatNode(node2, indent) { + const lines = []; + const pad = " ".repeat(indent); + const isInteractive = INTERACTIVE_ROLES.has(node2.role); + let ref2 = ""; + if (isInteractive) { + ref2 = `e${++refCounter}`; + refMap.set(ref2, { role: node2.role, name: node2.name }); + } + let desc = `${node2.role}`; + if (node2.name) desc += ` "${node2.name}"`; + if (ref2) desc += ` [ref=${ref2}]`; + const states = []; + if (node2.checked === true) states.push("checked"); + if (node2.checked === "mixed") states.push("mixed"); + if (node2.disabled) states.push("disabled"); + if (node2.expanded === true) states.push("expanded"); + if (node2.expanded === false) states.push("collapsed"); + if (node2.selected) states.push("selected"); + if (node2.pressed === true) states.push("pressed"); + if (node2.readonly) states.push("readonly"); + if (node2.required) states.push("required"); + if (states.length) desc += ` [${states.join(", ")}]`; + if (node2.value !== void 0) desc += `: "${node2.value}"`; + lines.push(`${pad}- ${desc}`); + if (node2.children) { + for (const child of node2.children) { + lines.push(formatNode(child, indent + 1)); + } + } + return lines.join("\n"); +} +function resolveRef(ref2) { + const entry = refMap.get(ref2); + if (!entry) throw new Error(`Unknown ref: ${ref2}. Run "snapshot" first.`); + return entry; +} +function getLocator(page, ref2) { + const entry = resolveRef(ref2); + return page.getByRole(entry.role, { name: entry.name, exact: true }); +} +async function execute(command2, page) { + const [keyword, ...args] = command2.trim().split(/\s+/); + try { + switch (keyword) { + case "snapshot": + return { text: await snapshot(page), isError: false }; + // goto, back, forward, reload are handled in background.ts via Chrome APIs + case "click": { + if (!args[0]) return { text: "Usage: click ", isError: true }; + await getLocator(page, args[0]).click(); + return { text: "Clicked", isError: false }; + } + case "fill": { + if (args.length < 2) return { text: "Usage: fill ", isError: true }; + await getLocator(page, args[0]).fill(args.slice(1).join(" ")); + return { text: "Filled", isError: false }; + } + case "type": { + if (args.length < 2) return { text: "Usage: type ", isError: true }; + await getLocator(page, args[0]).pressSequentially(args.slice(1).join(" ")); + return { text: "Typed", isError: false }; + } + case "press": { + if (args.length < 2) return { text: "Usage: press ", isError: true }; + await getLocator(page, args[0]).press(args.slice(1).join("+")); + return { text: "Pressed", isError: false }; + } + case "hover": { + if (!args[0]) return { text: "Usage: hover ", isError: true }; + await getLocator(page, args[0]).hover(); + return { text: "Hovered", isError: false }; + } + case "select": { + if (args.length < 2) return { text: "Usage: select ", isError: true }; + await getLocator(page, args[0]).selectOption(args.slice(1).join(" ")); + return { text: "Selected", isError: false }; + } + case "check": { + if (!args[0]) return { text: "Usage: check ", isError: true }; + await getLocator(page, args[0]).check(); + return { text: "Checked", isError: false }; + } + case "uncheck": { + if (!args[0]) return { text: "Usage: uncheck ", isError: true }; + await getLocator(page, args[0]).uncheck(); + return { text: "Unchecked", isError: false }; + } + case "screenshot": { + const buf = await page.screenshot(); + const base64 = buf.toString("base64"); + return { text: `data:image/png;base64,${base64}`, isError: false }; + } + case "wait": { + const ms2 = parseInt(args[0]) || 1e3; + await page.waitForTimeout(ms2); + return { text: `Waited ${ms2}ms`, isError: false }; + } + case "title": { + const title = await page.title(); + return { text: title, isError: false }; + } + case "url": + return { text: page.url(), isError: false }; + case "help": + return { + text: [ + "Commands:", + " snapshot — show accessibility tree with refs", + " goto — navigate to URL", + " click — click element", + " fill — fill input with text", + " type — type text character by character", + " press — press key (e.g. Enter, Tab)", + " hover — hover over element", + " select — select option by value", + " check — check checkbox", + " uncheck — uncheck checkbox", + " screenshot — capture screenshot", + " back / forward — navigate history", + " reload — reload page", + " wait [ms] — wait (default 1000ms)", + " title / url — show page title or URL" + ].join("\n"), + isError: false + }; + default: + return { text: `Unknown command: ${keyword}. Type "help" for commands.`, isError: true }; + } + } catch (e) { + return { text: String(e), isError: true }; + } +} +let crxApp = null; +let activePage = null; +let activeTabId = null; +chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }); +chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => { + if (msg.type === "attach") { + attachToTab(msg.tabId).then(sendResponse); + return true; + } + if (msg.type === "run") { + handleCommand(msg.command).then(sendResponse); + return true; + } +}); +function waitForTabLoad(tabId, timeout = 1e4) { + return new Promise((resolve) => { + let timer; + const listener = (id, info) => { + if (id === tabId && info.status === "complete") { + chrome.tabs.onUpdated.removeListener(listener); + clearTimeout(timer); + resolve(); + } + }; + chrome.tabs.onUpdated.addListener(listener); + timer = setTimeout(() => { + chrome.tabs.onUpdated.removeListener(listener); + resolve(); + }, timeout); + }); +} +async function getActiveTabId() { + if (activeTabId) return activeTabId; + const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true }); + return (tab == null ? void 0 : tab.id) ?? null; +} +async function navigateTab(url2) { + const tabId = await getActiveTabId(); + if (!tabId) return { text: "No active tab found.", isError: true }; + if (!activePage || activePage.isClosed()) { + await chrome.tabs.update(tabId, { url: "about:blank" }); + await waitForTabLoad(tabId, 2e3); + const result = await attachToTab(tabId); + if (!result.ok) { + return { text: `Cannot attach: ${result.error}`, isError: true }; + } + } + await chrome.tabs.update(tabId, { url: url2 }); + await waitForTabLoad(tabId); + return { text: `Navigated to ${url2}`, isError: false }; +} +async function goBackTab() { + const tabId = await getActiveTabId(); + if (!tabId) return { text: "No active tab found.", isError: true }; + await chrome.tabs.goBack(tabId); + await waitForTabLoad(tabId); + return { text: "Went back", isError: false }; +} +async function goForwardTab() { + const tabId = await getActiveTabId(); + if (!tabId) return { text: "No active tab found.", isError: true }; + await chrome.tabs.goForward(tabId); + await waitForTabLoad(tabId); + return { text: "Went forward", isError: false }; +} +async function reloadTab() { + const tabId = await getActiveTabId(); + if (!tabId) return { text: "No active tab found.", isError: true }; + await chrome.tabs.reload(tabId); + await waitForTabLoad(tabId); + return { text: "Reloaded", isError: false }; +} +async function attachToTab(tabId) { + var _a2; + try { + const tab = await chrome.tabs.get(tabId); + if ((_a2 = tab.url) == null ? void 0 : _a2.startsWith("chrome://")) { + return { ok: false, error: "Cannot attach to chrome:// pages. Navigate to a regular webpage first." }; + } + if (!crxApp) crxApp = await crx.start(); + if (activeTabId && activeTabId !== tabId) { + try { + await crxApp.detach(activeTabId); + } catch { + } + } + activePage = await crxApp.attach(tabId); + activeTabId = tabId; + return { ok: true, url: activePage.url() }; + } catch (e) { + activePage = null; + return { ok: false, error: String(e) }; + } +} +async function ensurePage() { + if (activePage && !activePage.isClosed()) return activePage; + const tabId = await getActiveTabId(); + if (tabId) { + const result = await attachToTab(tabId); + if (result.ok) return activePage; + } + return null; +} +async function handleCommand(command2) { + const [keyword, ...args] = command2.trim().split(/\s+/); + if (keyword === "goto") { + let url2 = args.join(" "); + if (!url2) return { text: "Usage: goto ", isError: true }; + if (!url2.startsWith("http")) url2 = `https://${url2}`; + return navigateTab(url2); + } + if (keyword === "back") return goBackTab(); + if (keyword === "forward") return goForwardTab(); + if (keyword === "reload") return reloadTab(); + const page = await ensurePage(); + if (!page) { + return { text: "Not attached to any tab. Click the connection indicator to reconnect.", isError: true }; + } + return await execute(command2, page); +} +//# sourceMappingURL=background.js.map diff --git a/packages/repl-ext/dist/background.js.map b/packages/repl-ext/dist/background.js.map new file mode 100644 index 0000000..552e239 --- /dev/null +++ b/packages/repl-ext/dist/background.js.map @@ -0,0 +1 @@ +{"version":3,"file":"background.js","sources":["../../../node_modules/playwright-crx/node_modules/process/browser.js","../../../node_modules/playwright-crx/src/shims/process.ts","../../../node_modules/playwright-crx/node_modules/setimmediate/setImmediate.js","../../../node_modules/playwright-crx/src/shims/setImmediate.ts","../../../node_modules/playwright-crx/node_modules/base64-js/index.js","../../../node_modules/playwright-crx/node_modules/ieee754/index.js","../../../node_modules/playwright-crx/node_modules/buffer/index.js","../../../node_modules/playwright-crx/src/shims/buffer.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/constants.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/Stats.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/internal/buffer.ts","../../../node_modules/playwright-crx/node_modules/has-symbols/shams.js","../../../node_modules/playwright-crx/node_modules/has-tostringtag/shams.js","../../../node_modules/playwright-crx/node_modules/es-object-atoms/index.js","../../../node_modules/playwright-crx/node_modules/es-errors/index.js","../../../node_modules/playwright-crx/node_modules/es-errors/eval.js","../../../node_modules/playwright-crx/node_modules/es-errors/range.js","../../../node_modules/playwright-crx/node_modules/es-errors/ref.js","../../../node_modules/playwright-crx/node_modules/es-errors/syntax.js","../../../node_modules/playwright-crx/node_modules/es-errors/type.js","../../../node_modules/playwright-crx/node_modules/es-errors/uri.js","../../../node_modules/playwright-crx/node_modules/math-intrinsics/abs.js","../../../node_modules/playwright-crx/node_modules/math-intrinsics/floor.js","../../../node_modules/playwright-crx/node_modules/math-intrinsics/max.js","../../../node_modules/playwright-crx/node_modules/math-intrinsics/min.js","../../../node_modules/playwright-crx/node_modules/math-intrinsics/pow.js","../../../node_modules/playwright-crx/node_modules/math-intrinsics/round.js","../../../node_modules/playwright-crx/node_modules/math-intrinsics/isNaN.js","../../../node_modules/playwright-crx/node_modules/math-intrinsics/sign.js","../../../node_modules/playwright-crx/node_modules/gopd/gOPD.js","../../../node_modules/playwright-crx/node_modules/gopd/index.js","../../../node_modules/playwright-crx/node_modules/es-define-property/index.js","../../../node_modules/playwright-crx/node_modules/has-symbols/index.js","../../../node_modules/playwright-crx/node_modules/get-proto/Reflect.getPrototypeOf.js","../../../node_modules/playwright-crx/node_modules/get-proto/Object.getPrototypeOf.js","../../../node_modules/playwright-crx/node_modules/function-bind/implementation.js","../../../node_modules/playwright-crx/node_modules/function-bind/index.js","../../../node_modules/playwright-crx/node_modules/call-bind-apply-helpers/functionCall.js","../../../node_modules/playwright-crx/node_modules/call-bind-apply-helpers/functionApply.js","../../../node_modules/playwright-crx/node_modules/call-bind-apply-helpers/reflectApply.js","../../../node_modules/playwright-crx/node_modules/call-bind-apply-helpers/actualApply.js","../../../node_modules/playwright-crx/node_modules/call-bind-apply-helpers/index.js","../../../node_modules/playwright-crx/node_modules/dunder-proto/get.js","../../../node_modules/playwright-crx/node_modules/get-proto/index.js","../../../node_modules/playwright-crx/node_modules/hasown/index.js","../../../node_modules/playwright-crx/node_modules/get-intrinsic/index.js","../../../node_modules/playwright-crx/node_modules/define-data-property/index.js","../../../node_modules/playwright-crx/node_modules/has-property-descriptors/index.js","../../../node_modules/playwright-crx/node_modules/set-function-length/index.js","../../../node_modules/playwright-crx/node_modules/call-bind-apply-helpers/applyBind.js","../../../node_modules/playwright-crx/node_modules/call-bind/index.js","../../../node_modules/playwright-crx/node_modules/call-bind/callBound.js","../../../node_modules/playwright-crx/node_modules/is-arguments/index.js","../../../node_modules/playwright-crx/node_modules/is-generator-function/index.js","../../../node_modules/playwright-crx/node_modules/is-callable/index.js","../../../node_modules/playwright-crx/node_modules/for-each/index.js","../../../node_modules/playwright-crx/node_modules/possible-typed-array-names/index.js","../../../node_modules/playwright-crx/node_modules/available-typed-arrays/index.js","../../../node_modules/playwright-crx/node_modules/call-bound/index.js","../../../node_modules/playwright-crx/node_modules/which-typed-array/index.js","../../../node_modules/playwright-crx/node_modules/is-typed-array/index.js","../../../node_modules/playwright-crx/node_modules/util/support/types.js","../../../node_modules/playwright-crx/node_modules/util/support/isBufferBrowser.js","../../../node_modules/playwright-crx/node_modules/inherits/inherits_browser.js","../../../node_modules/playwright-crx/node_modules/util/util.js","../../../node_modules/playwright-crx/node_modules/assert/build/internal/errors.js","../../../node_modules/playwright-crx/node_modules/assert/build/internal/assert/assertion_error.js","../../../node_modules/playwright-crx/node_modules/object-keys/isArguments.js","../../../node_modules/playwright-crx/node_modules/object-keys/implementation.js","../../../node_modules/playwright-crx/node_modules/object-keys/index.js","../../../node_modules/playwright-crx/node_modules/object.assign/implementation.js","../../../node_modules/playwright-crx/node_modules/object.assign/polyfill.js","../../../node_modules/playwright-crx/node_modules/object-is/implementation.js","../../../node_modules/playwright-crx/node_modules/object-is/polyfill.js","../../../node_modules/playwright-crx/node_modules/define-properties/index.js","../../../node_modules/playwright-crx/node_modules/object-is/shim.js","../../../node_modules/playwright-crx/node_modules/object-is/index.js","../../../node_modules/playwright-crx/node_modules/is-nan/implementation.js","../../../node_modules/playwright-crx/node_modules/is-nan/polyfill.js","../../../node_modules/playwright-crx/node_modules/is-nan/shim.js","../../../node_modules/playwright-crx/node_modules/is-nan/index.js","../../../node_modules/playwright-crx/node_modules/assert/build/internal/util/comparisons.js","../../../node_modules/playwright-crx/node_modules/assert/build/assert.js","../../../node_modules/playwright-crx/node_modules/memfs/src/internal/errors.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/encoding.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/Dirent.ts","../../../node_modules/playwright-crx/node_modules/path/node_modules/util/support/isBufferBrowser.js","../../../node_modules/playwright-crx/node_modules/path/node_modules/inherits/inherits_browser.js","../../../node_modules/playwright-crx/node_modules/path/node_modules/util/util.js","../../../node_modules/playwright-crx/node_modules/path/path.js","../../../node_modules/playwright-crx/node_modules/memfs/src/process.ts","../../../node_modules/playwright-crx/node_modules/events/events.js","../../../node_modules/playwright-crx/node_modules/memfs/src/node.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/setImmediate.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/queueMicrotask.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/setTimeoutUnref.ts","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/ours/primordials.js","../../../node_modules/playwright-crx/node_modules/abort-controller/browser.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/ours/util.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/ours/errors.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/validators.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/utils.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/end-of-stream.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/destroy.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/legacy.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/add-abort-signal.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/buffer_list.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/state.js","../../../node_modules/playwright-crx/node_modules/safe-buffer/index.js","../../../node_modules/playwright-crx/node_modules/string_decoder/lib/string_decoder.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/from.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/readable.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/writable.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/duplexify.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/duplex.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/transform.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/passthrough.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/pipeline.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/compose.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/operators.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/stream/promises.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/stream.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/ours/browser.js","../../../node_modules/playwright-crx/node_modules/memfs/src/node/constants.ts","../../../node_modules/playwright-crx/node_modules/punycode/punycode.js","../../../node_modules/playwright-crx/__vite-browser-external","../../../node_modules/playwright-crx/node_modules/object-inspect/index.js","../../../node_modules/playwright-crx/node_modules/side-channel-list/index.js","../../../node_modules/playwright-crx/node_modules/side-channel-map/index.js","../../../node_modules/playwright-crx/node_modules/side-channel-weakmap/index.js","../../../node_modules/playwright-crx/node_modules/side-channel/index.js","../../../node_modules/playwright-crx/node_modules/qs/lib/formats.js","../../../node_modules/playwright-crx/node_modules/qs/lib/utils.js","../../../node_modules/playwright-crx/node_modules/qs/lib/stringify.js","../../../node_modules/playwright-crx/node_modules/qs/lib/parse.js","../../../node_modules/playwright-crx/node_modules/qs/lib/index.js","../../../node_modules/playwright-crx/node_modules/url/url.js","../../../node_modules/playwright-crx/src/shims/url.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/node/util.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/node/FileHandle.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/node/FsPromises.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/json-joy/util/print/printTree.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/node-to-fsa/util.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/print/index.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/node/options.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/volume.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/node/lists/fsSynchronousApiList.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/node/lists/fsCallbackApiList.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/index.ts","../../../node_modules/playwright-crx/src/shims/fs.ts","../../../node_modules/playwright-crx/src/shims/global.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/protocol/validatorPrimitives.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/protocol/validator.ts","../../../node_modules/playwright-crx/src/protocol/validator.ts","../../../node_modules/playwright-crx/node_modules/os-browserify/browser.js","../../../node_modules/playwright-crx/src/shims/child_process.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/retry/lib/retry_operation.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/retry/lib/retry.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/retry/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/signal-exit/signals.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/signal-exit/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/src/third_party/lockfile.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/lib/styles.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/lib/system/has-flag.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/lib/system/supports-colors.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/lib/custom/trap.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/lib/custom/zalgo.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/lib/maps/america.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/lib/maps/zebra.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/lib/maps/rainbow.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/lib/maps/random.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/lib/colors.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/safe.js","../../../node_modules/playwright-crx/node_modules/ms/index.js","../../../node_modules/playwright-crx/node_modules/debug/src/common.js","../../../node_modules/playwright-crx/node_modules/debug/src/browser.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/diff/lib/index.mjs","../../../node_modules/playwright-crx/node_modules/randombytes/browser.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/internal/streams/stream-browser.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/internal/streams/buffer_list.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/internal/streams/destroy.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/errors-browser.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/internal/streams/state.js","../../../node_modules/playwright-crx/node_modules/util-deprecate/browser.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/_stream_writable.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/_stream_duplex.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/internal/streams/end-of-stream.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/internal/streams/async_iterator.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/internal/streams/from-browser.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/_stream_readable.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/_stream_transform.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/_stream_passthrough.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/internal/streams/pipeline.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/readable-browser.js","../../../node_modules/playwright-crx/node_modules/hash-base/index.js","../../../node_modules/playwright-crx/node_modules/md5.js/index.js","../../../node_modules/playwright-crx/node_modules/ripemd160/index.js","../../../node_modules/playwright-crx/node_modules/sha.js/hash.js","../../../node_modules/playwright-crx/node_modules/sha.js/sha.js","../../../node_modules/playwright-crx/node_modules/sha.js/sha1.js","../../../node_modules/playwright-crx/node_modules/sha.js/sha256.js","../../../node_modules/playwright-crx/node_modules/sha.js/sha224.js","../../../node_modules/playwright-crx/node_modules/sha.js/sha512.js","../../../node_modules/playwright-crx/node_modules/sha.js/sha384.js","../../../node_modules/playwright-crx/node_modules/sha.js/index.js","../../../node_modules/playwright-crx/node_modules/cipher-base/index.js","../../../node_modules/playwright-crx/node_modules/create-hash/browser.js","../../../node_modules/playwright-crx/node_modules/create-hmac/legacy.js","../../../node_modules/playwright-crx/node_modules/create-hash/md5.js","../../../node_modules/playwright-crx/node_modules/create-hmac/browser.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/algos.js","../../../node_modules/playwright-crx/node_modules/pbkdf2/lib/precondition.js","../../../node_modules/playwright-crx/node_modules/pbkdf2/lib/default-encoding.js","../../../node_modules/playwright-crx/node_modules/pbkdf2/lib/to-buffer.js","../../../node_modules/playwright-crx/node_modules/pbkdf2/lib/sync-browser.js","../../../node_modules/playwright-crx/node_modules/pbkdf2/lib/async.js","../../../node_modules/playwright-crx/node_modules/pbkdf2/browser.js","../../../node_modules/playwright-crx/node_modules/des.js/lib/des/utils.js","../../../node_modules/playwright-crx/node_modules/minimalistic-assert/index.js","../../../node_modules/playwright-crx/node_modules/des.js/lib/des/cipher.js","../../../node_modules/playwright-crx/node_modules/des.js/lib/des/des.js","../../../node_modules/playwright-crx/node_modules/des.js/lib/des/cbc.js","../../../node_modules/playwright-crx/node_modules/des.js/lib/des/ede.js","../../../node_modules/playwright-crx/node_modules/des.js/lib/des.js","../../../node_modules/playwright-crx/node_modules/browserify-des/index.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/modes/ecb.js","../../../node_modules/playwright-crx/node_modules/buffer-xor/index.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/modes/cbc.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/modes/cfb.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/modes/cfb8.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/modes/cfb1.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/modes/ofb.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/incr32.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/modes/ctr.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/modes/index.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/aes.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/ghash.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/authCipher.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/streamCipher.js","../../../node_modules/playwright-crx/node_modules/evp_bytestokey/index.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/encrypter.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/decrypter.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/browser.js","../../../node_modules/playwright-crx/node_modules/browserify-des/modes.js","../../../node_modules/playwright-crx/node_modules/browserify-cipher/browser.js","../../../node_modules/playwright-crx/node_modules/diffie-hellman/node_modules/bn.js/lib/bn.js","../../../node_modules/playwright-crx/node_modules/miller-rabin/node_modules/bn.js/lib/bn.js","../../../node_modules/playwright-crx/node_modules/brorand/index.js","../../../node_modules/playwright-crx/node_modules/miller-rabin/lib/mr.js","../../../node_modules/playwright-crx/node_modules/diffie-hellman/lib/generatePrime.js","../../../node_modules/playwright-crx/node_modules/diffie-hellman/lib/dh.js","../../../node_modules/playwright-crx/node_modules/diffie-hellman/browser.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/stream-browser.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/buffer_list.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/destroy.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/errors-browser.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/state.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_writable.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_duplex.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/end-of-stream.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/async_iterator.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/from-browser.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_readable.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_transform.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_passthrough.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/pipeline.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/readable-browser.js","../../../node_modules/playwright-crx/node_modules/bn.js/lib/bn.js","../../../node_modules/playwright-crx/node_modules/browserify-rsa/index.js","../../../node_modules/playwright-crx/node_modules/elliptic/node_modules/bn.js/lib/bn.js","../../../node_modules/playwright-crx/node_modules/minimalistic-crypto-utils/lib/utils.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/utils.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/curve/base.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/curve/short.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/curve/mont.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/curve/edwards.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/curve/index.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/utils.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/common.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/sha/common.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/sha/1.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/sha/256.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/sha/224.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/sha/512.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/sha/384.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/sha.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/ripemd.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/hmac.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/curves.js","../../../node_modules/playwright-crx/node_modules/hmac-drbg/lib/hmac-drbg.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/ec/key.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/ec/signature.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/ec/index.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/eddsa/key.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/eddsa/signature.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/eddsa/index.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic.js","../../../node_modules/playwright-crx/node_modules/asn1.js/node_modules/bn.js/lib/bn.js","../../../node_modules/playwright-crx/node_modules/safer-buffer/safer.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/base/reporter.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/base/buffer.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/base/node.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/constants/der.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/encoders/der.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/encoders/pem.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/encoders/index.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/decoders/der.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/decoders/pem.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/decoders/index.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/api.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/base/index.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/constants/index.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1.js","../../../node_modules/playwright-crx/node_modules/parse-asn1/certificate.js","../../../node_modules/playwright-crx/node_modules/parse-asn1/asn1.js","../../../node_modules/playwright-crx/node_modules/parse-asn1/fixProc.js","../../../node_modules/playwright-crx/node_modules/parse-asn1/index.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/browser/sign.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/browser/verify.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/browser/index.js","../../../node_modules/playwright-crx/node_modules/create-ecdh/node_modules/bn.js/lib/bn.js","../../../node_modules/playwright-crx/node_modules/create-ecdh/browser.js","../../../node_modules/playwright-crx/node_modules/public-encrypt/mgf.js","../../../node_modules/playwright-crx/node_modules/public-encrypt/xor.js","../../../node_modules/playwright-crx/node_modules/public-encrypt/node_modules/bn.js/lib/bn.js","../../../node_modules/playwright-crx/node_modules/public-encrypt/withPublic.js","../../../node_modules/playwright-crx/node_modules/public-encrypt/publicEncrypt.js","../../../node_modules/playwright-crx/node_modules/public-encrypt/privateDecrypt.js","../../../node_modules/playwright-crx/node_modules/public-encrypt/browser.js","../../../node_modules/playwright-crx/node_modules/randomfill/browser.js","../../../node_modules/playwright-crx/node_modules/crypto-browserify/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/dotenv/lib/main.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/proxy-from-env/index.js","../../../node_modules/playwright-crx/src/shims/net.ts","../../../node_modules/playwright-crx/src/shims/tls.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/agent-base/src/promisify.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/agent-base/src/index.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/https-proxy-agent/src/parse-proxy-response.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/https-proxy-agent/src/agent.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/https-proxy-agent/src/index.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/jpeg-js/lib/encoder.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/jpeg-js/lib/decoder.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/jpeg-js/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/mime/Mime.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/mime/types/standard.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/mime/types/other.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/mime/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/concat-map/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/balanced-match/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/brace-expansion/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/minimatch/minimatch.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/is-docker/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/is-wsl/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/define-lazy-prop/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/open/index.js","../../../node_modules/playwright-crx/node_modules/pako/lib/zlib/zstream.js","../../../node_modules/playwright-crx/node_modules/pako/lib/utils/common.js","../../../node_modules/playwright-crx/node_modules/pako/lib/zlib/trees.js","../../../node_modules/playwright-crx/node_modules/pako/lib/zlib/adler32.js","../../../node_modules/playwright-crx/node_modules/pako/lib/zlib/crc32.js","../../../node_modules/playwright-crx/node_modules/pako/lib/zlib/messages.js","../../../node_modules/playwright-crx/node_modules/pako/lib/zlib/deflate.js","../../../node_modules/playwright-crx/node_modules/pako/lib/zlib/inffast.js","../../../node_modules/playwright-crx/node_modules/pako/lib/zlib/inftrees.js","../../../node_modules/playwright-crx/node_modules/pako/lib/zlib/inflate.js","../../../node_modules/playwright-crx/node_modules/pako/lib/zlib/constants.js","../../../node_modules/playwright-crx/node_modules/browserify-zlib/lib/binding.js","../../../node_modules/playwright-crx/node_modules/browserify-zlib/lib/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/chunkstream.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/interlace.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/paeth-predictor.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/filter-parse.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/filter-parse-async.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/constants.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/crc.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/parser.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/bitmapper.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/format-normaliser.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/parser-async.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/bitpacker.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/filter-pack.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/packer.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/packer-async.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/sync-inflate.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/sync-reader.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/filter-parse-sync.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/parser-sync.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/packer-sync.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/png-sync.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/png.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/commander/lib/error.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/commander/lib/argument.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/commander/lib/help.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/commander/lib/option.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/commander/lib/suggestSimilar.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/commander/lib/command.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/commander/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/progress/lib/node-progress.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/progress/index.js","../../../node_modules/playwright-crx/src/shims/dns.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/smart-buffer/src/utils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/smart-buffer/src/smartbuffer.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/socks/src/common/constants.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/socks/src/common/util.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/ip-address/src/common.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/ip-address/src/v4/constants.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/ip-address/src/address-error.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/jsbn/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/sprintf-js/src/sprintf.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/ip-address/src/ipv4.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/ip-address/src/v6/constants.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/ip-address/src/v6/helpers.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/ip-address/src/v6/regular-expressions.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/ip-address/src/ipv6.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/ip-address/src/ip-address.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/socks/src/common/helpers.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/socks/src/common/receivebuffer.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/socks/src/client/socksclient.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/socks/src/index.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/socks-proxy-agent/src/agent.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/socks-proxy-agent/src/index.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/nodes/identity.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/visit.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/doc/directives.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/doc/anchors.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/doc/applyReviver.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/nodes/toJS.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/nodes/Node.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/nodes/Alias.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/nodes/Scalar.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/doc/createNode.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/nodes/Collection.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/stringify/stringifyComment.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/stringify/foldFlowLines.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/stringify/stringifyString.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/stringify/stringify.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/stringify/stringifyPair.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/log.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/nodes/addPairToJSMap.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/nodes/Pair.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/stringify/stringifyCollection.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/nodes/YAMLMap.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/common/map.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/nodes/YAMLSeq.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/common/seq.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/common/string.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/common/null.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/core/bool.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/stringify/stringifyNumber.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/core/float.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/core/int.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/core/schema.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/json/schema.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/yaml-1.1/float.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/yaml-1.1/int.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/yaml-1.1/set.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/tags.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/Schema.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/stringify/stringifyDocument.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/doc/Document.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/errors.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/resolve-props.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/util-contains-newline.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/util-flow-indent-check.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/util-map-includes.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/resolve-block-map.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/resolve-block-seq.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/resolve-end.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/resolve-flow-collection.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/compose-collection.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/resolve-block-scalar.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/compose-scalar.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/compose-node.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/compose-doc.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/composer.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/parse/cst-scalar.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/parse/cst-stringify.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/parse/cst-visit.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/parse/cst.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/parse/lexer.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/parse/line-counter.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/parse/parser.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/public-api.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/ws/browser.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/src/utilsBundleImpl.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utilsBundle.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/debugLogger.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/stackTrace.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/manualPromise.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/linuxUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/userAgent.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/wrappy/wrappy.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/once/once.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/end-of-stream/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/pump/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/get-stream/buffer-stream.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/get-stream/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/pend/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/yauzl/fd-slicer.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/buffer-crc32/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/yauzl/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/src/third_party/extract-zip.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/yazl/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/src/zipBundleImpl.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/zipBundle.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/fileUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/registry/browserFetcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/registry/nativeDeps.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/ascii.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/hostPlatform.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/spawnAsync.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/registry/dependencies.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/assert.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/headers.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/cssTokenizer.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/cssParser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/selectorParser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/stringUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/locatorGenerators.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/mimeType.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/multimap.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/protocolMetainfo.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/protocolFormatter.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/rtti.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/time.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/timeoutRunner.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/urlMatch.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/image_tools/colorUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/image_tools/imageChannel.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/image_tools/stats.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/image_tools/compare.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/third_party/pixelmatch.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/comparators.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/crypto.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/env.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/debug.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/eventsHelper.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/expectUtils.ts","../../../node_modules/playwright-crx/node_modules/stream-http/lib/capability.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/stream-browser.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/buffer_list.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/destroy.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/errors-browser.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/state.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/_stream_writable.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/_stream_duplex.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/end-of-stream.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/async_iterator.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/from-browser.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/_stream_readable.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/_stream_transform.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/_stream_passthrough.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/pipeline.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/readable-browser.js","../../../node_modules/playwright-crx/node_modules/stream-http/lib/response.js","../../../node_modules/playwright-crx/node_modules/stream-http/lib/request.js","../../../node_modules/playwright-crx/node_modules/xtend/immutable.js","../../../node_modules/playwright-crx/node_modules/builtin-status-codes/browser.js","../../../node_modules/playwright-crx/node_modules/stream-http/index.js","../../../node_modules/playwright-crx/node_modules/https-browserify/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/happyEyeballs.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/network.ts","../../../node_modules/playwright-crx/node_modules/inspector/node_modules/ws/lib/browser.js","../../../node_modules/playwright-crx/node_modules/endpoint/endpoint.js","../../../node_modules/playwright-crx/node_modules/inspector/inspector.js","../../../node_modules/playwright-crx/src/shims/async_hooks.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/zones.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/nodePlatform.ts","../../../node_modules/playwright-crx/src/shims/readline.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/processLauncher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/profiler.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/socksProxy.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/task.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/zipFile.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/registry/index.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/protocol/serializers.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/errors.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/instrumentation.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/protocolError.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/callLog.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/dispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/generated/clockSource.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/clock.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/debugger.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dialog.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/artifact.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/generated/utilityScriptSource.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/utilityScriptSerializers.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/javascript.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/progress.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/fileUploadUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/generated/injectedScriptSource.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dom.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/frameSelectors.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/helper.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/network.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/accessibility.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/console.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/fileChooser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/usKeyboardLayout.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/input.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/screenshotter.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/generated/bindingsControllerSource.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/page.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/types.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/frames.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/har/harTracer.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/har/harRecorder.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/codegen/language.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/recorder/recorderUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/recorder/recorderRunner.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/recorder/recorderCollection.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/generated/pollingRecorderSource.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/deviceDescriptors.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/codegen/csharp.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/codegen/javascript.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/codegen/java.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/codegen/jsonl.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/codegen/python.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/codegen/languages.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/recorder/throttledFile.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/recorder/contextRecorder.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/locatorParser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/recorder.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/launchApp.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/recorder/recorderApp.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/selectors.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/trace/recorder/snapshotterInjected.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/trace/recorder/snapshotter.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/trace/recorder/tracing.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/generated/storageScriptSource.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/browserContext.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/cookieStore.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/formData.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/socksClientCertificatesInterceptor.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/fetch.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/streamDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/artifactDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crConnection.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/cdpSessionDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/jsHandleDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/tracingDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/networkDispatchers.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/ariaSnapshot.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/frameDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/elementHandlerDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/generated/webSocketMockSource.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/webSocketRouteDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/pageDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/dialogDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/download.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/browser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crAccessibility.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crCoverage.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crProtocolHelper.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crDragDrop.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crExecutionContext.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/macEditingCommands.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crInput.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crNetworkManager.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crPdf.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/defaultFontFamilies.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/videoRecorder.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crPage.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crServiceWorker.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crBrowser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/writableStreamDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/pipeTransport.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/chromiumSwitches.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/android/android.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/androidDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/browserDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/browserTypeDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/transport.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/electron/electron.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/electronDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/harBackend.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/traceUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/localUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/jsonPipeDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/socksInterceptor.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/localUtilsDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/android/backendAdb.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/pipeTransport.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/browserType.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/bidiConnection.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/third_party/bidiProtocolCore.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/third_party/bidiProtocolPermissions.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/bidiNetworkManager.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/third_party/bidiDeserializer.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/third_party/bidiSerializer.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/bidiExecutionContext.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/third_party/bidiKeyboard.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/bidiInput.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/bidiPdf.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/bidiPage.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/bidiBrowser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/bidiChromium.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/third_party/firefoxPrefs.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/bidiFirefox.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crDevTools.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/chromium.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/debugController.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/firefox/ffConnection.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/firefox/ffAccessibility.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/firefox/ffExecutionContext.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/firefox/ffInput.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/firefox/ffNetworkManager.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/firefox/ffPage.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/firefox/ffBrowser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/firefox/firefox.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/webkit/wkConnection.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/webkit/wkAccessibility.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/webkit/wkExecutionContext.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/webkit/wkInput.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/webkit/wkInterceptableRequest.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/webkit/wkProvisionalPage.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/webkit/wkWorkers.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/webkit/wkPage.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/webkit/wkBrowser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/webkit/webkit.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/playwright.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/eventEmitter.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/clientStackTrace.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/channelOwner.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/stream.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/fileUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/artifact.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/cdpSession.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/clientHelper.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/clock.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/errors.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/jsHandle.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/accessibility.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/coverage.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/download.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/events.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/locatorUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/locator.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/tracing.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/timeoutSettings.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/fetch.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/waiter.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/worker.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/network.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/types.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/frame.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/writableStream.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/elementHandle.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/fileChooser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/harRouter.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/input.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/video.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/page.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/consoleMessage.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/dialog.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/webError.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/browserContext.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/webSocket.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/android.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/browser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/browserType.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/clientInstrumentation.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/electron.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/jsonPipe.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/localUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/selectors.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/playwright.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/connection.ts","../../../node_modules/playwright-crx/src/client/crx.ts","../../../node_modules/playwright-crx/src/client/crxPlaywright.ts","../../../node_modules/playwright-crx/src/client/crxConnection.ts","../../../node_modules/playwright-crx/src/server/recorder/popupRecorderWindow.ts","../../../node_modules/playwright-crx/src/server/recorder/sidepanelRecorderWindow.ts","../../../node_modules/playwright-crx/node_modules/acorn/dist/acorn.mjs","../../../node_modules/playwright-crx/node_modules/acorn-walk/dist/walk.mjs","../../../node_modules/playwright-crx/src/server/recorder/parser.ts","../../../node_modules/playwright-crx/src/server/recorder/crxRecorderApp.ts","../../../node_modules/playwright-crx/src/server/utils.ts","../../../node_modules/playwright-crx/src/server/transport/crxTransport.ts","../../../node_modules/playwright-crx/src/server/recorder/recorderUtils.ts","../../../node_modules/playwright-crx/src/server/recorder/crxPlayer.ts","../../../node_modules/playwright-crx/src/server/crx.ts","../../../node_modules/playwright-crx/src/server/crxPlaywright.ts","../../../node_modules/playwright-crx/src/server/dispatchers/crxDispatcher.ts","../../../node_modules/playwright-crx/src/server/dispatchers/crxPlaywrightDispatcher.ts","../../../node_modules/playwright-crx/src/client/crxZone.ts","../../../node_modules/playwright-crx/src/index.ts","../src/snapshot.ts","../src/commands.ts","../src/background.ts"],"sourcesContent":["// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","/**\n * Copyright (c) Rui Figueira.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// @ts-ignore\nimport process from 'process/browser';\n\n// https://github.com/cabinjs/browser-hrtime/blob/cb6b7c336e93726a302e04a5ac4755e7e353edaf/src/index.ts#L22\nprocess.hrtime = (previousTimestamp?: [number, number]): [number, number] => {\n const baseNow = Math.floor((Date.now() - performance.now()) * 1e-3);\n const clocktime = performance.now() * 1e-3;\n let seconds = Math.floor(clocktime) + baseNow;\n let nanoseconds = Math.floor((clocktime % 1) * 1e9);\n\n if (previousTimestamp) {\n seconds = seconds - previousTimestamp[0];\n nanoseconds = nanoseconds - previousTimestamp[1];\n if (nanoseconds < 0) {\n seconds--;\n nanoseconds += 1e9;\n }\n }\n return [seconds, nanoseconds];\n};\nprocess.platform = 'linux';\nprocess.versions.node = '18.16';\nprocess.stdout = { isTTY: 'false' };\nprocess.geteuid = () => '';\n\nprocess.env['PLAYWRIGHT_BROWSERS_PATH'] = '.';\n\nself.process = process;\n","(function (global, undefined) {\n \"use strict\";\n\n if (global.setImmediate) {\n return;\n }\n\n var nextHandle = 1; // Spec says greater than zero\n var tasksByHandle = {};\n var currentlyRunningATask = false;\n var doc = global.document;\n var registerImmediate;\n\n function setImmediate(callback) {\n // Callback can either be a function or a string\n if (typeof callback !== \"function\") {\n callback = new Function(\"\" + callback);\n }\n // Copy function arguments\n var args = new Array(arguments.length - 1);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i + 1];\n }\n // Store and register the task\n var task = { callback: callback, args: args };\n tasksByHandle[nextHandle] = task;\n registerImmediate(nextHandle);\n return nextHandle++;\n }\n\n function clearImmediate(handle) {\n delete tasksByHandle[handle];\n }\n\n function run(task) {\n var callback = task.callback;\n var args = task.args;\n switch (args.length) {\n case 0:\n callback();\n break;\n case 1:\n callback(args[0]);\n break;\n case 2:\n callback(args[0], args[1]);\n break;\n case 3:\n callback(args[0], args[1], args[2]);\n break;\n default:\n callback.apply(undefined, args);\n break;\n }\n }\n\n function runIfPresent(handle) {\n // From the spec: \"Wait until any invocations of this algorithm started before this one have completed.\"\n // So if we're currently running a task, we'll need to delay this invocation.\n if (currentlyRunningATask) {\n // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a\n // \"too much recursion\" error.\n setTimeout(runIfPresent, 0, handle);\n } else {\n var task = tasksByHandle[handle];\n if (task) {\n currentlyRunningATask = true;\n try {\n run(task);\n } finally {\n clearImmediate(handle);\n currentlyRunningATask = false;\n }\n }\n }\n }\n\n function installNextTickImplementation() {\n registerImmediate = function(handle) {\n process.nextTick(function () { runIfPresent(handle); });\n };\n }\n\n function canUsePostMessage() {\n // The test against `importScripts` prevents this implementation from being installed inside a web worker,\n // where `global.postMessage` means something completely different and can't be used for this purpose.\n if (global.postMessage && !global.importScripts) {\n var postMessageIsAsynchronous = true;\n var oldOnMessage = global.onmessage;\n global.onmessage = function() {\n postMessageIsAsynchronous = false;\n };\n global.postMessage(\"\", \"*\");\n global.onmessage = oldOnMessage;\n return postMessageIsAsynchronous;\n }\n }\n\n function installPostMessageImplementation() {\n // Installs an event handler on `global` for the `message` event: see\n // * https://developer.mozilla.org/en/DOM/window.postMessage\n // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages\n\n var messagePrefix = \"setImmediate$\" + Math.random() + \"$\";\n var onGlobalMessage = function(event) {\n if (event.source === global &&\n typeof event.data === \"string\" &&\n event.data.indexOf(messagePrefix) === 0) {\n runIfPresent(+event.data.slice(messagePrefix.length));\n }\n };\n\n if (global.addEventListener) {\n global.addEventListener(\"message\", onGlobalMessage, false);\n } else {\n global.attachEvent(\"onmessage\", onGlobalMessage);\n }\n\n registerImmediate = function(handle) {\n global.postMessage(messagePrefix + handle, \"*\");\n };\n }\n\n function installMessageChannelImplementation() {\n var channel = new MessageChannel();\n channel.port1.onmessage = function(event) {\n var handle = event.data;\n runIfPresent(handle);\n };\n\n registerImmediate = function(handle) {\n channel.port2.postMessage(handle);\n };\n }\n\n function installReadyStateChangeImplementation() {\n var html = doc.documentElement;\n registerImmediate = function(handle) {\n // Create a - - diff --git a/packages/extension/connect.js b/packages/extension/connect.js deleted file mode 100644 index 00d36ff..0000000 --- a/packages/extension/connect.js +++ /dev/null @@ -1,137 +0,0 @@ -const params = new URLSearchParams(window.location.search); -const mcpRelayUrl = params.get('mcpRelayUrl'); -const clientRaw = params.get('client') || '{}'; -const newTab = params.get('newTab') === 'true'; -const token = params.get('token'); - -const statusEl = document.getElementById('status'); -const buttonsEl = document.getElementById('buttons'); -const tabSectionEl = document.getElementById('tab-section'); - -let clientInfo = 'unknown'; -try { - const client = JSON.parse(clientRaw); - clientInfo = `${client.name}/${client.version}`; -} catch (e) {} - -function showStatus(type, message) { - statusEl.className = `status ${type}`; - statusEl.textContent = message; -} - -function showError(message) { - showStatus('error', message); - buttonsEl.innerHTML = ''; - tabSectionEl.innerHTML = ''; -} - -async function connectToMCPRelay() { - const response = await chrome.runtime.sendMessage({ type: 'connectToMCPRelay', mcpRelayUrl }); - if (!response.success) { - showError(response.error); - return false; - } - return true; -} - -async function connectToTab(tabId, windowId) { - buttonsEl.innerHTML = ''; - tabSectionEl.innerHTML = ''; - - try { - const response = await chrome.runtime.sendMessage({ - type: 'connectToTab', - mcpRelayUrl, - tabId, - windowId, - }); - - if (response?.success) { - showStatus('connected', `MCP client "${clientInfo}" connected.`); - } else { - showError(response?.error || `MCP client "${clientInfo}" failed to connect.`); - } - } catch (e) { - showError(`MCP client "${clientInfo}" failed to connect: ${e}`); - } -} - -async function loadTabs() { - const response = await chrome.runtime.sendMessage({ type: 'getTabs' }); - if (!response.success) { - showError('Failed to load tabs: ' + response.error); - return; - } - - tabSectionEl.innerHTML = '

Select page to expose to MCP server:

'; - for (const tab of response.tabs) { - const item = document.createElement('div'); - item.className = 'tab-item'; - const titleDiv = document.createElement('div'); - titleDiv.style.cssText = 'flex:1;min-width:0'; - const titleText = document.createElement('div'); - titleText.className = 'tab-title'; - titleText.textContent = tab.title || ''; - const urlText = document.createElement('div'); - urlText.className = 'tab-url'; - urlText.textContent = tab.url || ''; - titleDiv.append(titleText, urlText); - const btn = document.createElement('button'); - btn.className = 'btn-connect'; - btn.textContent = 'Connect'; - btn.onclick = () => connectToTab(tab.id, tab.windowId); - item.append(titleDiv, btn); - tabSectionEl.appendChild(item); - } -} - -// Listen for connection timeout -chrome.runtime.onMessage.addListener((message) => { - if (message.type === 'connectionTimeout') - showError('Connection timed out.'); -}); - -// ── Main flow ── -async function main() { - if (!mcpRelayUrl) { - showError('Missing mcpRelayUrl parameter in URL.'); - return; - } - - try { - const host = new URL(mcpRelayUrl).hostname; - if (host !== '127.0.0.1' && host !== '[::1]') { - showError(`Only loopback connections allowed. Received host: ${host}`); - return; - } - } catch (e) { - showError(`Invalid mcpRelayUrl: ${mcpRelayUrl}`); - return; - } - - showStatus('connecting', `Playwright MCP started from "${clientInfo}" is trying to connect.`); - - const ok = await connectToMCPRelay(); - if (!ok) return; - - if (newTab) { - const allowBtn = document.createElement('button'); - allowBtn.className = 'btn-allow'; - allowBtn.textContent = 'Allow'; - allowBtn.onclick = () => connectToTab(); - const rejectBtn = document.createElement('button'); - rejectBtn.className = 'btn-reject'; - rejectBtn.textContent = 'Reject'; - rejectBtn.onclick = () => showError('Connection rejected. This tab can be closed.'); - buttonsEl.append(allowBtn, rejectBtn); - } else { - const rejectBtn = document.createElement('button'); - rejectBtn.className = 'btn-reject'; - rejectBtn.textContent = 'Reject'; - rejectBtn.onclick = () => showError('Connection rejected. This tab can be closed.'); - buttonsEl.appendChild(rejectBtn); - await loadTabs(); - } -} - -main(); diff --git a/packages/extension/content/recorder.js b/packages/extension/content/recorder.js deleted file mode 100644 index 90eada7..0000000 --- a/packages/extension/content/recorder.js +++ /dev/null @@ -1,187 +0,0 @@ -// Content recorder — injected into the inspected page via CDP. -// Captures user interactions and sends .pw commands back via console.debug. - -(() => { - if (window.__pwRecorderActive) return; - window.__pwRecorderActive = true; - - function getLocator(el) { - const ariaLabel = el.getAttribute && el.getAttribute("aria-label"); - if (ariaLabel) return quote(ariaLabel); - - if (el.id) { - const label = document.querySelector('label[for="' + CSS.escape(el.id) + '"]'); - if (label && label.textContent.trim()) return quote(label.textContent.trim()); - } - const parentLabel = el.closest && el.closest("label"); - if (parentLabel && parentLabel.textContent.trim()) { - return quote(parentLabel.textContent.trim()); - } - - if (el.placeholder) return quote(el.placeholder); - - const text = el.textContent ? el.textContent.trim() : ""; - if (text && text.length < 80 && el.children.length === 0) return quote(text); - - if ((el.tagName === "BUTTON" || el.tagName === "A") && text && text.length < 80) { - return quote(text); - } - - if (el.title) return quote(el.title); - - const tag = el.tagName ? el.tagName.toLowerCase() : "unknown"; - return quote(tag); - } - - // Get the primary text of a container (e.g., a list item's label) - function getItemContext(el) { - const item = el.closest && el.closest("li, tr, [role=listitem], [role=row], article"); - if (!item) return null; - // Look for a label, heading, or primary text element - const primary = item.querySelector("label, h1, h2, h3, h4, [class*=title], [class*=text], p, span"); - if (primary && primary !== el && primary.textContent.trim()) { - const t = primary.textContent.trim(); - if (t.length < 80) return t; - } - return null; - } - - function quote(s) { - return '"' + s.replace(/"/g, '\\"') + '"'; - } - - function send(command) { - console.debug("__pw:" + command); - } - - let fillTimer = null; - let fillTarget = null; - let fillValue = ""; - - function flushFill() { - if (fillTarget && fillValue) { - const locator = getLocator(fillTarget); - send('fill ' + locator + ' "' + fillValue.replace(/"/g, '\\"') + '"'); - } - fillTimer = null; - fillTarget = null; - fillValue = ""; - } - - // Elements that are non-interactive containers — skip recording clicks on these - var skipTags = new Set(["HTML", "BODY", "MAIN", "FOOTER", "HEADER", "NAV", "SECTION", "ARTICLE", "DIV", "UL", "OL", "FORM", "FIELDSET", "TABLE", "TBODY", "THEAD", "TR"]); - - function findCheckbox(el) { - // Check if el itself is a checkbox - if (el.tagName === "INPUT" && el.type === "checkbox") return el; - // Check if clicking a label that toggles a checkbox - if (el.tagName === "LABEL") { - var input = el.querySelector('input[type="checkbox"]'); - if (input) return input; - if (el.htmlFor) { - var target = document.getElementById(el.htmlFor); - if (target && target.type === "checkbox") return target; - } - } - // Check only the immediate parent label (not li/div which are too broad) - var parentLabel = el.closest("label"); - if (parentLabel) { - var cb = parentLabel.querySelector('input[type="checkbox"]'); - if (cb) return cb; - } - return null; - } - - function handleClick(e) { - try { - if (fillTimer) { clearTimeout(fillTimer); flushFill(); } - var el = e.target; - if (!el || !el.tagName) return; - - // Skip text inputs and textareas - if ((el.tagName === "INPUT" && el.type !== "checkbox" && el.type !== "radio") || el.tagName === "TEXTAREA") return; - - // Skip clicks on non-interactive container elements - if (skipTags.has(el.tagName) && !el.getAttribute("role") && !el.getAttribute("onclick")) return; - - // Check for checkbox (direct or via label/parent) - var checkbox = findCheckbox(el); - if (checkbox) { - var cbLabel = getItemContext(checkbox) || ""; - if (cbLabel) { - send(checkbox.checked ? 'check "' + cbLabel + '"' : 'uncheck "' + cbLabel + '"'); - } else { - var loc = getLocator(checkbox); - send(checkbox.checked ? 'check ' + loc : 'uncheck ' + loc); - } - return; - } - - var locator = getLocator(el); - // Detect action buttons (Delete, Remove, Edit, close icons, etc.) - // by text content, class name, or aria-label - var actionWords = new Set(["delete", "remove", "edit", "close", "destroy", "\u00d7", "\u2715", "\u2716", "\u2717", "\u2718", "x"]); - var elText = (el.textContent || "").trim().toLowerCase(); - var elClass = (el.className || "").toLowerCase(); - var elAriaLabel = (el.getAttribute && el.getAttribute("aria-label") || "").toLowerCase(); - var isAction = actionWords.has(elText) - || [...actionWords].some(function(w) { return elClass.includes(w); }) - || [...actionWords].some(function(w) { return elAriaLabel.includes(w); }) - || (el.tagName === "BUTTON" && !elText && el.closest && el.closest("li, tr, [role=listitem]")); - try { - var ctx = getItemContext(el); - if (ctx && isAction) { - send('click ' + locator + ' "' + ctx.replace(/"/g, '\\"') + '"'); - } else { - send('click ' + locator); - } - } catch(ce) { - send('click ' + locator); - } - } catch(err) { - console.debug("__pw:# click recording error: " + err.message); - } - } - - function handleInput(e) { - const el = e.target; - if (el.tagName !== "INPUT" && el.tagName !== "TEXTAREA") return; - if (el.type === "checkbox" || el.type === "radio") return; - fillTarget = el; - fillValue = el.value; - if (fillTimer) clearTimeout(fillTimer); - fillTimer = setTimeout(flushFill, 1500); - } - - function handleChange(e) { - const el = e.target; - if (el.tagName === "SELECT") { - const opt = el.options[el.selectedIndex]; - const optText = opt ? opt.text.trim() : el.value; - send('select ' + getLocator(el) + ' "' + optText.replace(/"/g, '\\"') + '"'); - } - } - - function handleKeydown(e) { - const specialKeys = ["Enter", "Tab", "Escape"]; - if (specialKeys.includes(e.key)) { - if (fillTimer) { clearTimeout(fillTimer); flushFill(); } - send('press ' + e.key); - } - } - - document.addEventListener("click", handleClick, true); - document.addEventListener("input", handleInput, true); - document.addEventListener("change", handleChange, true); - document.addEventListener("keydown", handleKeydown, true); - - window.__pwRecorderCleanup = () => { - if (fillTimer) { clearTimeout(fillTimer); flushFill(); } - document.removeEventListener("click", handleClick, true); - document.removeEventListener("input", handleInput, true); - document.removeEventListener("change", handleChange, true); - document.removeEventListener("keydown", handleKeydown, true); - window.__pwRecorderActive = false; - delete window.__pwRecorderCleanup; - }; -})(); diff --git a/packages/extension/devtools.html b/packages/extension/devtools.html deleted file mode 100644 index c317bf3..0000000 --- a/packages/extension/devtools.html +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/packages/extension/devtools.js b/packages/extension/devtools.js deleted file mode 100644 index 89d94ed..0000000 --- a/packages/extension/devtools.js +++ /dev/null @@ -1,5 +0,0 @@ -chrome.devtools.panels.create( - "Playwright REPL", - "icons/icon16.png", - "panel/panel.html" -); diff --git a/packages/extension/lib/relayConnection.js b/packages/extension/lib/relayConnection.js deleted file mode 100644 index 51a0a39..0000000 --- a/packages/extension/lib/relayConnection.js +++ /dev/null @@ -1,142 +0,0 @@ -/** - * RelayConnection — CDP relay over WebSocket. - * - * Copied from Playwright MCP Bridge (packages/extension/src/relayConnection.ts), - * converted to plain JS. Bridges chrome.debugger <-> WebSocket so Playwright - * can control a browser tab via connectOverCDP. - * - * Protocol (3 message types): - * Server -> Extension: - * { id, method: "attachToTab", params: {} } - * -> attach chrome.debugger, return targetInfo - * { id, method: "forwardCDPCommand", params: { sessionId, method, params } } - * -> forward to chrome.debugger - * Extension -> Server: - * { method: "forwardCDPEvent", params: { sessionId, method, params } } - * -> forward chrome.debugger.onEvent to server - */ - -export function debugLog(...args) { - console.log('[Extension]', ...args); -} - -export class RelayConnection { - constructor(ws) { - this._debuggee = {}; - this._ws = ws; - this._closed = false; - this.onclose = null; - - // Tab ID is set later via setTabId(); attachToTab waits for it. - this._tabPromise = new Promise(resolve => { - this._tabPromiseResolve = resolve; - }); - - this._ws.onmessage = (event) => this._onMessage(event); - this._ws.onclose = () => this._onClose(); - - // Store listeners for cleanup - this._eventListener = (source, method, params) => this._onDebuggerEvent(source, method, params); - this._detachListener = (source, reason) => this._onDebuggerDetach(source, reason); - chrome.debugger.onEvent.addListener(this._eventListener); - chrome.debugger.onDetach.addListener(this._detachListener); - } - - // Either setTabId or close is called after creating the connection. - setTabId(tabId) { - this._debuggee = { tabId }; - this._tabPromiseResolve(); - } - - close(message) { - this._ws.close(1000, message); - // ws.onclose is called asynchronously, so we call it here to avoid forwarding - // CDP events to the closed connection. - this._onClose(); - } - - _onClose() { - if (this._closed) return; - this._closed = true; - chrome.debugger.onEvent.removeListener(this._eventListener); - chrome.debugger.onDetach.removeListener(this._detachListener); - chrome.debugger.detach(this._debuggee).catch(() => {}); - this.onclose?.(); - } - - // ─── CDP events from browser -> server ────────────────────────────────── - - _onDebuggerEvent(source, method, params) { - if (source.tabId !== this._debuggee.tabId) return; - debugLog('Forwarding CDP event:', method, params); - const sessionId = source.sessionId; - this._sendMessage({ - method: 'forwardCDPEvent', - params: { sessionId, method, params }, - }); - } - - _onDebuggerDetach(source, reason) { - if (source.tabId !== this._debuggee.tabId) return; - this.close(`Debugger detached: ${reason}`); - this._debuggee = {}; - } - - // ─── Messages from server -> extension ────────────────────────────────── - - _onMessage(event) { - this._onMessageAsync(event).catch(e => debugLog('Error handling message:', e)); - } - - async _onMessageAsync(event) { - let message; - try { - message = JSON.parse(event.data); - } catch (error) { - debugLog('Error parsing message:', error); - this._sendError(-32700, `Error parsing message: ${error.message}`); - return; - } - - debugLog('Received message:', message); - - const response = { id: message.id }; - try { - response.result = await this._handleCommand(message); - } catch (error) { - debugLog('Error handling command:', error); - response.error = error.message; - } - debugLog('Sending response:', response); - this._sendMessage(response); - } - - async _handleCommand(message) { - if (message.method === 'attachToTab') { - await this._tabPromise; - debugLog('Attaching debugger to tab:', this._debuggee); - await chrome.debugger.attach(this._debuggee, '1.3'); - const result = await chrome.debugger.sendCommand(this._debuggee, 'Target.getTargetInfo'); - return { targetInfo: result?.targetInfo }; - } - if (!this._debuggee.tabId) - throw new Error('No tab is connected.'); - if (message.method === 'forwardCDPCommand') { - const { sessionId, method, params } = message.params; - debugLog('CDP command:', method, params); - const debuggerSession = { ...this._debuggee, sessionId }; - return await chrome.debugger.sendCommand(debuggerSession, method, params); - } - } - - _sendError(code, message) { - this._sendMessage({ - error: { code, message }, - }); - } - - _sendMessage(message) { - if (this._ws.readyState === WebSocket.OPEN) - this._ws.send(JSON.stringify(message)); - } -} diff --git a/packages/extension/manifest.json b/packages/extension/manifest.json index 56fba98..739aa4d 100644 --- a/packages/extension/manifest.json +++ b/packages/extension/manifest.json @@ -2,12 +2,11 @@ "manifest_version": 3, "name": "Playwright REPL", "version": "1.0.0", - "description": "A REPL panel inside Chrome DevTools for Playwright-style browser automation commands.", - "devtools_page": "devtools.html", + "description": "A side panel for Playwright-style browser automation commands.", "permissions": [ - "debugger", "activeTab", - "tabs" + "tabs", + "sidePanel" ], "host_permissions": [ "" @@ -20,9 +19,11 @@ "128": "icons/icon128.png" } }, + "side_panel": { + "default_path": "panel/panel.html" + }, "background": { - "service_worker": "background.js", - "type": "module" + "service_worker": "background.js" }, "icons": { "16": "icons/icon16.png", diff --git a/packages/extension/panel/panel.js b/packages/extension/panel/panel.js index a5b6f4d..d468329 100644 --- a/packages/extension/panel/panel.js +++ b/packages/extension/panel/panel.js @@ -26,12 +26,12 @@ const lightboxCloseBtn = document.getElementById("lightbox-close-btn"); const ghostText = document.getElementById("ghost-text"); const dropdown = document.getElementById("autocomplete-dropdown"); -// The tab we're inspecting -const inspectedTabId = chrome.devtools.inspectedWindow.tabId; +// --- Server config --- +const SERVER_PORT = 6781; +const SERVER_URL = `http://localhost:${SERVER_PORT}`; // --- Theme detection --- -const themeName = chrome.devtools?.panels?.themeName; -if (themeName === "dark") { +if (window.matchMedia("(prefers-color-scheme: dark)").matches) { document.body.classList.add("theme-dark"); } @@ -425,61 +425,29 @@ async function executeCommand(raw) { addCommand(trimmed); try { - const result = await chrome.runtime.sendMessage({ - type: "pw-command", - raw: trimmed, - tabId: inspectedTabId, + const res = await fetch(`${SERVER_URL}/run`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ raw: trimmed }), }); + const result = await res.json(); - if (!result) { - addError("No response from background worker."); - return; - } - - // Handle Engine result format: { text, isError } - if (result.text !== undefined) { - if (result.isError) { - addError(result.text); - } else { - // Detect result type from content - const text = result.text; - if (text.startsWith("data:image/png;base64,")) { - addScreenshot(text.slice("data:image/png;base64,".length)); - } else if (text.includes("[ref=") || text.startsWith("- ")) { - for (const line of text.split("\n")) { - addSnapshot(line); - } - } else { - addSuccess(text); - } - } - return; - } - - // Legacy format: { type, data, success } - switch (result.type) { - case "success": - addSuccess(result.data); - break; - case "error": - addError(result.data); - break; - case "info": - addInfo(result.data); - break; - case "snapshot": - for (const line of result.data.split("\n")) { + if (result.isError) { + addError(result.text); + } else { + const text = result.text; + if (text.startsWith("data:image/png;base64,")) { + addScreenshot(text.slice("data:image/png;base64,".length)); + } else if (text.includes("[ref=") || text.startsWith("- ")) { + for (const line of text.split("\n")) { addSnapshot(line); } - break; - case "screenshot": - addScreenshot(result.data); - break; - default: - addInfo(result.data || "Done."); + } else { + addSuccess(text); + } } } catch (e) { - addError(`Error: ${e.message}`); + addError("Not connected to server. Run: playwright-repl --extension"); } } @@ -498,82 +466,33 @@ async function executeCommandForRun(raw) { addCommand(trimmed); try { - const result = await chrome.runtime.sendMessage({ - type: "pw-command", - raw: trimmed, - tabId: inspectedTabId, + const res = await fetch(`${SERVER_URL}/run`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ raw: trimmed }), }); + const result = await res.json(); - if (!result) { - addError("No response from background worker."); + if (result.isError) { + addError(result.text); lineResults[currentRunLine] = "fail"; runFailCount++; - updateConsoleStats(); - updateLineNumbers(); - return; - } - - // Handle Engine result format: { text, isError } - if (result.text !== undefined) { - if (result.isError) { - addError(result.text); - lineResults[currentRunLine] = "fail"; - runFailCount++; - } else { - const text = result.text; - if (text.startsWith("data:image/png;base64,")) { - addScreenshot(text.slice("data:image/png;base64,".length)); - } else if (text.includes("[ref=") || text.startsWith("- ")) { - for (const line of text.split("\n")) { - addSnapshot(line); - } - } else { - addSuccess(text); - } - lineResults[currentRunLine] = "pass"; - runPassCount++; - } - updateConsoleStats(); - updateLineNumbers(); - return; - } - - // Legacy format: { type, data, success } - switch (result.type) { - case "success": - addSuccess(result.data); - lineResults[currentRunLine] = "pass"; - runPassCount++; - break; - case "error": - addError(result.data); - lineResults[currentRunLine] = "fail"; - runFailCount++; - break; - case "info": - addInfo(result.data); - lineResults[currentRunLine] = "pass"; - runPassCount++; - break; - case "snapshot": - for (const line of result.data.split("\n")) { + } else { + const text = result.text; + if (text.startsWith("data:image/png;base64,")) { + addScreenshot(text.slice("data:image/png;base64,".length)); + } else if (text.includes("[ref=") || text.startsWith("- ")) { + for (const line of text.split("\n")) { addSnapshot(line); } - lineResults[currentRunLine] = "pass"; - runPassCount++; - break; - case "screenshot": - addScreenshot(result.data); - lineResults[currentRunLine] = "pass"; - runPassCount++; - break; - default: - addInfo(result.data || "Done."); - lineResults[currentRunLine] = "pass"; - runPassCount++; + } else { + addSuccess(text); + } + lineResults[currentRunLine] = "pass"; + runPassCount++; } } catch (e) { - addError(`Error: ${e.message}`); + addError("Not connected to server. Run: playwright-repl --extension"); lineResults[currentRunLine] = "fail"; runFailCount++; } @@ -905,68 +824,10 @@ copyBtn.addEventListener("click", () => { consoleClearBtn.addEventListener("click", clearConsole); -// --- Record button --- - -recordBtn.addEventListener("click", async () => { - recordBtn.classList.toggle("recording"); - const isRecording = recordBtn.classList.contains("recording"); - recordBtn.textContent = isRecording ? "\u23F9 Stop" : "\u23FA Record"; - - if (isRecording) { - try { - const result = await chrome.runtime.sendMessage({ - type: "pw-record-start", - tabId: inspectedTabId, - }); - if (result?.success) { - addInfo("Recording started. Interact with the page..."); - } else { - addError("Failed to start recording: " + (result?.error || "unknown")); - recordBtn.classList.remove("recording"); - recordBtn.textContent = "\u23FA Record"; - } - } catch (e) { - addError("Record error: " + e.message); - recordBtn.classList.remove("recording"); - recordBtn.textContent = "\u23FA Record"; - } - } else { - await chrome.runtime.sendMessage({ - type: "pw-record-stop", - tabId: inspectedTabId, - }); - addInfo("Recording stopped."); - } -}); - -// --- Port connection for recorded commands --- -// Service workers in Manifest V3 can terminate and restart at any time. -// When that happens, the port disconnects and panelPorts is lost. -// We reconnect automatically so recording keeps working. - -let port = null; - -function connectPort() { - // chrome.runtime.id is undefined when the extension context is invalidated - // (e.g., after extension reload/update). Stop retrying in that case. - if (!chrome.runtime?.id) return; - try { - port = chrome.runtime.connect({ name: `pw-panel-${inspectedTabId}` }); - } catch (e) { - return; - } - port.onMessage.addListener((message) => { - if (message.type === "pw-recorded-command") { - appendToEditor(message.command); - } - }); - port.onDisconnect.addListener(() => { - if (!chrome.runtime?.id) return; - setTimeout(connectPort, 500); - }); -} +// --- Record button (deferred — recording not yet supported in v3) --- -connectPort(); +recordBtn.disabled = true; +recordBtn.title = "Recording not available in side panel mode"; // --- Draggable splitter --- @@ -1044,4 +905,17 @@ updateButtonStates(); editor.focus(); addInfo("Playwright REPL v1.0.0"); -addInfo('Type commands below or open a .pw file in the editor.'); + +// Health check — verify server is running +(async () => { + try { + const res = await fetch(`${SERVER_URL}/health`); + if (res.ok) { + addInfo("Connected to server on port " + SERVER_PORT); + } else { + addError("Server returned status " + res.status); + } + } catch { + addError("Server not running. Start with: playwright-repl --extension"); + } +})(); diff --git a/packages/extension/test/background.test.js b/packages/extension/test/background.test.js deleted file mode 100644 index 730337c..0000000 --- a/packages/extension/test/background.test.js +++ /dev/null @@ -1,392 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { chrome } from "vitest-chrome/lib/index.esm.js"; -import { readFileSync } from "fs"; -import { resolve } from "path"; -import { RelayConnection } from "../lib/relayConnection.js"; - -// Read the actual recorder.js file content for fetch mock -const recorderCode = readFileSync( - resolve(import.meta.dirname, "..", "content", "recorder.js"), - "utf-8" -); - -// Mock WebSocket -class MockWebSocket { - constructor(url) { - this.url = url; - this.readyState = 1; // OPEN - this.send = vi.fn(); - this.close = vi.fn(); - } -} -MockWebSocket.OPEN = 1; -MockWebSocket.CLOSED = 3; -globalThis.WebSocket = MockWebSocket; - -// Mock fetch -globalThis.fetch = vi.fn(() => - Promise.resolve({ text: () => Promise.resolve(recorderCode) }) -); -chrome.runtime.getURL = vi.fn((path) => `chrome-extension://test/${path}`); - -// Mock chrome.action (not provided by vitest-chrome) -chrome.action = { - onClicked: { addListener: vi.fn() }, - setBadgeText: vi.fn(() => Promise.resolve()), - setBadgeBackgroundColor: vi.fn(() => Promise.resolve()), - setTitle: vi.fn(() => Promise.resolve()), -}; - -// ─── Import + reset helpers ───────────────────────────────────────────────── - -let mod; -let getState, resetState; - -beforeEach(async () => { - vi.restoreAllMocks(); - - globalThis.WebSocket = MockWebSocket; - globalThis.fetch = vi.fn(() => - Promise.resolve({ text: () => Promise.resolve(recorderCode) }) - ); - globalThis.chrome = chrome; - chrome.runtime.getURL = vi.fn((path) => `chrome-extension://test/${path}`); - chrome.debugger.sendCommand.mockReset(); - chrome.debugger.attach.mockReset(); - chrome.debugger.detach.mockReset(); - chrome.debugger.onEvent.clearListeners(); - chrome.debugger.onDetach.clearListeners(); - chrome.runtime.onConnect.clearListeners(); - chrome.runtime.onMessage.clearListeners(); - chrome.action = { - onClicked: { addListener: vi.fn() }, - setBadgeText: vi.fn(() => Promise.resolve()), - setBadgeBackgroundColor: vi.fn(() => Promise.resolve()), - setTitle: vi.fn(() => Promise.resolve()), - }; - - vi.resetModules(); - mod = await import("../background.js"); - getState = mod._getState; - resetState = mod._resetState; -}); - -// ─── Tests ────────────────────────────────────────────────────────────────── - -describe("handlePanelCommand", () => { - it("sends HTTP POST to command server", async () => { - globalThis.fetch = vi.fn(() => - Promise.resolve({ - json: () => Promise.resolve({ text: "Clicked", isError: false }), - }) - ); - - const result = await mod.handlePanelCommand("click e5"); - - expect(globalThis.fetch).toHaveBeenCalledWith( - "http://127.0.0.1:3000/run", - { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ raw: "click e5" }), - } - ); - expect(result.text).toBe("Clicked"); - expect(result.isError).toBe(false); - }); - - it("returns error when server is not reachable", async () => { - globalThis.fetch = vi.fn(() => - Promise.reject(new Error("Connection refused")) - ); - - const result = await mod.handlePanelCommand("snapshot"); - - expect(result.isError).toBe(true); - expect(result.text).toContain("Not connected to server"); - }); -}); - -describe("RelayConnection", () => { - it("handles attachToTab by attaching debugger and returning real targetInfo", async () => { - chrome.debugger.attach.mockResolvedValue(undefined); - chrome.debugger.sendCommand.mockResolvedValue({ - targetInfo: { - targetId: "ABC123", - type: "page", - title: "Example", - url: "http://example.com", - browserContextId: "CTX1", - }, - }); - - const mockWs = new MockWebSocket("ws://test"); - const relay = new RelayConnection(mockWs); - relay.setTabId(42); - - // Simulate server sending attachToTab - await relay._onMessageAsync({ - data: JSON.stringify({ id: 1, method: "attachToTab", params: {} }), - }); - - // Should have attached to tab 42 - expect(chrome.debugger.attach).toHaveBeenCalledWith({ tabId: 42 }, "1.3"); - - // Should have called Target.getTargetInfo via CDP - expect(chrome.debugger.sendCommand).toHaveBeenCalledWith( - { tabId: 42 }, - "Target.getTargetInfo" - ); - - // Should have sent response with real targetInfo - expect(mockWs.send).toHaveBeenCalled(); - const response = JSON.parse(mockWs.send.mock.calls[0][0]); - expect(response.id).toBe(1); - expect(response.result.targetInfo.targetId).toBe("ABC123"); - expect(response.result.targetInfo.browserContextId).toBe("CTX1"); - }); - - it("handles forwardCDPCommand with sessionId", async () => { - chrome.debugger.sendCommand.mockResolvedValue({ result: { value: 42 } }); - - const mockWs = new MockWebSocket("ws://test"); - const relay = new RelayConnection(mockWs); - relay.setTabId(10); - - await relay._onMessageAsync({ - data: JSON.stringify({ - id: 2, - method: "forwardCDPCommand", - params: { - sessionId: "session-1", - method: "Runtime.evaluate", - params: { expression: "1+1" }, - }, - }), - }); - - // Should pass sessionId directly to chrome.debugger - expect(chrome.debugger.sendCommand).toHaveBeenCalledWith( - { tabId: 10, sessionId: "session-1" }, - "Runtime.evaluate", - { expression: "1+1" } - ); - - const response = JSON.parse(mockWs.send.mock.calls[0][0]); - expect(response.id).toBe(2); - expect(response.result).toEqual({ result: { value: 42 } }); - }); - - it("handles forwardCDPCommand without sessionId", async () => { - chrome.debugger.sendCommand.mockResolvedValue({}); - - const mockWs = new MockWebSocket("ws://test"); - const relay = new RelayConnection(mockWs); - relay.setTabId(10); - - await relay._onMessageAsync({ - data: JSON.stringify({ - id: 3, - method: "forwardCDPCommand", - params: { method: "Page.enable", params: {} }, - }), - }); - - expect(chrome.debugger.sendCommand).toHaveBeenCalledWith( - { tabId: 10, sessionId: undefined }, - "Page.enable", - {} - ); - }); - - it("forwards CDP events to server", () => { - const mockWs = new MockWebSocket("ws://test"); - const relay = new RelayConnection(mockWs); - relay.setTabId(10); - - // Simulate chrome.debugger.onEvent - chrome.debugger.onEvent.callListeners( - { tabId: 10, sessionId: undefined }, - "Page.loadEventFired", - { timestamp: 123 } - ); - - expect(mockWs.send).toHaveBeenCalled(); - const sent = JSON.parse(mockWs.send.mock.calls[0][0]); - expect(sent.method).toBe("forwardCDPEvent"); - expect(sent.params.method).toBe("Page.loadEventFired"); - expect(sent.params.params.timestamp).toBe(123); - }); - - it("ignores CDP events from other tabs", () => { - const mockWs = new MockWebSocket("ws://test"); - const relay = new RelayConnection(mockWs); - relay.setTabId(10); - - chrome.debugger.onEvent.callListeners( - { tabId: 99 }, - "Page.loadEventFired", - {} - ); - - expect(mockWs.send).not.toHaveBeenCalled(); - }); - - it("handles command errors", async () => { - chrome.debugger.attach.mockRejectedValue(new Error("Cannot attach")); - - const mockWs = new MockWebSocket("ws://test"); - const relay = new RelayConnection(mockWs); - relay.setTabId(10); - - await relay._onMessageAsync({ - data: JSON.stringify({ id: 1, method: "attachToTab", params: {} }), - }); - - const response = JSON.parse(mockWs.send.mock.calls[0][0]); - expect(response.id).toBe(1); - expect(response.error).toContain("Cannot attach"); - }); - - it("cleans up on close", () => { - chrome.debugger.detach.mockResolvedValue(undefined); - const mockWs = new MockWebSocket("ws://test"); - const relay = new RelayConnection(mockWs); - relay.setTabId(10); - const onclose = vi.fn(); - relay.onclose = onclose; - - relay.close("test"); - - expect(mockWs.close).toHaveBeenCalledWith(1000, "test"); - expect(chrome.debugger.detach).toHaveBeenCalledWith({ tabId: 10 }); - expect(onclose).toHaveBeenCalled(); - }); -}); - -describe("ensureAttached (recording)", () => { - it("attaches debugger", async () => { - chrome.debugger.attach.mockResolvedValue(undefined); - - await mod.ensureAttached(1); - - expect(chrome.debugger.attach).toHaveBeenCalledWith({ tabId: 1 }, "1.3"); - }); - - it("skips attach if already attached to same tab", async () => { - chrome.debugger.attach.mockResolvedValue(undefined); - - await mod.ensureAttached(1); - chrome.debugger.attach.mockClear(); - - await mod.ensureAttached(1); - expect(chrome.debugger.attach).not.toHaveBeenCalled(); - }); - - it("detaches previous tab before attaching new one", async () => { - chrome.debugger.attach.mockResolvedValue(undefined); - chrome.debugger.detach.mockResolvedValue(undefined); - - await mod.ensureAttached(1); - await mod.ensureAttached(2); - - expect(chrome.debugger.detach).toHaveBeenCalledWith({ tabId: 1 }); - expect(chrome.debugger.attach).toHaveBeenCalledWith({ tabId: 2 }, "1.3"); - }); -}); - -describe("startRecording", () => { - it("returns success when recording starts", async () => { - chrome.debugger.attach.mockResolvedValue(undefined); - chrome.debugger.sendCommand.mockResolvedValue({ identifier: "script-1" }); - - const result = await mod.startRecording(1); - - expect(result.success).toBe(true); - expect(getState().recording[1]).toBe(true); - }); - - it("injects recorder.js via CDP", async () => { - chrome.debugger.attach.mockResolvedValue(undefined); - chrome.debugger.sendCommand.mockResolvedValue({ identifier: "script-1" }); - - await mod.startRecording(1); - - const methods = chrome.debugger.sendCommand.mock.calls.map((c) => c[1]); - expect(methods).toContain("Page.enable"); - expect(methods).toContain("Page.addScriptToEvaluateOnNewDocument"); - expect(methods).toContain("Runtime.evaluate"); - }); - - it("returns error when attach fails", async () => { - chrome.debugger.attach.mockRejectedValue(new Error("Cannot attach")); - - const result = await mod.startRecording(1); - - expect(result.success).toBe(false); - expect(result.error).toContain("Cannot attach"); - }); -}); - -describe("stopRecording", () => { - it("returns success and clears recording state", async () => { - chrome.debugger.attach.mockResolvedValue(undefined); - chrome.debugger.sendCommand.mockResolvedValue(undefined); - - await mod.startRecording(1); - expect(getState().recording[1]).toBe(true); - - const result = await mod.stopRecording(1); - - expect(result.success).toBe(true); - expect(getState().recording[1]).toBe(false); - }); - - it("handles cleanup failure gracefully", async () => { - chrome.debugger.sendCommand.mockRejectedValue( - new Error("Context destroyed") - ); - - const result = await mod.stopRecording(1); - expect(result.success).toBe(true); - }); -}); - -describe("panel port management", () => { - it("registers panel port on connect", () => { - const mockPort = { - name: "pw-panel-42", - onDisconnect: { addListener: vi.fn() }, - }; - - chrome.runtime.onConnect.callListeners(mockPort); - - expect(getState().panelPorts[42]).toBe(mockPort); - }); - - it("removes panel port on disconnect", () => { - const disconnectCallbacks = []; - const mockPort = { - name: "pw-panel-42", - onDisconnect: { - addListener: (cb) => disconnectCallbacks.push(cb), - }, - }; - - chrome.runtime.onConnect.callListeners(mockPort); - expect(getState().panelPorts[42]).toBe(mockPort); - - disconnectCallbacks[0](); - expect(getState().panelPorts[42]).toBeUndefined(); - }); - - it("ignores non-panel ports", () => { - const mockPort = { - name: "other-port", - onDisconnect: { addListener: vi.fn() }, - }; - - chrome.runtime.onConnect.callListeners(mockPort); - expect(Object.keys(getState().panelPorts)).toHaveLength(0); - }); -}); diff --git a/packages/extension/test/devtools.test.js b/packages/extension/test/devtools.test.js deleted file mode 100644 index 861d7a3..0000000 --- a/packages/extension/test/devtools.test.js +++ /dev/null @@ -1,14 +0,0 @@ -import { describe, it, expect } from "vitest"; -import { chrome } from "vitest-chrome/lib/index.esm.js"; - -describe("devtools.js", () => { - it("registers a DevTools panel", async () => { - await import("../devtools.js"); - - expect(chrome.devtools.panels.create).toHaveBeenCalledWith( - "Playwright REPL", - "icons/icon16.png", - "panel/panel.html" - ); - }); -}); diff --git a/packages/extension/test/panel.test.js b/packages/extension/test/panel.test.js index 1159916..d27fcee 100644 --- a/packages/extension/test/panel.test.js +++ b/packages/extension/test/panel.test.js @@ -1,19 +1,10 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; -import { chrome } from "vitest-chrome/lib/index.esm.js"; - -let mockPort; describe("panel.js", () => { beforeEach(() => { vi.restoreAllMocks(); vi.resetModules(); - // Clear chrome event listeners accumulated from re-imports - chrome.runtime.onConnect.clearListeners(); - chrome.runtime.onMessage.clearListeners(); - chrome.runtime.sendMessage.mockReset(); - chrome.runtime.connect.mockReset(); - // Set up the DOM that panel.js expects (split editor/REPL layout) document.body.innerHTML = `
@@ -63,22 +54,14 @@ describe("panel.js", () => { // Remove any theme class from previous test document.body.classList.remove("theme-dark"); - // Mock chrome.devtools.inspectedWindow.tabId - chrome.devtools = { - inspectedWindow: { tabId: 42 }, - panels: { create: vi.fn(), themeName: "default" }, - }; - - // Mock chrome.runtime.connect to return a port-like object - mockPort = { - onMessage: { addListener: vi.fn() }, - postMessage: vi.fn(), - onDisconnect: { addListener: vi.fn() }, - name: "pw-panel-42", - }; - chrome.runtime.id = "mock-extension-id"; - chrome.runtime.connect.mockReturnValue(mockPort); - chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); + // Mock window.matchMedia for theme detection + window.matchMedia = vi.fn().mockReturnValue({ matches: false }); + + // Mock fetch — default to successful response + global.fetch = vi.fn().mockResolvedValue({ + ok: true, + json: () => Promise.resolve({ text: "OK", isError: false }), + }); }); // --- Init --- @@ -87,27 +70,34 @@ describe("panel.js", () => { await import("../panel/panel.js"); const output = document.getElementById("output"); expect(output.textContent).toContain("Playwright REPL v1.0.0"); - expect(output.textContent).toContain("editor"); }); - it("connects to background via port", async () => { + it("performs health check on load", async () => { + await import("../panel/panel.js"); + await vi.waitFor(() => { + expect(global.fetch).toHaveBeenCalledWith( + expect.stringContaining("/health") + ); + }); + }); + + it("shows connected message when health check succeeds", async () => { await import("../panel/panel.js"); - expect(chrome.runtime.connect).toHaveBeenCalledWith({ - name: "pw-panel-42", + await vi.waitFor(() => { + expect(document.getElementById("output").textContent).toContain( + "Connected to server" + ); }); }); - it("reconnects port when service worker restarts", async () => { + it("shows error when health check fails", async () => { + global.fetch = vi.fn().mockRejectedValue(new Error("Connection refused")); await import("../panel/panel.js"); - // Grab the onDisconnect callback that panel.js registered - const disconnectCb = mockPort.onDisconnect.addListener.mock.calls[0][0]; - // Simulate service worker restart (port disconnects) - vi.useFakeTimers(); - disconnectCb(); - vi.advanceTimersByTime(500); - // Should have reconnected - expect(chrome.runtime.connect).toHaveBeenCalledTimes(2); - vi.useRealTimers(); + await vi.waitFor(() => { + expect(document.getElementById("output").textContent).toContain( + "Server not running" + ); + }); }); it("focuses the editor on load", async () => { @@ -129,26 +119,25 @@ describe("panel.js", () => { expect(document.getElementById("open-btn").disabled).toBe(false); }); + it("record button is disabled in side panel mode", async () => { + await import("../panel/panel.js"); + expect(document.getElementById("record-btn").disabled).toBe(true); + }); + // --- Theme --- - it("defaults to light theme (no theme-dark class)", async () => { - chrome.devtools.panels.themeName = "default"; + it("defaults to light theme", async () => { + window.matchMedia = vi.fn().mockReturnValue({ matches: false }); await import("../panel/panel.js"); expect(document.body.classList.contains("theme-dark")).toBe(false); }); - it("applies dark theme when DevTools theme is dark", async () => { - chrome.devtools.panels.themeName = "dark"; + it("applies dark theme when prefers-color-scheme: dark", async () => { + window.matchMedia = vi.fn().mockReturnValue({ matches: true }); await import("../panel/panel.js"); expect(document.body.classList.contains("theme-dark")).toBe(true); }); - it("applies light theme when themeName is undefined", async () => { - chrome.devtools.panels.themeName = undefined; - await import("../panel/panel.js"); - expect(document.body.classList.contains("theme-dark")).toBe(false); - }); - // --- Line numbers --- it("renders line numbers for editor content", async () => { @@ -175,17 +164,21 @@ describe("panel.js", () => { // --- REPL input --- - it("sends command to background on Enter key", async () => { + it("sends command via fetch on Enter key", async () => { await import("../panel/panel.js"); const input = document.getElementById("command-input"); - input.value = "help"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + input.value = "click e5"; + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); await vi.waitFor(() => { - expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ - type: "pw-command", - raw: "help", - tabId: 42, - }); + expect(global.fetch).toHaveBeenCalledWith( + expect.stringContaining("/run"), + expect.objectContaining({ + method: "POST", + body: JSON.stringify({ raw: "click e5" }), + }) + ); }); }); @@ -193,142 +186,141 @@ describe("panel.js", () => { await import("../panel/panel.js"); const input = document.getElementById("command-input"); input.value = "snapshot"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); expect(input.value).toBe(""); }); it("does not send empty commands", async () => { await import("../panel/panel.js"); + // Clear the health check fetch call + global.fetch.mockClear(); const input = document.getElementById("command-input"); input.value = " "; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - expect(chrome.runtime.sendMessage).not.toHaveBeenCalled(); + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); + expect(global.fetch).not.toHaveBeenCalledWith( + expect.stringContaining("/run"), + expect.anything() + ); }); - // --- Response display (legacy format) --- + // --- Response display --- it("displays success response in output", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "Navigated to https://example.com" }); + global.fetch = vi.fn().mockResolvedValue({ + ok: true, + json: () => Promise.resolve({ text: "Navigated", isError: false }), + }); await import("../panel/panel.js"); const input = document.getElementById("command-input"); input.value = "goto https://example.com"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); await vi.waitFor(() => { - const output = document.getElementById("output"); - expect(output.textContent).toContain("Navigated to https://example.com"); + expect(document.getElementById("output").textContent).toContain( + "Navigated" + ); }); }); it("displays error response in output", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "error", data: "Element not found" }); + global.fetch = vi.fn().mockResolvedValue({ + ok: true, + json: () => + Promise.resolve({ text: "Element not found", isError: true }), + }); await import("../panel/panel.js"); const input = document.getElementById("command-input"); input.value = 'click "Missing"'; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); await vi.waitFor(() => { - const output = document.getElementById("output"); - expect(output.textContent).toContain("Element not found"); + expect(document.getElementById("output").textContent).toContain( + "Element not found" + ); }); }); it("displays snapshot lines in output", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "snapshot", data: '- button "OK" [ref=e1]\n- link "Home" [ref=e2]' }); + global.fetch = vi.fn().mockResolvedValue({ + ok: true, + json: () => + Promise.resolve({ + text: '- button "OK" [ref=e1]\n- link "Home" [ref=e2]', + isError: false, + }), + }); await import("../panel/panel.js"); const input = document.getElementById("command-input"); input.value = "snapshot"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); await vi.waitFor(() => { - const output = document.getElementById("output"); - expect(output.textContent).toContain("button"); - expect(output.textContent).toContain("link"); + expect(document.getElementById("output").textContent).toContain( + "button" + ); + expect(document.getElementById("output").textContent).toContain("link"); }); }); it("displays screenshot as image in output", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "screenshot", data: "fakebase64" }); + global.fetch = vi.fn().mockResolvedValue({ + ok: true, + json: () => + Promise.resolve({ + text: "data:image/png;base64,fakebase64", + isError: false, + }), + }); await import("../panel/panel.js"); const input = document.getElementById("command-input"); input.value = "screenshot"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); await vi.waitFor(() => { - const img = document.querySelector("img"); + const img = document.querySelector("img:not(#lightbox-img)"); expect(img).not.toBeNull(); expect(img.src).toContain("fakebase64"); }); }); - it("displays info response in output", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "info", data: "Available commands:" }); - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - input.value = "help"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - await vi.waitFor(() => { - const output = document.getElementById("output"); - expect(output.textContent).toContain("Available commands:"); - }); - }); - - // --- Engine format: { text, isError } --- - - it("displays Engine success result in output", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ text: "Clicked", isError: false }); - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - input.value = 'click "OK"'; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - await vi.waitFor(() => { - const output = document.getElementById("output"); - expect(output.textContent).toContain("Clicked"); - }); - }); - - it("displays Engine error result in output", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ text: "Element not found", isError: true }); - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - input.value = 'click "Missing"'; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - await vi.waitFor(() => { - const output = document.getElementById("output"); - expect(output.textContent).toContain("Element not found"); - }); - }); - - // --- Error handling --- - - it("handles null response from background", async () => { - chrome.runtime.sendMessage.mockResolvedValue(null); - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - input.value = "snapshot"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - await vi.waitFor(() => { - const output = document.getElementById("output"); - expect(output.textContent).toContain("No response"); - }); - }); - - it("handles sendMessage rejection", async () => { - chrome.runtime.sendMessage.mockRejectedValue(new Error("Disconnected")); + it("shows server not running on fetch failure", async () => { + global.fetch = vi.fn().mockRejectedValue(new Error("Connection refused")); await import("../panel/panel.js"); const input = document.getElementById("command-input"); input.value = "snapshot"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); await vi.waitFor(() => { - const output = document.getElementById("output"); - expect(output.textContent).toContain("Error: Disconnected"); + expect(document.getElementById("output").textContent).toContain( + "Not connected to server" + ); }); }); - it("displays comments without sending to background", async () => { + it("displays comments without sending to server", async () => { await import("../panel/panel.js"); + global.fetch.mockClear(); const input = document.getElementById("command-input"); input.value = "# this is a comment"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - const output = document.getElementById("output"); - expect(output.textContent).toContain("# this is a comment"); - expect(chrome.runtime.sendMessage).not.toHaveBeenCalled(); + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); + expect(document.getElementById("output").textContent).toContain( + "# this is a comment" + ); + expect(global.fetch).not.toHaveBeenCalledWith( + expect.stringContaining("/run"), + expect.anything() + ); }); // --- History --- @@ -338,24 +330,36 @@ describe("panel.js", () => { const input = document.getElementById("command-input"); input.value = "help"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); input.value = "snapshot"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); - input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true })); + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true }) + ); expect(input.value).toBe("snapshot"); - input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true })); + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true }) + ); expect(input.value).toBe("help"); - input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })); + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }) + ); expect(input.value).toBe("snapshot"); - input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })); + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }) + ); expect(input.value).toBe(""); }); - // --- Copy/Save/Export tied to editor --- + // --- Copy/Save/Export --- it("enables copy, save, export when editor has content", async () => { await import("../panel/panel.js"); @@ -368,27 +372,11 @@ describe("panel.js", () => { expect(document.getElementById("export-btn").disabled).toBe(false); }); - it("disables copy, save, export when editor is empty", async () => { - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "goto https://example.com"; - editor.dispatchEvent(new Event("input")); - expect(document.getElementById("copy-btn").disabled).toBe(false); - - editor.value = ""; - editor.dispatchEvent(new Event("input")); - expect(document.getElementById("copy-btn").disabled).toBe(true); - expect(document.getElementById("save-btn").disabled).toBe(true); - expect(document.getElementById("export-btn").disabled).toBe(true); - }); - - // --- Copy --- - it("copy button copies editor content to clipboard", async () => { document.execCommand = vi.fn().mockReturnValue(true); await import("../panel/panel.js"); const editor = document.getElementById("editor"); - editor.value = "goto https://example.com\nclick \"OK\""; + editor.value = 'goto https://example.com\nclick "OK"'; editor.dispatchEvent(new Event("input")); document.getElementById("copy-btn").click(); @@ -396,20 +384,11 @@ describe("panel.js", () => { expect(document.getElementById("output").textContent).toContain("copied"); }); - it("copy button shows message when editor is empty", async () => { - await import("../panel/panel.js"); - document.getElementById("copy-btn").disabled = false; - document.getElementById("copy-btn").click(); - expect(document.getElementById("output").textContent).toContain("Nothing to copy"); - }); - - // --- Export --- - it("export button converts editor to Playwright code", async () => { await import("../panel/panel.js"); document.execCommand = vi.fn().mockReturnValue(true); const editor = document.getElementById("editor"); - editor.value = "goto https://example.com\nclick \"Submit\""; + editor.value = 'goto https://example.com\nclick "Submit"'; editor.dispatchEvent(new Event("input")); document.getElementById("export-btn").click(); @@ -417,142 +396,121 @@ describe("panel.js", () => { const codeBlock = output.querySelector(".code-block"); expect(codeBlock).not.toBeNull(); expect(codeBlock.textContent).toContain("@playwright/test"); - expect(codeBlock.querySelector(".code-copy-btn")).not.toBeNull(); - }); - - it("export command in REPL reads from editor", async () => { - await import("../panel/panel.js"); - document.execCommand = vi.fn().mockReturnValue(true); - const editor = document.getElementById("editor"); - editor.value = "goto https://example.com"; - editor.dispatchEvent(new Event("input")); - - const input = document.getElementById("command-input"); - input.value = "export"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - const output = document.getElementById("output"); - const codeBlock = output.querySelector(".code-block"); - expect(codeBlock).not.toBeNull(); - expect(codeBlock.textContent).toContain("@playwright/test"); }); - it("export shows nothing when editor is empty", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - input.value = "export"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - const output = document.getElementById("output"); - expect(output.textContent).toContain("Nothing to export"); - }); + // --- Console commands (history, clear, reset) --- - it("export single command converts to Playwright", async () => { + it("history command displays history in terminal", async () => { await import("../panel/panel.js"); const input = document.getElementById("command-input"); - input.value = 'export click "Submit"'; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - const output = document.getElementById("output"); - expect(output.textContent).toContain("click"); - }); - // --- Recording --- - - it("record button toggles recording state", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ success: true }); - await import("../panel/panel.js"); - const recordBtn = document.getElementById("record-btn"); + input.value = "help"; + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); + input.value = "snapshot"; + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); - recordBtn.click(); await vi.waitFor(() => { - expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ - type: "pw-record-start", - tabId: 42, - }); + // Wait for the fetch calls to complete + expect(global.fetch).toHaveBeenCalledWith( + expect.stringContaining("/run"), + expect.anything() + ); }); - expect(recordBtn.classList.contains("recording")).toBe(true); - expect(recordBtn.textContent).toContain("Stop"); + + input.value = "history"; + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); + + const output = document.getElementById("output"); + expect(output.textContent).toContain("help"); + expect(output.textContent).toContain("snapshot"); }); - it("record button stops recording on second click", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ success: true }); + it("clear command clears console output", async () => { await import("../panel/panel.js"); - const recordBtn = document.getElementById("record-btn"); + const input = document.getElementById("command-input"); - recordBtn.click(); - await vi.waitFor(() => { - expect(recordBtn.classList.contains("recording")).toBe(true); - }); + input.value = "clear"; + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); - recordBtn.click(); - await vi.waitFor(() => { - expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ - type: "pw-record-stop", - tabId: 42, - }); - }); - expect(recordBtn.classList.contains("recording")).toBe(false); - expect(recordBtn.textContent).toContain("Record"); + expect(document.getElementById("output").innerHTML).toBe(""); }); - it("record button reverts on failure", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ success: false, error: "Failed" }); + it("reset command clears history and console", async () => { await import("../panel/panel.js"); - const recordBtn = document.getElementById("record-btn"); + const input = document.getElementById("command-input"); - recordBtn.click(); - await vi.waitFor(() => { - expect(recordBtn.classList.contains("recording")).toBe(false); - expect(recordBtn.textContent).toContain("Record"); - }); - expect(document.getElementById("output").textContent).toContain("Failed to start recording"); - }); + input.value = "help"; + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); - it("recorded commands append to editor", async () => { - await import("../panel/panel.js"); - const onMessageCallback = mockPort.onMessage.addListener.mock.calls[0][0]; - onMessageCallback({ type: "pw-recorded-command", command: 'click "Submit"' }); - const editor = document.getElementById("editor"); - expect(editor.value).toContain('click "Submit"'); - expect(document.getElementById("copy-btn").disabled).toBe(false); + input.value = "reset"; + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); + + expect(document.getElementById("output").textContent).toContain( + "History and terminal cleared" + ); + + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true }) + ); + expect(input.value).toBe(""); }); // --- Run button --- - it("run button executes editor lines", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); + it("run button executes editor lines via fetch", async () => { await import("../panel/panel.js"); const editor = document.getElementById("editor"); - editor.value = "goto https://example.com\nclick \"OK\""; + editor.value = 'goto https://example.com\nclick "OK"'; editor.dispatchEvent(new Event("input")); document.getElementById("run-btn").click(); await vi.waitFor(() => { - const output = document.getElementById("output"); - expect(output.textContent).toContain("Running script..."); - expect(output.textContent).toContain("Run complete."); - }); - - expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ - type: "pw-command", - raw: "goto https://example.com", - tabId: 42, - }); - expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ - type: "pw-command", - raw: 'click "OK"', - tabId: 42, + expect(document.getElementById("output").textContent).toContain( + "Running script..." + ); + expect(document.getElementById("output").textContent).toContain( + "Run complete." + ); }); }); it("run button shows pass/fail stats", async () => { let callCount = 0; - chrome.runtime.sendMessage.mockImplementation(() => { - callCount++; - if (callCount === 1) return Promise.resolve({ type: "success", data: "OK" }); - return Promise.resolve({ type: "error", data: "Not found" }); + global.fetch = vi.fn().mockImplementation((url) => { + if (url.includes("/run")) { + callCount++; + if (callCount === 1) { + return Promise.resolve({ + ok: true, + json: () => Promise.resolve({ text: "OK", isError: false }), + }); + } + return Promise.resolve({ + ok: true, + json: () => + Promise.resolve({ text: "Not found", isError: true }), + }); + } + return Promise.resolve({ + ok: true, + json: () => Promise.resolve({ status: "ok" }), + }); }); await import("../panel/panel.js"); const editor = document.getElementById("editor"); - editor.value = "goto https://example.com\nclick \"Missing\""; + editor.value = 'goto https://example.com\nclick "Missing"'; editor.dispatchEvent(new Event("input")); document.getElementById("run-btn").click(); @@ -566,868 +524,112 @@ describe("panel.js", () => { it("run button shows message for empty editor", async () => { await import("../panel/panel.js"); document.getElementById("run-btn").click(); - const output = document.getElementById("output"); - expect(output.textContent).toContain("Editor is empty"); - }); - - it("run button skips empty lines and comments", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "# comment\n\ngoto https://example.com"; - editor.dispatchEvent(new Event("input")); - - document.getElementById("run-btn").click(); - await vi.waitFor(() => { - expect(document.getElementById("output").textContent).toContain("Run complete."); - }); - const pwCalls = chrome.runtime.sendMessage.mock.calls.filter( - (c) => c[0].type === "pw-command" + expect(document.getElementById("output").textContent).toContain( + "Editor is empty" ); - expect(pwCalls.length).toBe(1); - expect(pwCalls[0][0].raw).toBe("goto https://example.com"); }); // --- Ctrl+Enter --- it("Ctrl+Enter in editor triggers run", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); await import("../panel/panel.js"); const editor = document.getElementById("editor"); editor.value = "goto https://example.com"; editor.dispatchEvent(new Event("input")); - editor.dispatchEvent(new KeyboardEvent("keydown", { - key: "Enter", - ctrlKey: true, - bubbles: true, - })); + editor.dispatchEvent( + new KeyboardEvent("keydown", { + key: "Enter", + ctrlKey: true, + bubbles: true, + }) + ); await vi.waitFor(() => { - expect(document.getElementById("output").textContent).toContain("Running script..."); + expect(document.getElementById("output").textContent).toContain( + "Running script..." + ); }); }); - // --- Console commands (history, clear, reset) --- + // --- Step button --- - it("history command displays history in terminal", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); + it("step button executes the first executable line", async () => { await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - - input.value = "help"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - input.value = "snapshot"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + const editor = document.getElementById("editor"); + editor.value = 'goto https://example.com\nclick "OK"'; + editor.dispatchEvent(new Event("input")); + document.getElementById("step-btn").click(); await vi.waitFor(() => { - expect(chrome.runtime.sendMessage).toHaveBeenCalledTimes(2); + expect(global.fetch).toHaveBeenCalledWith( + expect.stringContaining("/run"), + expect.objectContaining({ + body: JSON.stringify({ raw: "goto https://example.com" }), + }) + ); }); - - input.value = "history"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - - const output = document.getElementById("output"); - expect(output.textContent).toContain("help"); - expect(output.textContent).toContain("snapshot"); - expect(document.getElementById("editor").value).toBe(""); }); - it("history command shows info when history is empty", async () => { + it("step button shows message for empty editor", async () => { await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - - input.value = "history"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - - expect(document.getElementById("output").textContent).toContain("No command history"); + document.getElementById("step-btn").click(); + expect(document.getElementById("output").textContent).toContain( + "Editor is empty" + ); }); - it("history command is not added to history itself", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); + // --- Autocomplete --- + + it("ghost text shows completion hint while typing", async () => { await import("../panel/panel.js"); const input = document.getElementById("command-input"); + const ghost = document.getElementById("ghost-text"); - input.value = "help"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - - input.value = "history"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - - input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true })); - expect(input.value).toBe("help"); + input.value = "go"; + input.dispatchEvent(new Event("input", { bubbles: true })); + expect(ghost.textContent).toBe("to"); }); - it("history command is not sent to background", async () => { + it("Tab completes single matching command", async () => { await import("../panel/panel.js"); const input = document.getElementById("command-input"); - input.value = "history"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - - expect(chrome.runtime.sendMessage).not.toHaveBeenCalled(); + input.value = "scr"; + input.dispatchEvent(new Event("input", { bubbles: true })); + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Tab", bubbles: true }) + ); + expect(input.value).toBe("screenshot "); }); - it("clear command clears console output", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "Done" }); + it("dropdown shows for multiple matches", async () => { await import("../panel/panel.js"); const input = document.getElementById("command-input"); + const dd = document.getElementById("autocomplete-dropdown"); - input.value = "help"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - await vi.waitFor(() => { - expect(document.getElementById("output").textContent).toContain("Done"); - }); - - input.value = "clear"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - - expect(document.getElementById("output").innerHTML).toBe(""); + input.value = "go"; + input.dispatchEvent(new Event("input", { bubbles: true })); + expect(dd.hidden).toBe(false); + expect(dd.querySelectorAll(".autocomplete-item").length).toBeGreaterThan(1); }); - it("clear command is not sent to background", async () => { + it("Escape closes dropdown", async () => { await import("../panel/panel.js"); - chrome.runtime.sendMessage.mockClear(); const input = document.getElementById("command-input"); - - input.value = "clear"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - - expect(chrome.runtime.sendMessage).not.toHaveBeenCalled(); - }); - - it("clear command is not added to history", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - - input.value = "help"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - - input.value = "clear"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - - input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true })); - expect(input.value).toBe("help"); - }); - - it("reset command clears history and console", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "Done" }); - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - - input.value = "help"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - await vi.waitFor(() => { - expect(document.getElementById("output").textContent).toContain("Done"); - }); - - input.value = "reset"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - - expect(document.getElementById("output").textContent).toContain("History and terminal cleared"); - - input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true })); - expect(input.value).toBe(""); - }); - - it("reset command is not added to history", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - - input.value = "help"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - - input.value = "reset"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - - input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true })); - expect(input.value).toBe(""); - }); - - // --- Console header clear button --- - - it("console header clear button clears output", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "Done" }); - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - input.value = "help"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - await vi.waitFor(() => { - expect(document.getElementById("output").textContent).toContain("Done"); - }); - - document.getElementById("console-clear-btn").click(); - expect(document.getElementById("output").innerHTML).toBe(""); - }); - - it("console header clear button resets pass/fail stats", async () => { - let callCount = 0; - chrome.runtime.sendMessage.mockImplementation(() => { - callCount++; - if (callCount === 1) return Promise.resolve({ type: "success", data: "OK" }); - return Promise.resolve({ type: "error", data: "Not found" }); - }); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "goto https://example.com\nclick \"Missing\""; - editor.dispatchEvent(new Event("input")); - - document.getElementById("run-btn").click(); - await vi.waitFor(() => { - const stats = document.getElementById("console-stats"); - expect(stats.textContent).toContain("1 passed"); - }); - - document.getElementById("console-clear-btn").click(); - expect(document.getElementById("console-stats").textContent).toBe(""); - }); - - // --- Step button --- - - it("step button executes the first executable line", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "goto https://example.com\nclick \"OK\""; - editor.dispatchEvent(new Event("input")); - - document.getElementById("step-btn").click(); - await vi.waitFor(() => { - expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ - type: "pw-command", - raw: "goto https://example.com", - tabId: 42, - }); - }); - }); - - it("step button skips empty lines and comments", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "# comment\n\ngoto https://example.com"; - editor.dispatchEvent(new Event("input")); - - document.getElementById("step-btn").click(); - await vi.waitFor(() => { - expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ - type: "pw-command", - raw: "goto https://example.com", - tabId: 42, - }); - }); - }); - - it("step button advances to next line on subsequent clicks", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "goto https://example.com\nclick \"OK\""; - editor.dispatchEvent(new Event("input")); - - document.getElementById("step-btn").click(); - await vi.waitFor(() => { - expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ - type: "pw-command", - raw: "goto https://example.com", - tabId: 42, - }); - }); - - await vi.waitFor(() => { - expect(document.getElementById("step-btn").disabled).toBe(false); - }); - - chrome.runtime.sendMessage.mockClear(); - document.getElementById("step-btn").click(); - await vi.waitFor(() => { - expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ - type: "pw-command", - raw: 'click "OK"', - tabId: 42, - }); - }); - }); - - it("step button shows message for empty editor", async () => { - await import("../panel/panel.js"); - document.getElementById("step-btn").click(); - expect(document.getElementById("output").textContent).toContain("Editor is empty"); - }); - - it("step button shows complete message after last line", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "goto https://example.com"; - editor.dispatchEvent(new Event("input")); - - document.getElementById("step-btn").click(); - await vi.waitFor(() => { - expect(document.getElementById("output").textContent).toContain("Step complete"); - }); - }); - - it("step state resets when editor content changes", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "goto https://example.com\nclick \"OK\""; - editor.dispatchEvent(new Event("input")); - - document.getElementById("step-btn").click(); - await vi.waitFor(() => { - expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ - type: "pw-command", - raw: "goto https://example.com", - tabId: 42, - }); - }); - - await vi.waitFor(() => { - expect(document.getElementById("step-btn").disabled).toBe(false); - }); - - editor.value = "goto https://other.com"; - editor.dispatchEvent(new Event("input")); - - chrome.runtime.sendMessage.mockClear(); - document.getElementById("step-btn").click(); - await vi.waitFor(() => { - expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ - type: "pw-command", - raw: "goto https://other.com", - tabId: 42, - }); - }); - }); - - // --- Autocomplete --- - - it("ghost text shows completion hint while typing", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - const ghost = document.getElementById("ghost-text"); - - input.value = "go"; - input.dispatchEvent(new Event("input", { bubbles: true })); - expect(ghost.textContent).toBe("to"); - }); - - it("ghost text shows hint for screenshot", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - const ghost = document.getElementById("ghost-text"); - - input.value = "scr"; - input.dispatchEvent(new Event("input", { bubbles: true })); - expect(ghost.textContent).toBe("eenshot"); - }); - - it("ghost text clears when full command is typed", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - const ghost = document.getElementById("ghost-text"); - - input.value = "goto"; - input.dispatchEvent(new Event("input", { bubbles: true })); - expect(ghost.textContent).toBe(""); - }); - - it("ghost text clears when space is typed after command", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - const ghost = document.getElementById("ghost-text"); - - input.value = "goto "; - input.dispatchEvent(new Event("input", { bubbles: true })); - expect(ghost.textContent).toBe(""); - }); - - it("ghost text clears on empty input", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - const ghost = document.getElementById("ghost-text"); - - input.value = ""; - input.dispatchEvent(new Event("input", { bubbles: true })); - expect(ghost.textContent).toBe(""); - }); - - it("Tab completes single matching command", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - - input.value = "scr"; - input.dispatchEvent(new Event("input", { bubbles: true })); - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true })); - expect(input.value).toBe("screenshot "); - }); - - it("dropdown shows for multiple matches", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - const dd = document.getElementById("autocomplete-dropdown"); - - input.value = "go"; - input.dispatchEvent(new Event("input", { bubbles: true })); - - expect(dd.hidden).toBe(false); - expect(dd.querySelectorAll(".autocomplete-item").length).toBeGreaterThan(1); - }); - - it("Tab selects first dropdown item when dropdown is open", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - const dd = document.getElementById("autocomplete-dropdown"); - - input.value = "go"; - input.dispatchEvent(new Event("input", { bubbles: true })); - expect(dd.hidden).toBe(false); - - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true })); - expect(input.value.startsWith("go")).toBe(true); - expect(input.value.endsWith(" ")).toBe(true); - expect(dd.hidden).toBe(true); - }); - - it("ArrowDown navigates dropdown items", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - const dd = document.getElementById("autocomplete-dropdown"); - - input.value = "go"; - input.dispatchEvent(new Event("input", { bubbles: true })); - expect(dd.hidden).toBe(false); - - input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })); - const items = dd.querySelectorAll(".autocomplete-item"); - expect(items[0].classList.contains("active")).toBe(true); - }); - - it("Enter selects highlighted dropdown item", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - const dd = document.getElementById("autocomplete-dropdown"); - - input.value = "go"; - input.dispatchEvent(new Event("input", { bubbles: true })); - - input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })); - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - expect(input.value.startsWith("go")).toBe(true); - expect(input.value.endsWith(" ")).toBe(true); - expect(dd.hidden).toBe(true); - }); - - it("Escape closes dropdown", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - const dd = document.getElementById("autocomplete-dropdown"); - - input.value = "go"; - input.dispatchEvent(new Event("input", { bubbles: true })); - expect(dd.hidden).toBe(false); - - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); - expect(dd.hidden).toBe(true); - }); - - it("dropdown hides when single match remains", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - const dd = document.getElementById("autocomplete-dropdown"); - - input.value = "scr"; - input.dispatchEvent(new Event("input", { bubbles: true })); - expect(dd.hidden).toBe(true); - }); - - it("clicking dropdown item selects it", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - const dd = document.getElementById("autocomplete-dropdown"); - - input.value = "go"; - input.dispatchEvent(new Event("input", { bubbles: true })); - expect(dd.hidden).toBe(false); - - const firstItem = dd.querySelector(".autocomplete-item"); - firstItem.dispatchEvent(new Event("mousedown", { bubbles: true })); - expect(input.value.endsWith(" ")).toBe(true); - expect(dd.hidden).toBe(true); - }); - - it("Enter clears ghost text", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - const ghost = document.getElementById("ghost-text"); - - input.value = "go"; - input.dispatchEvent(new Event("input", { bubbles: true })); - expect(ghost.textContent).not.toBe(""); - - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - expect(ghost.textContent).toBe(""); - }); - - it("ArrowUp clears ghost text when no dropdown", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - const ghost = document.getElementById("ghost-text"); - - input.value = "scr"; - input.dispatchEvent(new Event("input", { bubbles: true })); - expect(ghost.textContent).not.toBe(""); - - input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true })); - expect(ghost.textContent).toBe(""); - }); - - it("ArrowDown clears ghost text when no dropdown", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - const ghost = document.getElementById("ghost-text"); - - input.value = "scr"; - input.dispatchEvent(new Event("input", { bubbles: true })); - expect(ghost.textContent).not.toBe(""); - - input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })); - expect(ghost.textContent).toBe(""); - }); - - // ─── Engine format (executeCommand & executeCommandForRun) ──────────────── - - it("REPL handles Engine format screenshot response", async () => { - const fakeData = "data:image/png;base64,AAAA"; - chrome.runtime.sendMessage.mockResolvedValue({ text: fakeData, isError: false }); - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - - input.value = "screenshot"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - - await vi.waitFor(() => { - expect(document.querySelector(".screenshot-block")).toBeTruthy(); - }); - }); - - it("REPL handles Engine format snapshot response", async () => { - const snap = "- heading [ref=e1]\n- button [ref=e2]"; - chrome.runtime.sendMessage.mockResolvedValue({ text: snap, isError: false }); - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - - input.value = "snapshot"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - - await vi.waitFor(() => { - expect(document.querySelectorAll(".line-snapshot").length).toBeGreaterThanOrEqual(1); - }); - }); - - it("REPL handles null response from background", async () => { - chrome.runtime.sendMessage.mockResolvedValue(null); - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - - input.value = "goto https://example.com"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - - await vi.waitFor(() => { - expect(document.getElementById("output").textContent).toContain("No response"); - }); - }); - - it("REPL handles legacy default type response", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "other", data: "Some data" }); - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - - input.value = "help"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - - await vi.waitFor(() => { - expect(document.getElementById("output").textContent).toContain("Some data"); - }); - }); - - it("REPL export command shows conversion for unknown commands", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - - input.value = "export totally-invalid-command"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - - await vi.waitFor(() => { - expect(document.getElementById("output").textContent).toContain("unknown command"); - }); - }); - - // ─── Engine format in executeCommandForRun ──────────────────────────────── - - it("run button handles Engine format error in run mode", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ text: "Element not found", isError: true }); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = 'click "missing"'; - editor.dispatchEvent(new Event("input")); - - document.getElementById("run-btn").click(); - await vi.waitFor(() => { - const stats = document.getElementById("console-stats"); - expect(stats.textContent).toContain("1 failed"); - }); - }); - - it("run button handles Engine format screenshot in run mode", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ - text: "data:image/png;base64,AAAA", - isError: false, - }); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "screenshot"; - editor.dispatchEvent(new Event("input")); - - document.getElementById("run-btn").click(); - await vi.waitFor(() => { - expect(document.querySelector(".screenshot-block")).toBeTruthy(); - }); - }); - - it("run button handles Engine format snapshot in run mode", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ - text: "- heading [ref=e1]\n- button [ref=e2]", - isError: false, - }); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "snapshot"; - editor.dispatchEvent(new Event("input")); - - document.getElementById("run-btn").click(); - await vi.waitFor(() => { - expect(document.querySelectorAll(".line-snapshot").length).toBeGreaterThanOrEqual(1); - }); - }); - - it("run button handles null result in run mode", async () => { - chrome.runtime.sendMessage.mockResolvedValue(null); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "goto https://example.com"; - editor.dispatchEvent(new Event("input")); - - document.getElementById("run-btn").click(); - await vi.waitFor(() => { - expect(document.getElementById("output").textContent).toContain("No response"); - }); - }); - - it("run button handles legacy info type in run mode", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "info", data: "Page loaded" }); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "goto https://example.com"; - editor.dispatchEvent(new Event("input")); - - document.getElementById("run-btn").click(); - await vi.waitFor(() => { - expect(document.getElementById("output").textContent).toContain("Page loaded"); - }); - }); - - it("run button handles legacy snapshot type in run mode", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ - type: "snapshot", - data: "- heading [ref=e1]\n- button [ref=e2]", - }); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "snapshot"; - editor.dispatchEvent(new Event("input")); - - document.getElementById("run-btn").click(); - await vi.waitFor(() => { - expect(document.querySelectorAll(".line-snapshot").length).toBeGreaterThanOrEqual(1); - }); - }); - - it("run button handles legacy screenshot type in run mode", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ - type: "screenshot", - data: "AAAA", - }); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "screenshot"; - editor.dispatchEvent(new Event("input")); - - document.getElementById("run-btn").click(); - await vi.waitFor(() => { - expect(document.querySelector(".screenshot-block")).toBeTruthy(); - }); - }); - - it("run button handles legacy default type in run mode", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "other", data: "OK done" }); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "goto https://example.com"; - editor.dispatchEvent(new Event("input")); - - document.getElementById("run-btn").click(); - await vi.waitFor(() => { - expect(document.getElementById("output").textContent).toContain("OK done"); - }); - }); - - it("run button handles sendMessage exception in run mode", async () => { - chrome.runtime.sendMessage.mockRejectedValue(new Error("Connection lost")); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "goto https://example.com"; - editor.dispatchEvent(new Event("input")); - - document.getElementById("run-btn").click(); - await vi.waitFor(() => { - expect(document.getElementById("output").textContent).toContain("Connection lost"); - }); - }); - - // ─── Run button stop ───────────────────────────────────────────────────── - - it("run button can be stopped while running", async () => { - let resolveFirst; - chrome.runtime.sendMessage.mockImplementation( - () => new Promise((r) => { resolveFirst = r; }) - ); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "goto https://example.com\nclick \"OK\""; - editor.dispatchEvent(new Event("input")); - - const runBtn = document.getElementById("run-btn"); - runBtn.click(); - - // Wait for isRunning to be true (button changes text) - await vi.waitFor(() => { - expect(runBtn.textContent).toContain("\u25A0"); // stop symbol - }); - - // Click stop - runBtn.click(); - await vi.waitFor(() => { - expect(document.getElementById("output").textContent).toContain("Run stopped"); - }); - - // Resolve the pending command - resolveFirst({ type: "success", data: "Done" }); - }); - - // ─── Tab on empty input ─────────────────────────────────────────────────── - - it("Tab on empty input shows all commands", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - const dd = document.getElementById("autocomplete-dropdown"); - - input.value = ""; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true })); - expect(dd.hidden).toBe(false); - expect(dd.querySelectorAll(".autocomplete-item").length).toBeGreaterThan(5); - }); - - it("Tab with multiple matches shows dropdown", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - const dd = document.getElementById("autocomplete-dropdown"); - - input.value = "go"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true })); - expect(dd.hidden).toBe(false); - }); - - // ─── Ctrl+Space autocomplete ────────────────────────────────────────────── - - it("Ctrl+Space shows all commands when input is empty", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - const dd = document.getElementById("autocomplete-dropdown"); - - input.value = ""; - input.dispatchEvent( - new KeyboardEvent("keydown", { key: " ", ctrlKey: true, bubbles: true }) - ); - expect(dd.hidden).toBe(false); - expect(dd.querySelectorAll(".autocomplete-item").length).toBeGreaterThan(5); - }); - - it("Ctrl+Space shows filtered commands when typing", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - const dd = document.getElementById("autocomplete-dropdown"); + const dd = document.getElementById("autocomplete-dropdown"); input.value = "go"; - input.dispatchEvent( - new KeyboardEvent("keydown", { key: " ", ctrlKey: true, bubbles: true }) - ); + input.dispatchEvent(new Event("input", { bubbles: true })); expect(dd.hidden).toBe(false); - expect(dd.querySelectorAll(".autocomplete-item").length).toBeGreaterThanOrEqual(1); - }); - - it("Ctrl+Space does nothing when input has space", async () => { - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - const dd = document.getElementById("autocomplete-dropdown"); - input.value = "goto https://example.com"; input.dispatchEvent( - new KeyboardEvent("keydown", { key: " ", ctrlKey: true, bubbles: true }) + new KeyboardEvent("keydown", { key: "Escape", bubbles: true }) ); expect(dd.hidden).toBe(true); }); - // ─── Screenshot & lightbox interactions ─────────────────────────────────── - - it("screenshot image click opens lightbox", async () => { - const fakeData = "data:image/png;base64,AAAA"; - chrome.runtime.sendMessage.mockResolvedValue({ text: fakeData, isError: false }); - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - - input.value = "screenshot"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - - await vi.waitFor(() => { - expect(document.querySelector(".screenshot-block img")).toBeTruthy(); - }); - - document.querySelector(".screenshot-block img").click(); - expect(document.getElementById("lightbox").hidden).toBe(false); - expect(document.getElementById("lightbox-img").src).toContain("AAAA"); - }); - - it("screenshot save button triggers download", async () => { - const fakeData = "data:image/png;base64,AAAA"; - chrome.runtime.sendMessage.mockResolvedValue({ text: fakeData, isError: false }); - await import("../panel/panel.js"); - const input = document.getElementById("command-input"); - - input.value = "screenshot"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - - await vi.waitFor(() => { - expect(document.querySelector(".screenshot-btn")).toBeTruthy(); - }); - - // Click save button — just verify no error is thrown - document.querySelector(".screenshot-btn").click(); - }); + // --- Lightbox --- it("lightbox closes when clicking backdrop", async () => { await import("../panel/panel.js"); @@ -1438,17 +640,6 @@ describe("panel.js", () => { expect(lightbox.hidden).toBe(true); }); - it("lightbox does not close when clicking image", async () => { - await import("../panel/panel.js"); - const lightbox = document.getElementById("lightbox"); - const img = document.getElementById("lightbox-img"); - lightbox.hidden = false; - - img.dispatchEvent(new MouseEvent("click", { bubbles: true })); - // Should not close because target is img, not lightbox - expect(lightbox.hidden).toBe(false); - }); - it("lightbox close button works", async () => { await import("../panel/panel.js"); const lightbox = document.getElementById("lightbox"); @@ -1458,48 +649,37 @@ describe("panel.js", () => { expect(lightbox.hidden).toBe(true); }); - it("lightbox save button triggers download", async () => { - await import("../panel/panel.js"); - const lightbox = document.getElementById("lightbox"); - const lightboxImg = document.getElementById("lightbox-img"); - lightbox.hidden = false; - lightboxImg.src = "data:image/png;base64,AAAA"; - - document.getElementById("lightbox-save-btn").click(); - // Just verify no error thrown - }); - it("Escape key closes lightbox when visible", async () => { await import("../panel/panel.js"); const lightbox = document.getElementById("lightbox"); lightbox.hidden = false; - document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); + document.dispatchEvent( + new KeyboardEvent("keydown", { key: "Escape", bubbles: true }) + ); expect(lightbox.hidden).toBe(true); }); - // ─── Code block copy button ─────────────────────────────────────────────── + // --- Splitter --- - it("code block copy button copies text", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ - text: "```\nconst x = 1;\n```", - isError: false, - }); + it("splitter drag resizes editor pane", async () => { await import("../panel/panel.js"); - const input = document.getElementById("command-input"); + const splitter = document.getElementById("splitter"); - input.value = "run-code const x = 1"; - input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + splitter.dispatchEvent( + new MouseEvent("mousedown", { clientY: 200, bubbles: true }) + ); + expect(document.body.style.cursor).toBe("row-resize"); - await vi.waitFor(() => { - const copyBtns = document.querySelectorAll(".code-copy-btn"); - if (copyBtns.length > 0) { - copyBtns[0].click(); - } - }); + document.dispatchEvent( + new MouseEvent("mousemove", { clientY: 250, bubbles: true }) + ); + + document.dispatchEvent(new MouseEvent("mouseup", { bubbles: true })); + expect(document.body.style.cursor).toBe(""); }); - // ─── Save button ────────────────────────────────────────────────────────── + // --- Save button --- it("save button saves editor content", async () => { window.prompt = vi.fn().mockReturnValue("test.pw"); @@ -1509,68 +689,26 @@ describe("panel.js", () => { editor.dispatchEvent(new Event("input")); document.getElementById("save-btn").click(); - - expect(document.getElementById("output").textContent).toContain("Saved as test.pw"); - }); - - it("save button does nothing for empty editor", async () => { - window.prompt = vi.fn(); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - // Enable buttons with real content - editor.value = "goto https://example.com"; - editor.dispatchEvent(new Event("input")); - // Then clear content without updating button states - editor.value = ""; - - document.getElementById("save-btn").click(); - - expect(document.getElementById("output").textContent).toContain("Nothing to save"); - }); - - it("save button cancelled by user", async () => { - window.prompt = vi.fn().mockReturnValue(null); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "goto https://example.com"; - editor.dispatchEvent(new Event("input")); - - document.getElementById("save-btn").click(); - - const output = document.getElementById("output").textContent; - expect(output).not.toContain("Saved"); - }); - - it("save button appends .pw if missing", async () => { - window.prompt = vi.fn().mockReturnValue("test"); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "goto https://example.com"; - editor.dispatchEvent(new Event("input")); - - document.getElementById("save-btn").click(); - - expect(document.getElementById("output").textContent).toContain("Saved as test.pw"); + expect(document.getElementById("output").textContent).toContain( + "Saved as test.pw" + ); }); - // ─── Open button ────────────────────────────────────────────────────────── + // --- Open button --- it("open button loads file content into editor", async () => { await import("../panel/panel.js"); - // Trigger open button - const openBtn = document.getElementById("open-btn"); - - // We need to mock the file input that gets created const realCreateElement = document.createElement.bind(document); - let fileInputEl; vi.spyOn(document, "createElement").mockImplementation((tag) => { const el = realCreateElement(tag); if (tag === "input") { - fileInputEl = el; - // Mock click to trigger change event with a fake file el.click = () => { - const file = new File(["goto https://example.com\nclick \"OK\""], "test.pw", { type: "text/plain" }); + const file = new File( + ['goto https://example.com\nclick "OK"'], + "test.pw", + { type: "text/plain" } + ); Object.defineProperty(el, "files", { value: [file] }); el.dispatchEvent(new Event("change")); }; @@ -1578,148 +716,14 @@ describe("panel.js", () => { return el; }); - openBtn.click(); + document.getElementById("open-btn").click(); await vi.waitFor(() => { - expect(document.getElementById("editor").value).toContain("goto https://example.com"); + expect(document.getElementById("editor").value).toContain( + "goto https://example.com" + ); }); document.createElement.mockRestore(); }); - - // ─── Export empty editor ────────────────────────────────────────────────── - - it("export button shows message for empty editor", async () => { - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - // Enable buttons with real content - editor.value = "goto https://example.com"; - editor.dispatchEvent(new Event("input")); - // Then clear content without updating button states - editor.value = ""; - - document.getElementById("export-btn").click(); - - expect(document.getElementById("output").textContent).toContain("Nothing to export"); - }); - - it("export converts comments with hash to JS comments", async () => { - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "# my comment\ngoto https://example.com"; - editor.dispatchEvent(new Event("input")); - - document.getElementById("export-btn").click(); - - await vi.waitFor(() => { - // Should produce a code block with the export - const output = document.getElementById("output").textContent; - expect(output).toContain("//"); - }); - }); - - // ─── Copy clipboard failure ─────────────────────────────────────────────── - - it("copy button shows error on clipboard failure", async () => { - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "goto https://example.com"; - editor.dispatchEvent(new Event("input")); - - // Make execCommand fail - vi.spyOn(document, "execCommand").mockImplementation(() => { - throw new Error("copy failed"); - }); - - document.getElementById("copy-btn").click(); - - expect(document.getElementById("output").textContent).toContain("Failed to copy"); - - document.execCommand.mockRestore(); - }); - - // ─── appendToEditor adds newline ────────────────────────────────────────── - - it("appendToEditor adds newline when editor does not end with one", async () => { - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "line1"; - - // Simulate a recorded command coming in via port - const portListener = mockPort.onMessage.addListener.mock.calls[0]?.[0]; - if (portListener) { - portListener({ type: "pw-recorded-command", command: "click \"OK\"" }); - expect(editor.value).toBe("line1\nclick \"OK\""); - } - }); - - // ─── syncScroll ─────────────────────────────────────────────────────────── - - it("editor scroll syncs line numbers", async () => { - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = Array(50).fill("line").join("\n"); - editor.dispatchEvent(new Event("input")); - - editor.scrollTop = 100; - editor.dispatchEvent(new Event("scroll")); - // Just verify no error thrown - }); - - // ─── Splitter drag ─────────────────────────────────────────────────────── - - it("splitter drag resizes editor pane", async () => { - await import("../panel/panel.js"); - const splitter = document.getElementById("splitter"); - const editorPane = document.getElementById("editor-pane"); - - // Simulate drag - splitter.dispatchEvent(new MouseEvent("mousedown", { clientY: 200, bubbles: true })); - expect(document.body.style.cursor).toBe("row-resize"); - - document.dispatchEvent(new MouseEvent("mousemove", { clientY: 250, bubbles: true })); - - document.dispatchEvent(new MouseEvent("mouseup", { bubbles: true })); - expect(document.body.style.cursor).toBe(""); - }); - - // ─── Recording error ───────────────────────────────────────────────────── - - it("record button handles start error", async () => { - chrome.runtime.sendMessage.mockRejectedValue(new Error("Cannot attach")); - await import("../panel/panel.js"); - - const recordBtn = document.getElementById("record-btn"); - recordBtn.click(); - - await vi.waitFor(() => { - expect(document.getElementById("output").textContent).toContain("Record error"); - }); - expect(recordBtn.classList.contains("recording")).toBe(false); - }); - - // ─── Step complete at end ───────────────────────────────────────────────── - - it("step button shows no-more-lines when editor shrinks between steps", async () => { - chrome.runtime.sendMessage.mockResolvedValue({ type: "success", data: "OK" }); - await import("../panel/panel.js"); - const editor = document.getElementById("editor"); - editor.value = "goto https://example.com\nclick \"OK\""; - editor.dispatchEvent(new Event("input")); - - const stepBtn = document.getElementById("step-btn"); - stepBtn.click(); - await vi.waitFor(() => { - expect(stepBtn.disabled).toBe(false); - }); - - // Shrink editor to only 1 line while stepLine=1 - editor.value = "goto https://example.com"; - // Don't dispatch input — stepLine stays at 1 - - stepBtn.click(); - await vi.waitFor(() => { - expect(document.getElementById("output").textContent).toContain("No more lines"); - }); - }); }); diff --git a/packages/extension/test/recorder.test.js b/packages/extension/test/recorder.test.js deleted file mode 100644 index 76b1c91..0000000 --- a/packages/extension/test/recorder.test.js +++ /dev/null @@ -1,534 +0,0 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; - -describe("content/recorder.js", () => { - let debugSpy; - - beforeEach(() => { - // Reset the recorder state - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - // Spy on console.debug (the recorder uses it to send commands) - debugSpy = vi.spyOn(console, "debug").mockImplementation(() => {}); - }); - - afterEach(() => { - // Clean up if recorder is active - if (window.__pwRecorderCleanup) { - window.__pwRecorderCleanup(); - } - debugSpy.mockRestore(); - }); - - it("sets __pwRecorderActive on load", async () => { - await import("../content/recorder.js"); - expect(window.__pwRecorderActive).toBe(true); - }); - - it("provides a cleanup function", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - await import("../content/recorder.js"); - expect(typeof window.__pwRecorderCleanup).toBe("function"); - }); - - it("does not run twice when __pwRecorderActive is set", async () => { - window.__pwRecorderActive = true; - const cleanupBefore = window.__pwRecorderCleanup; - await import("../content/recorder.js"); - // Cleanup should not be set (skipped due to guard) - expect(window.__pwRecorderCleanup).toBe(cleanupBefore); - }); - - it("cleanup resets __pwRecorderActive", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - await import("../content/recorder.js"); - expect(window.__pwRecorderActive).toBe(true); - window.__pwRecorderCleanup(); - expect(window.__pwRecorderActive).toBe(false); - }); - - it("cleanup removes __pwRecorderCleanup", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - await import("../content/recorder.js"); - window.__pwRecorderCleanup(); - expect(window.__pwRecorderCleanup).toBeUndefined(); - }); - - it("records click events", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - document.body.innerHTML = ''; - - await import("../content/recorder.js"); - - const btn = document.getElementById("test-btn"); - btn.click(); - - expect(debugSpy).toHaveBeenCalledWith("__pw:click \"Submit\""); - }); - - it("records checkbox check/uncheck", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - document.body.innerHTML = ''; - - await import("../content/recorder.js"); - - const cb = document.getElementById("test-cb"); - cb.checked = true; - cb.dispatchEvent(new Event("click", { bubbles: true })); - - expect(debugSpy).toHaveBeenCalledWith( - expect.stringContaining("__pw:check") - ); - }); - - it("records special key presses", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - await import("../content/recorder.js"); - - document.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - - expect(debugSpy).toHaveBeenCalledWith("__pw:press Enter"); - }); - - it("records Tab key press", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - await import("../content/recorder.js"); - - document.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true })); - - expect(debugSpy).toHaveBeenCalledWith("__pw:press Tab"); - }); - - it("records Escape key press", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - await import("../content/recorder.js"); - - document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); - - expect(debugSpy).toHaveBeenCalledWith("__pw:press Escape"); - }); - - it("does not record non-special key presses", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - await import("../content/recorder.js"); - - document.dispatchEvent(new KeyboardEvent("keydown", { key: "a", bubbles: true })); - - const pwCalls = debugSpy.mock.calls.filter(c => String(c[0]).startsWith("__pw:")); - expect(pwCalls).toHaveLength(0); - }); - - it("skips clicks on text input elements", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - document.body.innerHTML = ''; - - await import("../content/recorder.js"); - - const input = document.getElementById("test-input"); - input.click(); - - const pwCalls = debugSpy.mock.calls.filter(c => String(c[0]).startsWith("__pw:")); - expect(pwCalls).toHaveLength(0); - }); - - it("skips clicks on textarea elements", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - document.body.innerHTML = ''; - - await import("../content/recorder.js"); - - document.getElementById("test-ta").click(); - - const pwCalls = debugSpy.mock.calls.filter(c => String(c[0]).startsWith("__pw:")); - expect(pwCalls).toHaveLength(0); - }); - - it("records input events as debounced fill commands", async () => { - vi.resetModules(); - vi.useFakeTimers(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - document.body.innerHTML = ''; - - await import("../content/recorder.js"); - - const input = document.getElementById("test-input"); - input.value = "alice"; - input.dispatchEvent(new Event("input", { bubbles: true })); - - // Should not send immediately (debounced at 1500ms) - const pwCallsBefore = debugSpy.mock.calls.filter(c => String(c[0]).startsWith("__pw:")); - expect(pwCallsBefore).toHaveLength(0); - - // After debounce timer fires - vi.advanceTimersByTime(1500); - - expect(debugSpy).toHaveBeenCalledWith( - expect.stringContaining("__pw:fill") - ); - expect(debugSpy).toHaveBeenCalledWith( - expect.stringContaining("alice") - ); - - vi.useRealTimers(); - }); - - it("records select changes", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - document.body.innerHTML = ` - - `; - - await import("../content/recorder.js"); - - const sel = document.getElementById("test-sel"); - sel.value = "b"; - sel.dispatchEvent(new Event("change", { bubbles: true })); - - expect(debugSpy).toHaveBeenCalledWith( - expect.stringContaining("__pw:select") - ); - }); - - it("records link clicks with text content", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - document.body.innerHTML = 'About Us'; - - await import("../content/recorder.js"); - - document.getElementById("test-link").click(); - - expect(debugSpy).toHaveBeenCalledWith('__pw:click "About Us"'); - }); - - it("uses aria-label for locator", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - document.body.innerHTML = ''; - - await import("../content/recorder.js"); - - document.querySelector("button").click(); - - expect(debugSpy).toHaveBeenCalledWith( - expect.stringContaining('__pw:click "Close dialog"') - ); - }); - - // ─── getLocator: parent label ───────────────────────────────────────────── - - it("uses parent label text for locator", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - document.body.innerHTML = ''; - - await import("../content/recorder.js"); - - const cb = document.getElementById("cb"); - cb.checked = true; - cb.dispatchEvent(new Event("click", { bubbles: true })); - - expect(debugSpy).toHaveBeenCalledWith( - expect.stringContaining("Full Name") - ); - }); - - // ─── getLocator: button/link text, title, tag fallbacks ──────────────────── - - it("uses title attribute as locator fallback", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - document.body.innerHTML = ''; - - await import("../content/recorder.js"); - - document.querySelector("button").click(); - - expect(debugSpy).toHaveBeenCalledWith('__pw:click "Delete item"'); - }); - - it("falls back to tag name when no other locator available", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - // Element with no text, no aria-label, no title, no id - document.body.innerHTML = ''; - - await import("../content/recorder.js"); - - // Remove the id so getLocator falls through all branches - const btn = document.getElementById("test-empty"); - btn.removeAttribute("id"); - btn.click(); - - expect(debugSpy).toHaveBeenCalledWith('__pw:click "button"'); - }); - - it("uses placeholder for input locator", async () => { - vi.resetModules(); - vi.useFakeTimers(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - document.body.innerHTML = ''; - - await import("../content/recorder.js"); - - const input = document.getElementById("search"); - input.value = "hello"; - input.dispatchEvent(new Event("input", { bubbles: true })); - - vi.advanceTimersByTime(1500); - - expect(debugSpy).toHaveBeenCalledWith( - expect.stringContaining("Search...") - ); - - vi.useRealTimers(); - }); - - // ─── getItemContext: scoped clicks ───────────────────────────────────────── - - it("records action button with item context", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - document.body.innerHTML = ` -
    -
  • - Buy milk - -
  • -
- `; - - await import("../content/recorder.js"); - - document.getElementById("del-btn").click(); - - expect(debugSpy).toHaveBeenCalledWith( - expect.stringContaining("Buy milk") - ); - }); - - // ─── findCheckbox: label with htmlFor ────────────────────────────────────── - - it("finds checkbox via label htmlFor", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - document.body.innerHTML = ` - - - `; - - await import("../content/recorder.js"); - - const label = document.querySelector("label"); - const cb = document.getElementById("terms-cb"); - cb.checked = true; - label.click(); - - expect(debugSpy).toHaveBeenCalledWith( - expect.stringContaining("__pw:check") - ); - }); - - it("finds checkbox in parent label", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - document.body.innerHTML = ` - - `; - - await import("../content/recorder.js"); - - const cb = document.getElementById("nested-cb"); - cb.checked = true; - // Click the span, which is inside the label - document.getElementById("label-text").click(); - - expect(debugSpy).toHaveBeenCalledWith( - expect.stringContaining("__pw:check") - ); - }); - - // ─── checkbox with item context ──────────────────────────────────────────── - - it("records checkbox with item context label", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - document.body.innerHTML = ` -
    -
  • - - -
  • -
- `; - - await import("../content/recorder.js"); - - const cb = document.getElementById("task-cb"); - cb.checked = true; - cb.dispatchEvent(new Event("click", { bubbles: true })); - - expect(debugSpy).toHaveBeenCalledWith( - expect.stringContaining("Buy groceries") - ); - }); - - // ─── skips non-interactive containers ────────────────────────────────────── - - it("skips clicks on non-interactive containers like div", async () => { - vi.resetModules(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - document.body.innerHTML = '
Some content
'; - - await import("../content/recorder.js"); - - document.getElementById("container").click(); - - const pwCalls = debugSpy.mock.calls.filter(c => String(c[0]).startsWith("__pw:click")); - expect(pwCalls).toHaveLength(0); - }); - - // ─── click flushes pending fill ──────────────────────────────────────────── - - it("click flushes pending fill before recording click", async () => { - vi.resetModules(); - vi.useFakeTimers(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - document.body.innerHTML = ` - - - `; - - await import("../content/recorder.js"); - - const input = document.getElementById("name-input"); - input.value = "Alice"; - input.dispatchEvent(new Event("input", { bubbles: true })); - - // Click before debounce fires — should flush fill first - document.getElementById("submit-btn").click(); - - const pwCalls = debugSpy.mock.calls.filter(c => String(c[0]).startsWith("__pw:")); - expect(pwCalls[0][0]).toContain("__pw:fill"); - expect(pwCalls[1][0]).toContain("__pw:click"); - - vi.useRealTimers(); - }); - - // ─── label[for] locator ──────────────────────────────────────────────────── - - it("uses associated label text for locator via for attribute", async () => { - vi.resetModules(); - vi.useFakeTimers(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - document.body.innerHTML = ` - - - `; - - await import("../content/recorder.js"); - - const input = document.getElementById("email-input"); - input.value = "test@test.com"; - input.dispatchEvent(new Event("input", { bubbles: true })); - - vi.advanceTimersByTime(1500); - - expect(debugSpy).toHaveBeenCalledWith( - expect.stringContaining("Email Address") - ); - - vi.useRealTimers(); - }); - - it("cleanup flushes pending fill", async () => { - vi.resetModules(); - vi.useFakeTimers(); - delete window.__pwRecorderActive; - delete window.__pwRecorderCleanup; - - document.body.innerHTML = ''; - - await import("../content/recorder.js"); - - const input = document.getElementById("test-input"); - input.value = "test@test.com"; - input.dispatchEvent(new Event("input", { bubbles: true })); - - // Cleanup should flush pending fill - window.__pwRecorderCleanup(); - - expect(debugSpy).toHaveBeenCalledWith( - expect.stringContaining("__pw:fill") - ); - - vi.useRealTimers(); - }); -}); diff --git a/packages/extension/vitest.config.js b/packages/extension/vitest.config.js index f6d81cb..92fd447 100644 --- a/packages/extension/vitest.config.js +++ b/packages/extension/vitest.config.js @@ -6,7 +6,7 @@ export default defineConfig({ environment: "happy-dom", coverage: { provider: "v8", - include: ["content/**/*.js", "lib/**/*.js", "panel/**/*.js", "background.js", "devtools.js"], + include: ["lib/**/*.js", "panel/**/*.js", "background.js"], reporter: ["text", "html"], }, }, From d78e5a7fa7903efc7c8f57064b29f0b4741a9b62 Mon Sep 17 00:00:00 2001 From: Steve Zhang Date: Fri, 20 Feb 2026 16:46:33 -0500 Subject: [PATCH 08/27] extension: fix tab auto-select, suppress prompt, improve response filtering - Fix tab auto-select using page.bringToFront() instead of browser_tabs index (browserContext.pages() includes internal pages, causing index mismatch) - Panel sends activeTabUrl with each command via chrome.tabs.query - Suppress pw> prompt in extension mode for clean server logs - Single Ctrl+C exits immediately in extension mode - Server logs each command with page URL - Panel filterResponse extracts ### Result and ### Error sections Co-Authored-By: Claude Opus 4.6 --- packages/cli/src/repl.mjs | 5 ++ packages/core/src/engine.mjs | 16 +++++++ packages/core/src/extension-server.mjs | 9 +++- packages/extension/panel/panel.js | 65 ++++++++++++++++++++++++-- 4 files changed, 90 insertions(+), 5 deletions(-) diff --git a/packages/cli/src/repl.mjs b/packages/cli/src/repl.mjs index 8d8ae1f..887cce5 100644 --- a/packages/cli/src/repl.mjs +++ b/packages/cli/src/repl.mjs @@ -380,6 +380,10 @@ export function startCommandLoop(ctx) { let lastSigint = 0; ctx.rl.on('SIGINT', () => { + if (ctx.opts?.extension) { + ctx.conn.close(); + process.exit(0); + } const now = Date.now(); if (now - lastSigint < 500) { ctx.conn.close(); @@ -394,6 +398,7 @@ export function startCommandLoop(ctx) { // ─── Prompt string ────────────────────────────────────────────────────────── export function promptStr(ctx) { + if (ctx.opts?.extension) return ''; const mode = ctx.session.mode; const prefix = mode === 'recording' ? `${c.red}⏺${c.reset} ` : mode === 'paused' ? `${c.yellow}⏸${c.reset} ` diff --git a/packages/core/src/engine.mjs b/packages/core/src/engine.mjs index 3dd9520..50de992 100644 --- a/packages/core/src/engine.mjs +++ b/packages/core/src/engine.mjs @@ -46,6 +46,7 @@ export class Engine { constructor(deps) { this._deps = deps; this._backend = null; + this._browserContext = null; this._close = null; this._connected = false; } @@ -133,6 +134,7 @@ export class Engine { const { browserContext, close } = await factory.createContext( clientInfo, new AbortController().signal, {}, ); + this._browserContext = browserContext; this._close = close; const existingContextFactory = { @@ -165,6 +167,7 @@ export class Engine { const { browserContext, close } = await factory.createContext( clientInfo, new AbortController().signal, {}, ); + this._browserContext = browserContext; this._close = close; const existingContextFactory = { @@ -205,6 +208,19 @@ export class Engine { return formatResult(response); } + /** + * Select the Playwright page matching the given URL. + * Uses browserContext.pages() directly — no text parsing. + */ + async selectPageByUrl(targetUrl) { + if (!this._browserContext || !this._backend) return; + const pages = this._browserContext.pages(); + const page = pages.find(p => p.url() === targetUrl); + if (page) { + await page.bringToFront(); + } + } + /** * Shut down the browser and backend. */ diff --git a/packages/core/src/extension-server.mjs b/packages/core/src/extension-server.mjs index b392203..b3e3069 100644 --- a/packages/core/src/extension-server.mjs +++ b/packages/core/src/extension-server.mjs @@ -68,7 +68,14 @@ export class CommandServer { if (req.method === 'POST' && urlPath === '/run') { try { const body = await readBody(req); - const { raw } = JSON.parse(body); + const { raw, activeTabUrl } = JSON.parse(body); + console.log(`[server] ${raw} | ${activeTabUrl || 'no-url'}`); + + // Auto-select the tab matching the panel's active tab. + if (activeTabUrl) { + await this._engine.selectPageByUrl(activeTabUrl); + } + let args = parseInput(raw); if (!args) { res.writeHead(400, { 'Content-Type': 'application/json' }); diff --git a/packages/extension/panel/panel.js b/packages/extension/panel/panel.js index d468329..9a72379 100644 --- a/packages/extension/panel/panel.js +++ b/packages/extension/panel/panel.js @@ -30,6 +30,51 @@ const dropdown = document.getElementById("autocomplete-dropdown"); const SERVER_PORT = 6781; const SERVER_URL = `http://localhost:${SERVER_PORT}`; +// --- Response history (full responses stored for reference) --- +const responseHistory = []; + +/** + * Filter verbose response for panel display. + * + * Playwright MCP responses follow a consistent structure: + * ← the actual outcome (e.g. "Clicked", "Navigated to...") + * ### Section 1 ← supplementary context (code, tabs, page info, etc.) + * ### Section 2 + * ... + * + * Generic strategy: + * - Always store the full response in responseHistory + * - For "snapshot": show the ### Snapshot section (that's the whole point) + * - For everything else: show only the result text (before the first ### header) + */ +function filterResponse(command, text) { + responseHistory.push({ command, text, timestamp: Date.now() }); + + const cmdName = command.trim().split(/\s+/)[0]; + + // snapshot: return full response (the whole point is to see the tree) + if (cmdName === 'snapshot') return text; + + // Extract text before the first ### header (if any) + const firstSectionIdx = text.indexOf('### '); + const preamble = firstSectionIdx > 0 ? text.slice(0, firstSectionIdx).trim() : ''; + + // Extract content from useful ### sections (Result, Error, Snapshot) + const sections = text.split(/^### /m).slice(1); + const kept = []; + for (const section of sections) { + const nl = section.indexOf('\n'); + if (nl === -1) continue; + const title = section.substring(0, nl).trim(); + const content = section.substring(nl + 1).trim(); + if (title === 'Result' || title === 'Error') kept.push(content); + } + + if (preamble) return preamble; + if (kept.length > 0) return kept.join('\n'); + return 'Done'; +} + // --- Theme detection --- if (window.matchMedia("(prefers-color-scheme: dark)").matches) { document.body.classList.add("theme-dark"); @@ -363,6 +408,16 @@ function exportFromLines(cmds) { addCodeBlock(code); } +// --- Active tab detection --- + +async function getActiveTabUrl() { + try { + const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + console.log('[panel] activeTab:', tab?.id, tab?.url); + return tab?.url || null; + } catch (e) { console.error('[panel] tabs.query failed:', e); return null; } +} + // --- Command execution (REPL ad-hoc) --- async function executeCommand(raw) { @@ -425,17 +480,18 @@ async function executeCommand(raw) { addCommand(trimmed); try { + const activeTabUrl = await getActiveTabUrl(); const res = await fetch(`${SERVER_URL}/run`, { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ raw: trimmed }), + body: JSON.stringify({ raw: trimmed, activeTabUrl }), }); const result = await res.json(); if (result.isError) { addError(result.text); } else { - const text = result.text; + const text = filterResponse(trimmed, result.text); if (text.startsWith("data:image/png;base64,")) { addScreenshot(text.slice("data:image/png;base64,".length)); } else if (text.includes("[ref=") || text.startsWith("- ")) { @@ -466,10 +522,11 @@ async function executeCommandForRun(raw) { addCommand(trimmed); try { + const activeTabUrl = await getActiveTabUrl(); const res = await fetch(`${SERVER_URL}/run`, { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ raw: trimmed }), + body: JSON.stringify({ raw: trimmed, activeTabUrl }), }); const result = await res.json(); @@ -478,7 +535,7 @@ async function executeCommandForRun(raw) { lineResults[currentRunLine] = "fail"; runFailCount++; } else { - const text = result.text; + const text = filterResponse(trimmed, result.text); if (text.startsWith("data:image/png;base64,")) { addScreenshot(text.slice("data:image/png;base64,".length)); } else if (text.includes("[ref=") || text.startsWith("- ")) { From cdebba70b166b8d838c6a1a4e22b306c52994587 Mon Sep 17 00:00:00 2001 From: Steve Zhang Date: Fri, 20 Feb 2026 19:39:05 -0500 Subject: [PATCH 09/27] test: add Playwright E2E tests for extension side panel - Custom fixtures (panelPage, mockResponse) with page.route() mocking - 17 tests: initialization, REPL input, history, editor, run button, theme - Worker-scoped browser context, test-scoped page for isolation - CI workflow updated to install Chromium and run E2E tests - Fix hardcoded version string to read from /health endpoint Co-Authored-By: Claude Opus 4.6 --- .github/workflows/test.yml | 8 + package-lock.json | 157 +++++++++++----- packages/core/src/extension-server.mjs | 3 +- packages/extension/e2e/helpers.mjs | 78 ++++++++ packages/extension/e2e/panel.e2e.test.mjs | 211 ++++++++++++++++++++++ packages/extension/package.json | 2 + packages/extension/panel/panel.js | 6 +- packages/extension/playwright.config.js | 30 +++ 8 files changed, 444 insertions(+), 51 deletions(-) create mode 100644 packages/extension/e2e/helpers.mjs create mode 100644 packages/extension/e2e/panel.e2e.test.mjs create mode 100644 packages/extension/playwright.config.js diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 3cd6802..82c5855 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -27,3 +27,11 @@ jobs: - name: Run tests run: npm test + + - name: Install Playwright Chromium + run: npx playwright install chromium + working-directory: packages/extension + + - name: Run extension E2E tests + run: npx playwright test + working-directory: packages/extension diff --git a/package-lock.json b/package-lock.json index d026453..92d64ff 100644 --- a/package-lock.json +++ b/package-lock.json @@ -550,14 +550,49 @@ "resolved": "packages/core", "link": true }, - "node_modules/@playwright-repl/crx": { - "resolved": "packages/crx", - "link": true - }, "node_modules/@playwright-repl/extension": { "resolved": "packages/extension", "link": true }, + "node_modules/@playwright-repl/repl-ext": { + "resolved": "packages/repl-ext", + "link": true + }, + "node_modules/@playwright/test": { + "version": "1.58.2", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.58.2.tgz", + "integrity": "sha512-akea+6bHYBBfA9uQqSYmlJXn61cTa+jbO87xVLCWbTqbWadRVmhxlXATaOjOgcBaWU4ePo0wB41KMFv3o35IXA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.58.2" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@playwright/test/node_modules/playwright": { + "version": "1.58.2", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.58.2.tgz", + "integrity": "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.58.2" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, "node_modules/@rollup/pluginutils": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-3.1.0.tgz", @@ -1561,6 +1596,19 @@ "fsevents": "2.3.2" } }, + "node_modules/playwright-core": { + "version": "1.58.2", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.2.tgz", + "integrity": "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/playwright-crx": { "version": "0.15.0", "resolved": "https://registry.npmjs.org/playwright-crx/-/playwright-crx-0.15.0.tgz", @@ -2048,6 +2096,7 @@ "version": "8.19.0", "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", + "dev": true, "license": "MIT", "engines": { "node": ">=10.0.0" @@ -2117,8 +2166,7 @@ "name": "@playwright-repl/core", "version": "0.3.0", "dependencies": { - "minimist": "^1.2.8", - "ws": "^8.19.0" + "minimist": "^1.2.8" }, "devDependencies": { "vitest": "^4.0.18" @@ -2127,6 +2175,7 @@ "packages/crx": { "name": "@playwright-repl/crx", "version": "0.1.0", + "extraneous": true, "dependencies": { "playwright-crx": "^0.15.0" }, @@ -2137,7 +2186,31 @@ "vite": "^6.1.0" } }, - "packages/crx/node_modules/@esbuild/aix-ppc64": { + "packages/extension": { + "name": "@playwright-repl/extension", + "version": "1.0.0", + "devDependencies": { + "@playwright/test": "^1.58.2", + "@vitest/coverage-v8": "^4.0.18", + "happy-dom": "^20.6.1", + "vitest": "^4.0.18", + "vitest-chrome": "^0.1.0" + } + }, + "packages/repl-ext": { + "name": "@playwright-repl/repl-ext", + "version": "0.1.0", + "dependencies": { + "playwright-crx": "^0.15.0" + }, + "devDependencies": { + "@types/chrome": "^0.0.281", + "rollup-plugin-sourcemaps": "^0.6.3", + "typescript": "^5.7.3", + "vite": "^6.1.0" + } + }, + "packages/repl-ext/node_modules/@esbuild/aix-ppc64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", @@ -2154,7 +2227,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/android-arm": { + "packages/repl-ext/node_modules/@esbuild/android-arm": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", @@ -2171,7 +2244,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/android-arm64": { + "packages/repl-ext/node_modules/@esbuild/android-arm64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", @@ -2188,7 +2261,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/android-x64": { + "packages/repl-ext/node_modules/@esbuild/android-x64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", @@ -2205,7 +2278,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/darwin-arm64": { + "packages/repl-ext/node_modules/@esbuild/darwin-arm64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", @@ -2222,7 +2295,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/darwin-x64": { + "packages/repl-ext/node_modules/@esbuild/darwin-x64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", @@ -2239,7 +2312,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/freebsd-arm64": { + "packages/repl-ext/node_modules/@esbuild/freebsd-arm64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", @@ -2256,7 +2329,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/freebsd-x64": { + "packages/repl-ext/node_modules/@esbuild/freebsd-x64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", @@ -2273,7 +2346,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/linux-arm": { + "packages/repl-ext/node_modules/@esbuild/linux-arm": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", @@ -2290,7 +2363,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/linux-arm64": { + "packages/repl-ext/node_modules/@esbuild/linux-arm64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", @@ -2307,7 +2380,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/linux-ia32": { + "packages/repl-ext/node_modules/@esbuild/linux-ia32": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", @@ -2324,7 +2397,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/linux-loong64": { + "packages/repl-ext/node_modules/@esbuild/linux-loong64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", @@ -2341,7 +2414,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/linux-mips64el": { + "packages/repl-ext/node_modules/@esbuild/linux-mips64el": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", @@ -2358,7 +2431,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/linux-ppc64": { + "packages/repl-ext/node_modules/@esbuild/linux-ppc64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", @@ -2375,7 +2448,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/linux-riscv64": { + "packages/repl-ext/node_modules/@esbuild/linux-riscv64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", @@ -2392,7 +2465,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/linux-s390x": { + "packages/repl-ext/node_modules/@esbuild/linux-s390x": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", @@ -2409,7 +2482,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/linux-x64": { + "packages/repl-ext/node_modules/@esbuild/linux-x64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", @@ -2426,7 +2499,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/netbsd-arm64": { + "packages/repl-ext/node_modules/@esbuild/netbsd-arm64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", @@ -2443,7 +2516,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/netbsd-x64": { + "packages/repl-ext/node_modules/@esbuild/netbsd-x64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", @@ -2460,7 +2533,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/openbsd-arm64": { + "packages/repl-ext/node_modules/@esbuild/openbsd-arm64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", @@ -2477,7 +2550,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/openbsd-x64": { + "packages/repl-ext/node_modules/@esbuild/openbsd-x64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", @@ -2494,7 +2567,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/openharmony-arm64": { + "packages/repl-ext/node_modules/@esbuild/openharmony-arm64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", @@ -2511,7 +2584,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/sunos-x64": { + "packages/repl-ext/node_modules/@esbuild/sunos-x64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", @@ -2528,7 +2601,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/win32-arm64": { + "packages/repl-ext/node_modules/@esbuild/win32-arm64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", @@ -2545,7 +2618,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/win32-ia32": { + "packages/repl-ext/node_modules/@esbuild/win32-ia32": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", @@ -2562,7 +2635,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@esbuild/win32-x64": { + "packages/repl-ext/node_modules/@esbuild/win32-x64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", @@ -2579,7 +2652,7 @@ "node": ">=18" } }, - "packages/crx/node_modules/@types/chrome": { + "packages/repl-ext/node_modules/@types/chrome": { "version": "0.0.281", "resolved": "https://registry.npmjs.org/@types/chrome/-/chrome-0.0.281.tgz", "integrity": "sha512-MH+8FFrJ1POZwKnKRBa+jZcVp+yCFxes6PYKvgFd0qLTzoQe+TdejC3dkA8gSs8UGjFKrKzu4AkZypmswv0NOg==", @@ -2590,7 +2663,7 @@ "@types/har-format": "*" } }, - "packages/crx/node_modules/esbuild": { + "packages/repl-ext/node_modules/esbuild": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", @@ -2632,7 +2705,7 @@ "@esbuild/win32-x64": "0.25.12" } }, - "packages/crx/node_modules/fsevents": { + "packages/repl-ext/node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", @@ -2647,7 +2720,7 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, - "packages/crx/node_modules/rollup": { + "packages/repl-ext/node_modules/rollup": { "version": "4.58.0", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.58.0.tgz", "integrity": "sha512-wbT0mBmWbIvvq8NeEYWWvevvxnOyhKChir47S66WCxw1SXqhw7ssIYejnQEVt7XYQpsj2y8F9PM+Cr3SNEa0gw==", @@ -2692,7 +2765,7 @@ "fsevents": "~2.3.2" } }, - "packages/crx/node_modules/vite": { + "packages/repl-ext/node_modules/vite": { "version": "6.4.1", "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz", "integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==", @@ -2766,16 +2839,6 @@ "optional": true } } - }, - "packages/extension": { - "name": "@playwright-repl/extension", - "version": "1.0.0", - "devDependencies": { - "@vitest/coverage-v8": "^4.0.18", - "happy-dom": "^20.6.1", - "vitest": "^4.0.18", - "vitest-chrome": "^0.1.0" - } } } } diff --git a/packages/core/src/extension-server.mjs b/packages/core/src/extension-server.mjs index b3e3069..169fe47 100644 --- a/packages/core/src/extension-server.mjs +++ b/packages/core/src/extension-server.mjs @@ -8,6 +8,7 @@ import { createServer } from 'node:http'; import { parseInput } from './parser.mjs'; +import { replVersion } from './resolve.mjs'; import { buildRunCode, verifyText, verifyElement, verifyValue, verifyList, actionByText, fillByText, selectByText, checkByText, uncheckByText, @@ -60,7 +61,7 @@ export class CommandServer { // Health check endpoint if (req.method === 'GET' && urlPath === '/health') { res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ status: 'ok' })); + res.end(JSON.stringify({ status: 'ok', version: replVersion })); return; } diff --git a/packages/extension/e2e/helpers.mjs b/packages/extension/e2e/helpers.mjs new file mode 100644 index 0000000..d745860 --- /dev/null +++ b/packages/extension/e2e/helpers.mjs @@ -0,0 +1,78 @@ +/** + * E2E test fixtures — launches Chromium with the extension loaded, + * sets up page.route() mocking, and provides fixtures to tests. + */ + +import { test as base, chromium } from '@playwright/test'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const EXTENSION_PATH = path.resolve(__dirname, '..'); + +/** + * Custom test fixtures for the extension panel. + * + * Worker-scoped: browser context is shared across all tests in a worker. + * Test-scoped: panelPage and mockResponse reset per test. + */ +export const test = base.extend({ + // Worker-scoped: launch browser once, reuse across tests + extensionContext: [async ({}, use) => { + const headlessArgs = process.env.HEADED ? [] : ['--headless=new']; + + const context = await chromium.launchPersistentContext('', { + headless: false, + args: [ + ...headlessArgs, + `--disable-extensions-except=${EXTENSION_PATH}`, + `--load-extension=${EXTENSION_PATH}`, + '--no-first-run', + '--no-default-browser-check', + ], + }); + + // Get extension ID from the service worker URL + let sw = context.serviceWorkers()[0]; + if (!sw) sw = await context.waitForEvent('serviceworker'); + const extensionId = sw.url().split('/')[2]; + + // Context-level route: applies to all pages, set up once + await context.route('**/health', (route) => { + route.fulfill({ + contentType: 'application/json', + body: JSON.stringify({ status: 'ok', version: '0.4.0-test' }), + }); + }); + + await use({ context, extensionId }); + await context.close(); + }, { scope: 'worker' }], + + // Test-scoped: fresh panelPage with route mocking for each test + panelPage: async ({ extensionContext }, use) => { + const { context, extensionId } = extensionContext; + const page = await context.newPage(); + + page._runResponse = { text: 'OK', isError: false }; + + await page.route('**/run', async (route) => { + await route.fulfill({ + contentType: 'application/json', + body: JSON.stringify(page._runResponse), + }); + }); + + await page.goto(`chrome-extension://${extensionId}/panel/panel.html`); + await page.waitForSelector('.line-info', { timeout: 10000 }); + + await use(page); + await page.close(); + }, + + mockResponse: async ({ panelPage }, use) => { + await use((response) => { panelPage._runResponse = response; }); + }, +}); + +export { expect } from '@playwright/test'; diff --git a/packages/extension/e2e/panel.e2e.test.mjs b/packages/extension/e2e/panel.e2e.test.mjs new file mode 100644 index 0000000..5b4e3e9 --- /dev/null +++ b/packages/extension/e2e/panel.e2e.test.mjs @@ -0,0 +1,211 @@ +/** + * E2E tests for the extension side panel UI. + * + * Launches Chromium with the extension loaded, navigates to panel.html, + * and uses page.route() to intercept HTTP calls to the CommandServer. + */ + +import { test, expect } from './helpers.mjs'; + +// ─── Initialization ──────────────────────────────────────────────────────── + +test('shows version from health endpoint', async ({ panelPage }) => { + const text = await panelPage.locator('#output').textContent(); + expect(text).toContain('Playwright REPL v0.4.0-test'); +}); + +test('shows connected status', async ({ panelPage }) => { + const text = await panelPage.locator('#output').textContent(); + expect(text).toContain('Connected to server'); +}); + +test('has record button disabled', async ({ panelPage }) => { + const disabled = await panelPage.locator('#record-btn').isDisabled(); + expect(disabled).toBe(true); +}); + +test('has prompt visible', async ({ panelPage }) => { + const visible = await panelPage.locator('#prompt').isVisible(); + expect(visible).toBe(true); +}); + +// ─── REPL Command Input ──────────────────────────────────────────────────── + +test('displays success response after command', async ({ panelPage, mockResponse }) => { + mockResponse({ text: '### Result\nNavigated to https://example.com', isError: false }); + + const input = panelPage.locator('#command-input'); + await input.fill('goto https://example.com'); + await input.press('Enter'); + + await panelPage.waitForFunction( + () => document.querySelector('.line-success')?.textContent?.includes('Navigated'), + ); +}); + +test('clears input after submit', async ({ panelPage }) => { + const input = panelPage.locator('#command-input'); + await input.fill('snapshot'); + await input.press('Enter'); + await panelPage.waitForTimeout(200); + const value = await input.inputValue(); + expect(value).toBe(''); +}); + +test('does not send empty input', async ({ panelPage }) => { + const input = panelPage.locator('#command-input'); + await input.fill(' '); + await input.press('Enter'); + await panelPage.waitForTimeout(300); + const commands = panelPage.locator('.line-command'); + expect(await commands.count()).toBe(0); +}); + +test('displays error responses with error styling', async ({ panelPage, mockResponse }) => { + mockResponse({ text: 'Element not found', isError: true }); + + const input = panelPage.locator('#command-input'); + await input.fill('click missing'); + await input.press('Enter'); + + await panelPage.waitForFunction( + () => document.querySelector('.line-error')?.textContent?.includes('Element not found'), + ); +}); + +// ─── Command History ─────────────────────────────────────────────────────── + +test('navigates history with ArrowUp/ArrowDown', async ({ panelPage }) => { + const input = panelPage.locator('#command-input'); + + await input.fill('goto https://a.com'); + await input.press('Enter'); + await panelPage.waitForTimeout(300); + + await input.fill('goto https://b.com'); + await input.press('Enter'); + await panelPage.waitForTimeout(300); + + await input.press('ArrowUp'); + expect(await input.inputValue()).toBe('goto https://b.com'); + + await input.press('ArrowUp'); + expect(await input.inputValue()).toBe('goto https://a.com'); + + await input.press('ArrowDown'); + expect(await input.inputValue()).toBe('goto https://b.com'); + + await input.press('ArrowDown'); + expect(await input.inputValue()).toBe(''); +}); + +// ─── Local Commands ──────────────────────────────────────────────────────── + +test('clear empties the output', async ({ panelPage }) => { + const input = panelPage.locator('#command-input'); + await input.fill('snapshot'); + await input.press('Enter'); + await panelPage.waitForSelector('.line-command'); + + await input.fill('clear'); + await input.press('Enter'); + + const lines = panelPage.locator('#output .line'); + expect(await lines.count()).toBe(0); +}); + +test('comments display without server call', async ({ panelPage }) => { + const input = panelPage.locator('#command-input'); + await input.fill('# this is a comment'); + await input.press('Enter'); + + await panelPage.waitForSelector('.line-comment'); + const text = await panelPage.locator('.line-comment').last().textContent(); + expect(text).toContain('# this is a comment'); +}); + +// ─── Editor ──────────────────────────────────────────────────────────────── + +test('shows line numbers for content', async ({ panelPage }) => { + const editor = panelPage.locator('#editor'); + await editor.fill('goto https://example.com\nclick OK\npress Enter'); + await editor.dispatchEvent('input'); + await panelPage.waitForTimeout(100); + + const lineNums = panelPage.locator('#line-numbers div'); + expect(await lineNums.count()).toBe(3); +}); + +test('enables buttons when editor has content', async ({ panelPage }) => { + const editor = panelPage.locator('#editor'); + await editor.fill('goto https://example.com'); + await editor.dispatchEvent('input'); + await panelPage.waitForTimeout(100); + + expect(await panelPage.locator('#copy-btn').isDisabled()).toBe(false); + expect(await panelPage.locator('#save-btn').isDisabled()).toBe(false); + expect(await panelPage.locator('#export-btn').isDisabled()).toBe(false); +}); + +test('disables buttons when editor is empty', async ({ panelPage }) => { + const editor = panelPage.locator('#editor'); + await editor.fill(''); + await editor.dispatchEvent('input'); + await panelPage.waitForTimeout(100); + + expect(await panelPage.locator('#copy-btn').isDisabled()).toBe(true); + expect(await panelPage.locator('#save-btn').isDisabled()).toBe(true); + expect(await panelPage.locator('#export-btn').isDisabled()).toBe(true); +}); + +// ─── Run Button ──────────────────────────────────────────────────────────── + +test('executes all editor lines and shows Run complete', async ({ panelPage }) => { + const editor = panelPage.locator('#editor'); + await editor.fill('goto https://example.com\nclick OK'); + await editor.dispatchEvent('input'); + + await panelPage.locator('#run-btn').click(); + + await panelPage.waitForFunction( + () => document.getElementById('output').textContent.includes('Run complete'), + { timeout: 15000 }, + ); +}); + +test('shows fail stats when command errors', async ({ panelPage, mockResponse }) => { + mockResponse({ text: 'Failed', isError: true }); + + const input = panelPage.locator('#command-input'); + await input.fill('clear'); + await input.press('Enter'); + + const editor = panelPage.locator('#editor'); + await editor.fill('click missing'); + await editor.dispatchEvent('input'); + + await panelPage.locator('#run-btn').click(); + + await panelPage.waitForFunction( + () => document.getElementById('output').textContent.includes('Run complete'), + { timeout: 15000 }, + ); + + const statsText = await panelPage.locator('#console-stats').textContent(); + expect(statsText).toContain('1'); +}); + +// ─── Theme ───────────────────────────────────────────────────────────────── + +test('applies dark theme based on color scheme', async ({ panelPage }) => { + await panelPage.emulateMedia({ colorScheme: 'dark' }); + await panelPage.reload(); + await panelPage.waitForSelector('.line-info', { timeout: 10000 }); + + const hasDark = await panelPage.evaluate( + () => document.body.classList.contains('theme-dark'), + ); + expect(hasDark).toBe(true); + + await panelPage.emulateMedia({ colorScheme: 'light' }); +}); diff --git a/packages/extension/package.json b/packages/extension/package.json index 9b3ee2d..8b50358 100644 --- a/packages/extension/package.json +++ b/packages/extension/package.json @@ -6,9 +6,11 @@ "type": "module", "scripts": { "test": "vitest run", + "test:e2e": "npx playwright test", "test:coverage": "vitest run --coverage" }, "devDependencies": { + "@playwright/test": "^1.58.2", "@vitest/coverage-v8": "^4.0.18", "happy-dom": "^20.6.1", "vitest": "^4.0.18", diff --git a/packages/extension/panel/panel.js b/packages/extension/panel/panel.js index 9a72379..64a4a14 100644 --- a/packages/extension/panel/panel.js +++ b/packages/extension/panel/panel.js @@ -961,13 +961,13 @@ updateFileInfo(); updateButtonStates(); editor.focus(); -addInfo("Playwright REPL v1.0.0"); - -// Health check — verify server is running +// Health check — verify server is running and show version (async () => { try { const res = await fetch(`${SERVER_URL}/health`); if (res.ok) { + const data = await res.json(); + addInfo(`Playwright REPL v${data.version || '?'}`); addInfo("Connected to server on port " + SERVER_PORT); } else { addError("Server returned status " + res.status); diff --git a/packages/extension/playwright.config.js b/packages/extension/playwright.config.js new file mode 100644 index 0000000..4b2c74a --- /dev/null +++ b/packages/extension/playwright.config.js @@ -0,0 +1,30 @@ +import { defineConfig } from '@playwright/test'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +export default defineConfig({ + testDir: './e2e', + timeout: 30000, + retries: 0, + use: { + headless: false, + }, + projects: [ + { + name: 'extension', + use: { + launchOptions: { + args: [ + ...(process.env.HEADED ? [] : ['--headless=new']), + `--disable-extensions-except=${__dirname}`, + `--load-extension=${__dirname}`, + '--no-first-run', + '--no-default-browser-check', + ], + }, + }, + }, + ], +}); From 0b1ead8fb8e6a6a46c08df987d636becf0bec217 Mon Sep 17 00:00:00 2001 From: Steve Zhang Date: Fri, 20 Feb 2026 21:49:16 -0500 Subject: [PATCH 10/27] test: add command integration tests and restructure E2E test suite Restructure E2E tests into panel/ and commands/ projects under playwright.config.js. Add 25 command integration tests exercising the full Engine + CommandServer stack via HTTP POST /run, covering navigation, snapshot, click, fill, press, select, eval, screenshot, check/uncheck, hover, run-code (4 auto-wrap paths), verify-text, verify-element, aliases, and error cases. Also fix CommandServer port 0 support for test isolation, extract screenshot image from formatResult in engine.mjs, and update panel.js to display base64 screenshot images. Co-Authored-By: Claude Opus 4.6 --- .github/workflows/test.yml | 8 +- packages/core/src/engine.mjs | 9 +- packages/core/src/extension-server.mjs | 6 +- .../extension/e2e/commands/commands.test.mjs | 244 ++++++++++++++++++ packages/extension/e2e/commands/fixtures.mjs | 44 ++++ .../e2e/{helpers.mjs => panel/fixtures.mjs} | 2 +- .../panel.test.mjs} | 2 +- packages/extension/panel/panel.js | 14 +- packages/extension/playwright.config.js | 27 +- packages/extension/vitest.config.js | 1 + 10 files changed, 323 insertions(+), 34 deletions(-) create mode 100644 packages/extension/e2e/commands/commands.test.mjs create mode 100644 packages/extension/e2e/commands/fixtures.mjs rename packages/extension/e2e/{helpers.mjs => panel/fixtures.mjs} (97%) rename packages/extension/e2e/{panel.e2e.test.mjs => panel/panel.test.mjs} (99%) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 82c5855..6cc0d6e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -32,6 +32,10 @@ jobs: run: npx playwright install chromium working-directory: packages/extension - - name: Run extension E2E tests - run: npx playwright test + - name: Run extension panel tests + run: npx playwright test --project=panel + working-directory: packages/extension + + - name: Run command integration tests + run: npx playwright test --project=commands working-directory: packages/extension diff --git a/packages/core/src/engine.mjs b/packages/core/src/engine.mjs index 50de992..9697a1d 100644 --- a/packages/core/src/engine.mjs +++ b/packages/core/src/engine.mjs @@ -308,6 +308,11 @@ export class Engine { function formatResult(result) { const isError = result.isError; - const text = result.content[0].type === 'text' ? result.content[0].text : undefined; - return { isError, text }; + let text; + let image; + for (const item of result.content) { + if (item.type === 'text' && !text) text = item.text; + if (item.type === 'image' && !image) image = `data:${item.mimeType || 'image/png'};base64,${item.data}`; + } + return { isError, text, image }; } diff --git a/packages/core/src/extension-server.mjs b/packages/core/src/extension-server.mjs index 169fe47..39b58c8 100644 --- a/packages/core/src/extension-server.mjs +++ b/packages/core/src/extension-server.mjs @@ -26,11 +26,13 @@ export class CommandServer { get port() { return this._port; } async start(port = 6781) { - this._port = port; this._server = createServer((req, res) => this._handleHttp(req, res)); return new Promise((resolve, reject) => { - this._server.listen(port, () => resolve()); + this._server.listen(port, () => { + this._port = this._server.address().port; + resolve(); + }); this._server.on('error', reject); }); } diff --git a/packages/extension/e2e/commands/commands.test.mjs b/packages/extension/e2e/commands/commands.test.mjs new file mode 100644 index 0000000..dc2b029 --- /dev/null +++ b/packages/extension/e2e/commands/commands.test.mjs @@ -0,0 +1,244 @@ +/** + * Command integration tests — exercises the full stack: + * real Engine + CommandServer + Playwright browser. + * + * Each test sends commands via HTTP POST /run and asserts on actual results. + */ + +import { test, expect } from './fixtures.mjs'; + +// ─── Helper ───────────────────────────────────────────────────────────────── + +/** + * Extract an element ref (e.g. "e5") from snapshot text by matching a label. + * Handles formats like: + * - link "Learn more" [ref=e6] → label before ref + * - textbox "Name" [ref=e2] → label before ref + * - combobox [ref=e2]: → type before ref (no label) + */ +function findRef(snapshotText, labelPattern) { + // Try: label appears before [ref=eN] on same line + const re1 = new RegExp(`${labelPattern}.*\\[ref=(e\\d+)\\]`, 'i'); + const m1 = snapshotText.match(re1); + if (m1) return m1[1]; + + // Try: [ref=eN] appears before label on same line + const re2 = new RegExp(`\\[ref=(e\\d+)\\].*${labelPattern}`, 'i'); + const m2 = snapshotText.match(re2); + if (m2) return m2[1]; + + throw new Error(`No ref found for "${labelPattern}" in snapshot:\n${snapshotText}`); +} + +// ─── Navigation ───────────────────────────────────────────────────────────── + +test('goto navigates to a URL', async ({ run }) => { + const result = await run('goto https://example.com'); + expect(result.isError).toBeFalsy(); + expect(result.text).toContain('Page URL: https://example.com'); +}); + +test('goto with alias g', async ({ run }) => { + const result = await run('g https://example.com'); + expect(result.isError).toBeFalsy(); + expect(result.text).toContain('Page URL: https://example.com'); +}); + +test('go-back navigates to previous page', async ({ run }) => { + await run('goto https://example.com'); + await run('goto https://www.iana.org'); + const result = await run('go-back'); + expect(result.isError).toBeFalsy(); + expect(result.text).toContain('Page URL: https://example.com'); +}); + +test('go-forward navigates to next page', async ({ run }) => { + await run('goto https://example.com'); + await run('goto https://www.iana.org'); + await run('go-back'); + const result = await run('go-forward'); + expect(result.isError).toBeFalsy(); + expect(result.text).toContain('Page URL: https://www.iana.org'); +}); + +// ─── Snapshot ─────────────────────────────────────────────────────────────── + +test('snapshot returns accessibility tree with refs', async ({ run }) => { + await run('goto https://example.com'); + const result = await run('snapshot'); + expect(result.isError).toBeFalsy(); + expect(result.text).toContain('Example Domain'); + expect(result.text).toMatch(/\[ref=e\d+\]/); +}); + +test('snapshot with alias s', async ({ run }) => { + await run('goto https://example.com'); + const result = await run('s'); + expect(result.isError).toBeFalsy(); + expect(result.text).toContain('Example Domain'); + expect(result.text).toMatch(/\[ref=e\d+\]/); +}); + +// ─── Click ────────────────────────────────────────────────────────────────── + +test('click an element by ref', async ({ run }) => { + await run('goto https://example.com'); + const snap = await run('snapshot'); + const ref = findRef(snap.text, 'Learn more'); + const result = await run(`click ${ref}`); + expect(result.isError).toBeFalsy(); + expect(result.text).toContain('Page URL'); +}); + +// ─── Fill ─────────────────────────────────────────────────────────────────── + +test('fill an input field', async ({ run }) => { + await run('goto https://demo.playwright.dev/todomvc/'); + const result = await run('fill "What needs to be done" "Buy groceries"'); + expect(result.isError).toBeFalsy(); +}); + +// ─── Press ────────────────────────────────────────────────────────────────── + +test('press a keyboard key', async ({ run }) => { + await run('goto https://example.com'); + const result = await run('press Tab'); + expect(result.isError).toBeFalsy(); +}); + +// ─── Select ───────────────────────────────────────────────────────────────── + +test('select a dropdown option', async ({ run }) => { + await run('goto https://the-internet.herokuapp.com/dropdown'); + const snap = await run('snapshot'); + const ref = findRef(snap.text, 'combobox'); + const result = await run(`select ${ref} "Option 1"`); + expect(result.isError).toBeFalsy(); +}); + +// ─── Eval ─────────────────────────────────────────────────────────────────── + +test('eval executes JavaScript', async ({ run }) => { + await run('goto https://example.com'); + const result = await run('eval document.title'); + expect(result.isError).toBeFalsy(); + expect(result.text).toContain('Example Domain'); +}); + +// ─── Screenshot ───────────────────────────────────────────────────────────── + +test('screenshot captures the page', async ({ run }) => { + await run('goto https://example.com'); + const result = await run('screenshot'); + expect(result.isError).toBeFalsy(); + expect(result.text).toContain('.png'); + expect(result.image).toMatch(/^data:image\/png;base64,/); +}); + +// ─── Check / Uncheck ──────────────────────────────────────────────────────── + +test('check a todo item', async ({ run }) => { + await run('goto https://demo.playwright.dev/todomvc/'); + await run('fill "What needs to be done" "Buy groceries"'); + await run('press Enter'); + const result = await run('check "Buy groceries"'); + expect(result.isError).toBeFalsy(); +}); + +test('uncheck a todo item', async ({ run }) => { + await run('goto https://demo.playwright.dev/todomvc/'); + await run('fill "What needs to be done" "Clean house"'); + await run('press Enter'); + await run('check "Clean house"'); + const result = await run('uncheck "Clean house"'); + expect(result.isError).toBeFalsy(); +}); + +// ─── Hover ────────────────────────────────────────────────────────────────── + +test('hover over an element', async ({ run }) => { + await run('goto https://example.com'); + const result = await run('hover "Example Domain"'); + expect(result.isError).toBeFalsy(); +}); + +// ─── Run-code ─────────────────────────────────────────────────────────────── + +test('run-code simple expression returns result', async ({ run }) => { + await run('goto https://example.com'); + const result = await run('run-code page.title()'); + expect(result.isError).toBeFalsy(); + expect(result.text).toContain('### Result'); + expect(result.text).toContain('Example Domain'); + expect(result.text).toContain('return await page.title()'); +}); + +test('run-code multi-statement with semicolons', async ({ run }) => { + await run('goto https://example.com'); + const result = await run('run-code const t = await page.title(); return t'); + expect(result.isError).toBeFalsy(); + expect(result.text).toContain('### Result'); + expect(result.text).toContain('Example Domain'); + expect(result.text).toContain('const t = await page.title(); return t'); +}); + +test('run-code with await statement', async ({ run }) => { + await run('goto https://example.com'); + const result = await run('run-code await page.waitForTimeout(100)'); + expect(result.isError).toBeFalsy(); + expect(result.text).toContain('await page.waitForTimeout(100)'); +}); + +test('run-code with async function passes through unchanged', async ({ run }) => { + await run('goto https://example.com'); + const result = await run('run-code async (page) => { const t = await page.title(); return t }'); + expect(result.isError).toBeFalsy(); + expect(result.text).toContain('### Result'); + expect(result.text).toContain('Example Domain'); + expect(result.text).toContain('const t = await page.title(); return t'); +}); + +// ─── Verify commands ──────────────────────────────────────────────────────── + +test('verify-text passes when text exists', async ({ run }) => { + await run('goto https://example.com'); + const result = await run('verify-text "Example Domain"'); + expect(result.isError).toBeFalsy(); +}); + +test('verify-text fails when text is missing', async ({ run }) => { + await run('goto https://example.com'); + const result = await run('verify-text "nonexistent text xyz"'); + expect(result.isError).toBe(true); + expect(result.text).toContain('Text not found'); +}); + +test('verify-element passes when element exists', async ({ run }) => { + await run('goto https://example.com'); + const result = await run('verify-element heading "Example Domain"'); + expect(result.isError).toBeFalsy(); +}); + +// ─── Aliases ──────────────────────────────────────────────────────────────── + +test('alias c for click', async ({ run }) => { + await run('goto https://example.com'); + const snap = await run('s'); + const ref = findRef(snap.text, 'Learn more'); + const result = await run(`c ${ref}`); + expect(result.isError).toBeFalsy(); +}); + +// ─── Errors ───────────────────────────────────────────────────────────────── + +test('unknown command returns error', async ({ run }) => { + const result = await run('nonexistent'); + expect(result.isError).toBe(true); + expect(result.text).toContain('Unknown command'); +}); + +test('invalid ref returns error', async ({ run }) => { + await run('goto https://example.com'); + const result = await run('click e9999'); + expect(result.isError).toBe(true); +}); diff --git a/packages/extension/e2e/commands/fixtures.mjs b/packages/extension/e2e/commands/fixtures.mjs new file mode 100644 index 0000000..7126533 --- /dev/null +++ b/packages/extension/e2e/commands/fixtures.mjs @@ -0,0 +1,44 @@ +/** + * Command integration test fixtures. + * + * Launches a real Engine + CommandServer, sends commands via HTTP, + * and asserts on actual Playwright browser behavior. + */ + +import { test as base } from '@playwright/test'; +import { Engine } from '../../../core/src/engine.mjs'; +import { CommandServer } from '../../../core/src/extension-server.mjs'; + +export const test = base.extend({ + // Worker-scoped: one Engine + CommandServer per worker + engineContext: [async ({}, use) => { + const engine = new Engine(); + await engine.start({ browser: 'chromium', headed: false }); + + const server = new CommandServer(engine); + await server.start(0); // OS-assigned port + + await use({ engine, server, port: server.port }); + + await server.close(); + await engine.close(); + }, { scope: 'worker' }], + + // Test-scoped: run() helper sends commands to the real server + run: async ({ engineContext }, use) => { + const { port } = engineContext; + + const run = async (command) => { + const res = await fetch(`http://localhost:${port}/run`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ raw: command }), + }); + return res.json(); + }; + + await use(run); + }, +}); + +export { expect } from '@playwright/test'; diff --git a/packages/extension/e2e/helpers.mjs b/packages/extension/e2e/panel/fixtures.mjs similarity index 97% rename from packages/extension/e2e/helpers.mjs rename to packages/extension/e2e/panel/fixtures.mjs index d745860..96fdbb8 100644 --- a/packages/extension/e2e/helpers.mjs +++ b/packages/extension/e2e/panel/fixtures.mjs @@ -8,7 +8,7 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); -const EXTENSION_PATH = path.resolve(__dirname, '..'); +const EXTENSION_PATH = path.resolve(__dirname, '../..'); /** * Custom test fixtures for the extension panel. diff --git a/packages/extension/e2e/panel.e2e.test.mjs b/packages/extension/e2e/panel/panel.test.mjs similarity index 99% rename from packages/extension/e2e/panel.e2e.test.mjs rename to packages/extension/e2e/panel/panel.test.mjs index 5b4e3e9..2c48168 100644 --- a/packages/extension/e2e/panel.e2e.test.mjs +++ b/packages/extension/e2e/panel/panel.test.mjs @@ -5,7 +5,7 @@ * and uses page.route() to intercept HTTP calls to the CommandServer. */ -import { test, expect } from './helpers.mjs'; +import { test, expect } from './fixtures.mjs'; // ─── Initialization ──────────────────────────────────────────────────────── diff --git a/packages/extension/panel/panel.js b/packages/extension/panel/panel.js index 64a4a14..88fb4e1 100644 --- a/packages/extension/panel/panel.js +++ b/packages/extension/panel/panel.js @@ -491,10 +491,11 @@ async function executeCommand(raw) { if (result.isError) { addError(result.text); } else { + if (result.image) { + addScreenshot(result.image.replace(/^data:image\/\w+;base64,/, '')); + } const text = filterResponse(trimmed, result.text); - if (text.startsWith("data:image/png;base64,")) { - addScreenshot(text.slice("data:image/png;base64,".length)); - } else if (text.includes("[ref=") || text.startsWith("- ")) { + if (text.includes("[ref=") || text.startsWith("- ")) { for (const line of text.split("\n")) { addSnapshot(line); } @@ -535,10 +536,11 @@ async function executeCommandForRun(raw) { lineResults[currentRunLine] = "fail"; runFailCount++; } else { + if (result.image) { + addScreenshot(result.image.replace(/^data:image\/\w+;base64,/, '')); + } const text = filterResponse(trimmed, result.text); - if (text.startsWith("data:image/png;base64,")) { - addScreenshot(text.slice("data:image/png;base64,".length)); - } else if (text.includes("[ref=") || text.startsWith("- ")) { + if (text.includes("[ref=") || text.startsWith("- ")) { for (const line of text.split("\n")) { addSnapshot(line); } diff --git a/packages/extension/playwright.config.js b/packages/extension/playwright.config.js index 4b2c74a..b7daede 100644 --- a/packages/extension/playwright.config.js +++ b/packages/extension/playwright.config.js @@ -1,30 +1,17 @@ import { defineConfig } from '@playwright/test'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const __dirname = path.dirname(fileURLToPath(import.meta.url)); export default defineConfig({ - testDir: './e2e', timeout: 30000, retries: 0, - use: { - headless: false, - }, projects: [ { - name: 'extension', - use: { - launchOptions: { - args: [ - ...(process.env.HEADED ? [] : ['--headless=new']), - `--disable-extensions-except=${__dirname}`, - `--load-extension=${__dirname}`, - '--no-first-run', - '--no-default-browser-check', - ], - }, - }, + name: 'panel', + testDir: './e2e/panel', + }, + { + name: 'commands', + testDir: './e2e/commands', + timeout: 60000, }, ], }); diff --git a/packages/extension/vitest.config.js b/packages/extension/vitest.config.js index 92fd447..986afd3 100644 --- a/packages/extension/vitest.config.js +++ b/packages/extension/vitest.config.js @@ -4,6 +4,7 @@ export default defineConfig({ test: { setupFiles: "./test/setup.js", environment: "happy-dom", + exclude: ["e2e/**", "node_modules/**"], coverage: { provider: "v8", include: ["lib/**/*.js", "panel/**/*.js", "background.js"], From 473e13abff05700c4f7a95a7caf67f1f7f6bf17e Mon Sep 17 00:00:00 2001 From: Steve Zhang Date: Fri, 20 Feb 2026 21:57:26 -0500 Subject: [PATCH 11/27] fix: update panel unit tests to match current fetch API - Make mock fetch route-aware (/health returns version, /run returns result) - Update fetch call expectations to include activeTabUrl and headers - Fix success response mock to use realistic format with ### sections - Fix screenshot mock to use result.image field instead of base64 in text Co-Authored-By: Claude Opus 4.6 --- packages/extension/test/panel.test.js | 61 ++++++++++++++++++++------- 1 file changed, 45 insertions(+), 16 deletions(-) diff --git a/packages/extension/test/panel.test.js b/packages/extension/test/panel.test.js index d27fcee..f539933 100644 --- a/packages/extension/test/panel.test.js +++ b/packages/extension/test/panel.test.js @@ -57,10 +57,18 @@ describe("panel.js", () => { // Mock window.matchMedia for theme detection window.matchMedia = vi.fn().mockReturnValue({ matches: false }); - // Mock fetch — default to successful response - global.fetch = vi.fn().mockResolvedValue({ - ok: true, - json: () => Promise.resolve({ text: "OK", isError: false }), + // Mock fetch — route-aware: /health returns version, /run returns command result + global.fetch = vi.fn((url) => { + if (url && url.includes("/health")) { + return Promise.resolve({ + ok: true, + json: () => Promise.resolve({ status: "ok", version: "1.0.0" }), + }); + } + return Promise.resolve({ + ok: true, + json: () => Promise.resolve({ text: "OK", isError: false }), + }); }); }); @@ -176,7 +184,7 @@ describe("panel.js", () => { expect.stringContaining("/run"), expect.objectContaining({ method: "POST", - body: JSON.stringify({ raw: "click e5" }), + body: JSON.stringify({ raw: "click e5", activeTabUrl: null }), }) ); }); @@ -210,9 +218,21 @@ describe("panel.js", () => { // --- Response display --- it("displays success response in output", async () => { - global.fetch = vi.fn().mockResolvedValue({ - ok: true, - json: () => Promise.resolve({ text: "Navigated", isError: false }), + global.fetch = vi.fn((url) => { + if (url && url.includes("/health")) { + return Promise.resolve({ + ok: true, + json: () => Promise.resolve({ status: "ok", version: "1.0.0" }), + }); + } + return Promise.resolve({ + ok: true, + json: () => + Promise.resolve({ + text: "Navigated\n### Page\n- Page URL: https://example.com", + isError: false, + }), + }); }); await import("../panel/panel.js"); const input = document.getElementById("command-input"); @@ -270,13 +290,22 @@ describe("panel.js", () => { }); it("displays screenshot as image in output", async () => { - global.fetch = vi.fn().mockResolvedValue({ - ok: true, - json: () => - Promise.resolve({ - text: "data:image/png;base64,fakebase64", - isError: false, - }), + global.fetch = vi.fn((url) => { + if (url && url.includes("/health")) { + return Promise.resolve({ + ok: true, + json: () => Promise.resolve({ status: "ok", version: "1.0.0" }), + }); + } + return Promise.resolve({ + ok: true, + json: () => + Promise.resolve({ + text: "Screenshot saved\n### Page\n- Page URL: https://example.com", + image: "data:image/png;base64,fakebase64", + isError: false, + }), + }); }); await import("../panel/panel.js"); const input = document.getElementById("command-input"); @@ -565,7 +594,7 @@ describe("panel.js", () => { expect(global.fetch).toHaveBeenCalledWith( expect.stringContaining("/run"), expect.objectContaining({ - body: JSON.stringify({ raw: "goto https://example.com" }), + body: JSON.stringify({ raw: "goto https://example.com", activeTabUrl: null }), }) ); }); From 09e25d16061794fdfa7768de741a76c8bfcf5c82 Mon Sep 17 00:00:00 2001 From: Steve Zhang Date: Fri, 20 Feb 2026 22:03:00 -0500 Subject: [PATCH 12/27] fix: drop Node 18, use 127.0.0.1 and port 0 in server tests Playwright requires Node.js >= 20. Drop Node 18 from CI matrix and update engines field. Fix extension-server tests to use 127.0.0.1 instead of localhost (avoids IPv6 resolution issues) and port 0 (OS-assigned, avoids EADDRINUSE conflicts). Co-Authored-By: Claude Opus 4.6 --- .github/workflows/test.yml | 2 +- packages/cli/package.json | 2 +- packages/core/test/extension-server.test.mjs | 39 ++++++++++---------- 3 files changed, 21 insertions(+), 22 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 6cc0d6e..ac1143a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -12,7 +12,7 @@ jobs: strategy: matrix: - node-version: [18, 20, 22] + node-version: [20, 22] steps: - uses: actions/checkout@v4 diff --git a/packages/cli/package.json b/packages/cli/package.json index eda8575..a022fdb 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -33,7 +33,7 @@ "src/" ], "engines": { - "node": ">=18.0.0" + "node": ">=20.0.0" }, "dependencies": { "@playwright-repl/core": "file:../core", diff --git a/packages/core/test/extension-server.test.mjs b/packages/core/test/extension-server.test.mjs index dd6470d..eb7ca62 100644 --- a/packages/core/test/extension-server.test.mjs +++ b/packages/core/test/extension-server.test.mjs @@ -15,7 +15,6 @@ function createMockEngine() { describe('CommandServer', () => { let server; let engine; - const TEST_PORT = 13579; beforeEach(() => { engine = createMockEngine(); @@ -28,12 +27,12 @@ describe('CommandServer', () => { describe('lifecycle', () => { it('starts and listens on the given port', async () => { - await server.start(TEST_PORT); - expect(server.port).toBe(TEST_PORT); + await server.start(0); + expect(server.port).toBeGreaterThan(0); }); it('close() is idempotent', async () => { - await server.start(TEST_PORT); + await server.start(0); await server.close(); await server.close(); // Should not throw }); @@ -45,9 +44,9 @@ describe('CommandServer', () => { describe('POST /run', () => { it('runs command through engine and returns result', async () => { - await server.start(TEST_PORT); + await server.start(0); - const res = await fetch(`http://localhost:${TEST_PORT}/run`, { + const res = await fetch(`http://127.0.0.1:${server.port}/run`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ raw: 'click e5' }), @@ -61,9 +60,9 @@ describe('CommandServer', () => { }); it('returns 400 for unknown commands', async () => { - await server.start(TEST_PORT); + await server.start(0); - const res = await fetch(`http://localhost:${TEST_PORT}/run`, { + const res = await fetch(`http://127.0.0.1:${server.port}/run`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ raw: '' }), @@ -76,9 +75,9 @@ describe('CommandServer', () => { it('returns 500 when engine throws', async () => { engine.run.mockRejectedValueOnce(new Error('Engine exploded')); - await server.start(TEST_PORT); + await server.start(0); - const res = await fetch(`http://localhost:${TEST_PORT}/run`, { + const res = await fetch(`http://127.0.0.1:${server.port}/run`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ raw: 'click e5' }), @@ -93,9 +92,9 @@ describe('CommandServer', () => { describe('CORS', () => { it('responds to OPTIONS preflight with CORS headers', async () => { - await server.start(TEST_PORT); + await server.start(0); - const res = await fetch(`http://localhost:${TEST_PORT}/run`, { + const res = await fetch(`http://127.0.0.1:${server.port}/run`, { method: 'OPTIONS', }); @@ -105,9 +104,9 @@ describe('CommandServer', () => { }); it('includes CORS headers on POST responses', async () => { - await server.start(TEST_PORT); + await server.start(0); - const res = await fetch(`http://localhost:${TEST_PORT}/run`, { + const res = await fetch(`http://127.0.0.1:${server.port}/run`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ raw: 'click e5' }), @@ -119,9 +118,9 @@ describe('CommandServer', () => { describe('GET /health', () => { it('returns 200 with status ok', async () => { - await server.start(TEST_PORT); + await server.start(0); - const res = await fetch(`http://localhost:${TEST_PORT}/health`); + const res = await fetch(`http://127.0.0.1:${server.port}/health`); expect(res.status).toBe(200); const data = await res.json(); expect(data.status).toBe('ok'); @@ -130,16 +129,16 @@ describe('CommandServer', () => { describe('other routes', () => { it('returns 404 for unknown paths', async () => { - await server.start(TEST_PORT); + await server.start(0); - const res = await fetch(`http://localhost:${TEST_PORT}/unknown`); + const res = await fetch(`http://127.0.0.1:${server.port}/unknown`); expect(res.status).toBe(404); }); it('returns 404 for GET /run', async () => { - await server.start(TEST_PORT); + await server.start(0); - const res = await fetch(`http://localhost:${TEST_PORT}/run`); + const res = await fetch(`http://127.0.0.1:${server.port}/run`); expect(res.status).toBe(404); }); }); From 86e17ef268075fa3f4e210c0cd40c75512018286 Mon Sep 17 00:00:00 2001 From: Steve Zhang Date: Fri, 20 Feb 2026 22:05:59 -0500 Subject: [PATCH 13/27] fix: install Chromium for both playwright versions in CI The root playwright (1.59-alpha, used by Engine in command tests) and @playwright/test (1.58, used by panel tests) have different browser cache paths. Install Chromium for both. Co-Authored-By: Claude Opus 4.6 --- .github/workflows/test.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ac1143a..736860c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -28,10 +28,13 @@ jobs: - name: Run tests run: npm test - - name: Install Playwright Chromium + - name: Install Playwright Chromium (panel tests) run: npx playwright install chromium working-directory: packages/extension + - name: Install Playwright Chromium (command tests) + run: npx playwright install chromium + - name: Run extension panel tests run: npx playwright test --project=panel working-directory: packages/extension From e1dc00ef8142ef8b6ac7ff6a623ad8c62fb369b6 Mon Sep 17 00:00:00 2001 From: Steve Zhang Date: Fri, 20 Feb 2026 22:11:06 -0500 Subject: [PATCH 14/27] fix: use explicit playwright CLI path for command tests Chromium install npx playwright install from root resolves to @playwright/test's CLI binary instead of the root playwright package. Use the explicit path node_modules/playwright/cli.js to ensure Chromium is installed for the correct package version (1.59.0-alpha) that Engine uses. Co-Authored-By: Claude Opus 4.6 --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 736860c..d1a9a63 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -33,7 +33,7 @@ jobs: working-directory: packages/extension - name: Install Playwright Chromium (command tests) - run: npx playwright install chromium + run: node node_modules/playwright/cli.js install chromium - name: Run extension panel tests run: npx playwright test --project=panel From fc7afed2c38feb69306319ab542d41588ecfa43b Mon Sep 17 00:00:00 2001 From: Steve Zhang Date: Sat, 21 Feb 2026 10:11:45 -0500 Subject: [PATCH 15/27] extension: recording, go-back/forward fix, and CDP stability improvements Recording: inject recorder.js via chrome.scripting.executeScript, capture clicks/fills/selects/keypresses, detect go-back/go-forward via webNavigation.onCommitted, re-inject on navigation. Panel record button toggles recording and receives commands via chrome.runtime.onMessage. Fixes: go-back/go-forward use history API instead of page.goBack() to avoid bfcache hangs in CDP mode. selectPageByUrl uses backend.callTool to properly update tab tracker. Auto-select skips internal chrome:// pages. Added timeout protection for all server commands. Reduced navigation timeout to 15s for extension mode. Link clicks in recorder emit immediately to avoid loss during page navigation. Co-Authored-By: Claude Opus 4.6 --- packages/core/src/engine.mjs | 32 +- packages/core/src/extension-server.mjs | 24 +- packages/extension/background.js | 166 ++++++- packages/extension/content/recorder.js | 238 ++++++++++ packages/extension/e2e/panel/panel.test.mjs | 107 ++++- packages/extension/manifest.json | 4 +- packages/extension/panel/panel.js | 46 +- packages/extension/test/background.test.js | 283 +++++++++++ packages/extension/test/panel.test.js | 4 +- packages/extension/test/recorder.test.js | 492 ++++++++++++++++++++ packages/extension/test/setup.js | 24 + packages/extension/vitest.config.js | 2 +- 12 files changed, 1399 insertions(+), 23 deletions(-) create mode 100644 packages/extension/content/recorder.js create mode 100644 packages/extension/test/background.test.js create mode 100644 packages/extension/test/recorder.test.js diff --git a/packages/core/src/engine.mjs b/packages/core/src/engine.mjs index 9697a1d..f53fc58 100644 --- a/packages/core/src/engine.mjs +++ b/packages/core/src/engine.mjs @@ -144,17 +144,23 @@ export class Engine { await this._backend.initialize?.(clientInfo); this._connected = true; - // 5. Auto-select the active (visible) tab so commands target what the user sees. + // 5. Auto-select the first visible web page. const pages = browserContext.pages(); + const INTERNAL = /^(chrome|devtools|chrome-extension|about):/; + let selectedIdx = -1; for (let i = 0; i < pages.length; i++) { + const pageUrl = pages[i].url(); + if (!pageUrl || INTERNAL.test(pageUrl)) continue; try { const state = await pages[i].evaluate(() => document.visibilityState); - if (state === 'visible' && i > 0) { - await this._backend.callTool('browser_tabs', { action: 'select', index: i }); - break; + if (state === 'visible' && selectedIdx === -1) { + selectedIdx = i; } } catch {} } + if (selectedIdx > 0) { + await this._backend.callTool('browser_tabs', { action: 'select', index: selectedIdx }); + } console.log('Ready! Side panel can send commands.'); @@ -210,14 +216,20 @@ export class Engine { /** * Select the Playwright page matching the given URL. - * Uses browserContext.pages() directly — no text parsing. + * Uses backend.callTool('browser_tabs') to properly update the tab tracker. */ async selectPageByUrl(targetUrl) { - if (!this._browserContext || !this._backend) return; + if (!this._browserContext || !this._backend || !targetUrl) return; const pages = this._browserContext.pages(); - const page = pages.find(p => p.url() === targetUrl); - if (page) { - await page.bringToFront(); + const normalize = (u) => u.replace(/\/+$/, ''); + const target = normalize(targetUrl); + for (let i = 0; i < pages.length; i++) { + if (normalize(pages[i].url()) === target) { + try { + await this._backend.callTool('browser_tabs', { action: 'select', index: i }); + } catch {} + return; + } } } @@ -263,7 +275,7 @@ export class Engine { network: {}, timeouts: { action: opts.extension ? 30000 : 5000, - navigation: 60000, + navigation: opts.extension ? 15000 : 60000, }, }; diff --git a/packages/core/src/extension-server.mjs b/packages/core/src/extension-server.mjs index 39b58c8..bfc94df 100644 --- a/packages/core/src/extension-server.mjs +++ b/packages/core/src/extension-server.mjs @@ -76,7 +76,7 @@ export class CommandServer { // Auto-select the tab matching the panel's active tab. if (activeTabUrl) { - await this._engine.selectPageByUrl(activeTabUrl); + await withTimeout(this._engine.selectPageByUrl(activeTabUrl), 5000).catch(() => {}); } let args = parseInput(raw); @@ -86,7 +86,7 @@ export class CommandServer { return; } args = resolveArgs(args); - const result = await this._engine.run(args); + const result = await withTimeout(this._engine.run(args), 30000); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(result)); } catch (e) { @@ -147,6 +147,16 @@ function resolveArgs(args) { else args = buildRunCode(fn, textArg); } + // ── go-back / go-forward → evaluate history.back/forward ── + // Playwright's page.goBack() waits for load which can hang with bfcache in CDP mode. + // Use history API directly — the user sees the browser live, no need to wait. + if (cmdName === 'go-back') { + args = { _: ['run-code', 'async (page) => { await page.evaluate(() => history.back()); return "Navigated back"; }'] }; + } + if (cmdName === 'go-forward') { + args = { _: ['run-code', 'async (page) => { await page.evaluate(() => history.forward()); return "Navigated forward"; }'] }; + } + // ── Auto-wrap run-code body with async (page) => { ... } ── if (cmdName === 'run-code' && args._[1] && !args._[1].startsWith('async')) { const STMT = /^(await|return|const|let|var|for|if|while|throw|try)\b/; @@ -168,3 +178,13 @@ function readBody(req) { req.on('end', () => resolve(data)); }); } + +function withTimeout(promise, ms) { + let timer; + return Promise.race([ + promise, + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(`Command timed out after ${ms / 1000}s`)), ms); + }), + ]).finally(() => clearTimeout(timer)); +} diff --git a/packages/extension/background.js b/packages/extension/background.js index 0cb0176..364772d 100644 --- a/packages/extension/background.js +++ b/packages/extension/background.js @@ -1,2 +1,166 @@ -// background.js — Opens side panel when extension icon is clicked. +// background.js — Opens side panel when extension icon is clicked + recording handlers. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }); + +// ─── Recording State ─────────────────────────────────────────────────────── + +let recordingTabId = null; +let tabUpdateListener = null; +let navCommittedListener = null; +let lastRecordedUrl = null; +let urlStack = []; +let stackIndex = -1; + +// ─── Message Handler ──────────────────────────────────────────────────────── + +chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => { + if (msg.type === "pw-record-start") { + startRecording(msg.tabId).then(sendResponse); + return true; + } + if (msg.type === "pw-record-stop") { + stopRecording(msg.tabId).then(sendResponse); + return true; + } +}); + +// ─── Tab Activation (follow active tab) ───────────────────────────────────── + +chrome.tabs.onActivated.addListener((activeInfo) => { + if (recordingTabId === null) return; + recordingTabId = activeInfo.tabId; + injectRecorder(activeInfo.tabId).catch(() => {}); + // Notify panel about tab switch + chrome.tabs.get(activeInfo.tabId, (tab) => { + if (chrome.runtime.lastError) return; + chrome.runtime.sendMessage({ + type: "pw-recorded-command", + command: "# tab: " + (tab.title || tab.url || "unknown"), + }).catch(() => {}); + }); +}); + +// ─── Recording Functions ──────────────────────────────────────────────────── + +async function startRecording(tabId) { + try { + await injectRecorder(tabId); + recordingTabId = tabId; + + // Store the initial URL and initialize history stack + const tab = await chrome.tabs.get(tabId); + lastRecordedUrl = tab.url; + urlStack = [tab.url]; + stackIndex = 0; + + // Listen for navigation commits to detect back/forward vs typed URLs + navCommittedListener = (details) => { + if (details.tabId !== recordingTabId) return; + if (details.frameId !== 0) return; // main frame only + if (details.url === lastRecordedUrl) return; + + const qualifiers = details.transitionQualifiers || []; + + if (qualifiers.includes("forward_back")) { + // Back or forward — compare to history stack + if (stackIndex > 0 && details.url === urlStack[stackIndex - 1]) { + stackIndex--; + chrome.runtime.sendMessage({ + type: "pw-recorded-command", + command: "go-back", + }).catch(() => {}); + } else if (stackIndex < urlStack.length - 1 && details.url === urlStack[stackIndex + 1]) { + stackIndex++; + chrome.runtime.sendMessage({ + type: "pw-recorded-command", + command: "go-forward", + }).catch(() => {}); + } else { + // Can't determine direction — default to go-back + chrome.runtime.sendMessage({ + type: "pw-recorded-command", + command: "go-back", + }).catch(() => {}); + } + } else if (details.transitionType === "typed" || qualifiers.includes("from_address_bar")) { + // User typed URL in address bar + chrome.runtime.sendMessage({ + type: "pw-recorded-command", + command: "goto " + details.url, + }).catch(() => {}); + // Push to history stack (truncate any forward entries) + urlStack = urlStack.slice(0, stackIndex + 1); + urlStack.push(details.url); + stackIndex = urlStack.length - 1; + } else { + // Link click, form submit, etc. — don't emit goto (click already recorded) + // But do update the history stack + urlStack = urlStack.slice(0, stackIndex + 1); + urlStack.push(details.url); + stackIndex = urlStack.length - 1; + } + + lastRecordedUrl = details.url; + }; + chrome.webNavigation.onCommitted.addListener(navCommittedListener); + + // Listen for page load completion to re-inject recorder + tabUpdateListener = (updatedTabId, changeInfo) => { + if (updatedTabId !== recordingTabId) return; + if (changeInfo.status === "complete") { + injectRecorder(updatedTabId).catch((err) => { + console.warn("[recorder] re-injection failed:", err.message); + }); + } + }; + chrome.tabs.onUpdated.addListener(tabUpdateListener); + + return { ok: true }; + } catch (err) { + return { ok: false, error: err.message }; + } +} + +async function stopRecording(tabId) { + try { + // Remove navigation listeners + if (navCommittedListener) { + chrome.webNavigation.onCommitted.removeListener(navCommittedListener); + navCommittedListener = null; + } + if (tabUpdateListener) { + chrome.tabs.onUpdated.removeListener(tabUpdateListener); + tabUpdateListener = null; + } + recordingTabId = null; + urlStack = []; + stackIndex = -1; + + // Run cleanup on the tab + await chrome.scripting.executeScript({ + target: { tabId }, + func: () => { + if (typeof window.__pwRecorderCleanup === "function") { + window.__pwRecorderCleanup(); + } + }, + }); + + return { ok: true }; + } catch (err) { + // Cleanup failure is non-fatal (tab may have closed) + return { ok: true }; + } +} + +async function injectRecorder(tabId) { + await chrome.scripting.executeScript({ + target: { tabId }, + files: ["content/recorder.js"], + }); +} + +// ─── Exports for Testing ──────────────────────────────────────────────────── + +if (typeof module !== "undefined" && module.exports) { + module.exports = { startRecording, stopRecording, injectRecorder }; +} diff --git a/packages/extension/content/recorder.js b/packages/extension/content/recorder.js new file mode 100644 index 0000000..d1c2c4f --- /dev/null +++ b/packages/extension/content/recorder.js @@ -0,0 +1,238 @@ +// Content recorder — injected into pages via chrome.scripting.executeScript. +// Captures user interactions and sends .pw commands via chrome.runtime.sendMessage. + +(() => { + if (document.documentElement.dataset.pwRecorderActive) return; + document.documentElement.dataset.pwRecorderActive = "true"; + + function getLocator(el) { + const ariaLabel = el.getAttribute && el.getAttribute("aria-label"); + if (ariaLabel) return quote(ariaLabel); + + if (el.id) { + const label = document.querySelector('label[for="' + CSS.escape(el.id) + '"]'); + if (label && label.textContent.trim()) return quote(label.textContent.trim()); + } + const parentLabel = el.closest && el.closest("label"); + if (parentLabel && parentLabel.textContent.trim()) { + return quote(parentLabel.textContent.trim()); + } + + if (el.placeholder) return quote(el.placeholder); + + const text = el.textContent ? el.textContent.trim() : ""; + if (text && text.length < 80 && el.children.length === 0) return quote(text); + + if ((el.tagName === "BUTTON" || el.tagName === "A") && text && text.length < 80) { + return quote(text); + } + + if (el.title) return quote(el.title); + + const tag = el.tagName ? el.tagName.toLowerCase() : "unknown"; + return quote(tag); + } + + // Get the primary text of a container (e.g., a list item's label) + function getItemContext(el) { + const item = el.closest && el.closest("li, tr, [role=listitem], [role=row], article"); + if (!item) return null; + const primary = item.querySelector("label, h1, h2, h3, h4, [class*=title], [class*=text], p, span"); + if (primary && primary !== el && primary.textContent.trim()) { + const t = primary.textContent.trim(); + if (t.length < 80) return t; + } + return null; + } + + function quote(s) { + return '"' + s.replace(/"/g, '\\"') + '"'; + } + + function send(command) { + chrome.runtime.sendMessage({ type: "pw-recorded-command", command }); + } + + let fillTimer = null; + let fillTarget = null; + let fillValue = ""; + + function flushFill() { + if (fillTarget && fillValue) { + const locator = getLocator(fillTarget); + send('fill ' + locator + ' "' + fillValue.replace(/"/g, '\\"') + '"'); + } + fillTimer = null; + fillTarget = null; + fillValue = ""; + } + + // Elements that are non-interactive containers — skip recording clicks on these + var skipTags = new Set(["HTML", "BODY", "MAIN", "FOOTER", "HEADER", "NAV", "SECTION", "ARTICLE", "DIV", "UL", "OL", "FORM", "FIELDSET", "TABLE", "TBODY", "THEAD", "TR"]); + + function findCheckbox(el) { + if (el.tagName === "INPUT" && el.type === "checkbox") return el; + if (el.tagName === "LABEL") { + var input = el.querySelector('input[type="checkbox"]'); + if (input) return input; + if (el.htmlFor) { + var target = document.getElementById(el.htmlFor); + if (target && target.type === "checkbox") return target; + } + } + var parentLabel = el.closest("label"); + if (parentLabel) { + var cb = parentLabel.querySelector('input[type="checkbox"]'); + if (cb) return cb; + } + return null; + } + + let clickTimer = null; + + function handleClick(e) { + try { + var el = e.target; + if (!el || !el.tagName) return; + + // Skip text inputs and textareas — handled by handleInput + if ((el.tagName === "INPUT" && el.type !== "checkbox" && el.type !== "radio") || el.tagName === "TEXTAREA") return; + + // Skip clicks on non-interactive container elements + if (skipTags.has(el.tagName) && !el.getAttribute("role") && !el.getAttribute("onclick")) return; + + // Links: emit immediately (page navigates before debounce timer fires) + if (el.closest && el.closest("a[href]")) { + if (clickTimer) { clearTimeout(clickTimer); clickTimer = null; } + if (fillTimer) { clearTimeout(fillTimer); flushFill(); } + emitClick(e); + return; + } + + // Delay other clicks to allow dblclick dedup + if (clickTimer) { clearTimeout(clickTimer); clickTimer = null; } + clickTimer = setTimeout(() => { + clickTimer = null; + emitClick(e); + }, 250); + } catch(err) { + send("# click recording error: " + err.message); + } + } + + function emitClick(e) { + try { + if (fillTimer) { clearTimeout(fillTimer); flushFill(); } + var el = e.target; + + // Check for checkbox (direct or via label/parent) + var checkbox = findCheckbox(el); + if (checkbox) { + var cbLabel = getItemContext(checkbox) || ""; + if (cbLabel) { + send(checkbox.checked ? 'check "' + cbLabel + '"' : 'uncheck "' + cbLabel + '"'); + } else { + var loc = getLocator(checkbox); + send(checkbox.checked ? 'check ' + loc : 'uncheck ' + loc); + } + return; + } + + var locator = getLocator(el); + var actionWords = new Set(["delete", "remove", "edit", "close", "destroy", "\u00d7", "\u2715", "\u2716", "\u2717", "\u2718", "x"]); + var elText = (el.textContent || "").trim().toLowerCase(); + var elClass = (el.className || "").toLowerCase(); + var elAriaLabel = (el.getAttribute && el.getAttribute("aria-label") || "").toLowerCase(); + var isAction = actionWords.has(elText) + || [...actionWords].some(function(w) { return elClass.includes(w); }) + || [...actionWords].some(function(w) { return elAriaLabel.includes(w); }) + || (el.tagName === "BUTTON" && !elText && el.closest && el.closest("li, tr, [role=listitem]")); + try { + var ctx = getItemContext(el); + if (ctx && isAction) { + send('click ' + locator + ' "' + ctx.replace(/"/g, '\\"') + '"'); + } else { + send('click ' + locator); + } + } catch(ce) { + send('click ' + locator); + } + } catch(err) { + send("# click recording error: " + err.message); + } + } + + function handleDblClick(e) { + try { + // Cancel pending single click — dblclick supersedes it + if (clickTimer) { clearTimeout(clickTimer); clickTimer = null; } + if (fillTimer) { clearTimeout(fillTimer); flushFill(); } + var el = e.target; + if (!el || !el.tagName) return; + if (skipTags.has(el.tagName) && !el.getAttribute("role") && !el.getAttribute("onclick")) return; + var locator = getLocator(el); + send('dblclick ' + locator); + } catch(err) { + send("# dblclick recording error: " + err.message); + } + } + + function handleContextMenu(e) { + try { + var el = e.target; + if (!el || !el.tagName) return; + if (skipTags.has(el.tagName) && !el.getAttribute("role") && !el.getAttribute("onclick")) return; + var locator = getLocator(el); + send('click ' + locator + ' --button right'); + } catch(err) { + send("# contextmenu recording error: " + err.message); + } + } + + function handleInput(e) { + const el = e.target; + if (el.tagName !== "INPUT" && el.tagName !== "TEXTAREA") return; + if (el.type === "checkbox" || el.type === "radio") return; + fillTarget = el; + fillValue = el.value; + if (fillTimer) clearTimeout(fillTimer); + fillTimer = setTimeout(flushFill, 1500); + } + + function handleChange(e) { + const el = e.target; + if (el.tagName === "SELECT") { + const opt = el.options[el.selectedIndex]; + const optText = opt ? opt.text.trim() : el.value; + send('select ' + getLocator(el) + ' "' + optText.replace(/"/g, '\\"') + '"'); + } + } + + function handleKeydown(e) { + const specialKeys = ["Enter", "Tab", "Escape"]; + if (specialKeys.includes(e.key)) { + if (fillTimer) { clearTimeout(fillTimer); flushFill(); } + send('press ' + e.key); + } + } + + document.addEventListener("click", handleClick, true); + document.addEventListener("dblclick", handleDblClick, true); + document.addEventListener("contextmenu", handleContextMenu, true); + document.addEventListener("input", handleInput, true); + document.addEventListener("change", handleChange, true); + document.addEventListener("keydown", handleKeydown, true); + + window.__pwRecorderCleanup = () => { + if (fillTimer) { clearTimeout(fillTimer); flushFill(); } + if (clickTimer) { clearTimeout(clickTimer); clickTimer = null; } + document.removeEventListener("click", handleClick, true); + document.removeEventListener("dblclick", handleDblClick, true); + document.removeEventListener("contextmenu", handleContextMenu, true); + document.removeEventListener("input", handleInput, true); + document.removeEventListener("change", handleChange, true); + document.removeEventListener("keydown", handleKeydown, true); + delete document.documentElement.dataset.pwRecorderActive; + delete window.__pwRecorderCleanup; + }; +})(); diff --git a/packages/extension/e2e/panel/panel.test.mjs b/packages/extension/e2e/panel/panel.test.mjs index 2c48168..fcee979 100644 --- a/packages/extension/e2e/panel/panel.test.mjs +++ b/packages/extension/e2e/panel/panel.test.mjs @@ -19,9 +19,9 @@ test('shows connected status', async ({ panelPage }) => { expect(text).toContain('Connected to server'); }); -test('has record button disabled', async ({ panelPage }) => { - const disabled = await panelPage.locator('#record-btn').isDisabled(); - expect(disabled).toBe(true); +test('has record button enabled', async ({ panelPage }) => { + const enabled = await panelPage.locator('#record-btn').isEnabled(); + expect(enabled).toBe(true); }); test('has prompt visible', async ({ panelPage }) => { @@ -195,6 +195,107 @@ test('shows fail stats when command errors', async ({ panelPage, mockResponse }) expect(statsText).toContain('1'); }); +// ─── Recording UI ───────────────────────────────────────────────────────── + +test('record button toggles to Stop when recording starts', async ({ panelPage }) => { + // Mock chrome APIs so we don't need a real tab to inject into + await panelPage.evaluate(() => { + chrome.tabs.query = async () => [{ id: 999, title: "Test Page", url: "https://example.com" }]; + const origSend = chrome.runtime.sendMessage.bind(chrome.runtime); + chrome.runtime.sendMessage = async (msg) => { + if (msg.type === 'pw-record-start' || msg.type === 'pw-record-stop') return { ok: true }; + return origSend(msg); + }; + }); + + const btn = panelPage.locator('#record-btn'); + + // Click to start recording + await btn.click(); + await expect(btn).toHaveText('Stop'); + const hasRecording = await btn.evaluate(el => el.classList.contains('recording')); + expect(hasRecording).toBe(true); + + // Info message should appear + await panelPage.waitForFunction( + () => { + const infos = document.querySelectorAll('.line-info'); + return [...infos].some(el => el.textContent.includes('Recording on')); + }, + ); +}); + +test('record button toggles back to Record when stopped', async ({ panelPage }) => { + await panelPage.evaluate(() => { + chrome.tabs.query = async () => [{ id: 999, title: "Test Page", url: "https://example.com" }]; + const origSend = chrome.runtime.sendMessage.bind(chrome.runtime); + chrome.runtime.sendMessage = async (msg) => { + if (msg.type === 'pw-record-start' || msg.type === 'pw-record-stop') return { ok: true }; + return origSend(msg); + }; + }); + + const btn = panelPage.locator('#record-btn'); + + // Start then stop + await btn.click(); + await expect(btn).toHaveText('Stop'); + await btn.click(); + await expect(btn).toHaveText('Record'); + const hasRecording = await btn.evaluate(el => el.classList.contains('recording')); + expect(hasRecording).toBe(false); + + // Stop info message should appear + await panelPage.waitForFunction( + () => { + const infos = document.querySelectorAll('.line-info'); + return [...infos].some(el => el.textContent.includes('Recording stopped')); + }, + ); +}); + +test('record button shows error when injection fails', async ({ panelPage }) => { + await panelPage.evaluate(() => { + chrome.tabs.query = async () => [{ id: 999, title: "Test Page", url: "chrome://settings" }]; + const origSend = chrome.runtime.sendMessage.bind(chrome.runtime); + chrome.runtime.sendMessage = async (msg) => { + if (msg.type === 'pw-record-start') return { ok: false, error: 'Cannot access chrome:// URLs' }; + return origSend(msg); + }; + }); + + const btn = panelPage.locator('#record-btn'); + await btn.click(); + + // Should show error + await panelPage.waitForFunction( + () => document.querySelector('.line-error')?.textContent?.includes('Cannot access'), + ); + + // Button should NOT be in recording state + const hasRecording = await btn.evaluate(el => el.classList.contains('recording')); + expect(hasRecording).toBe(false); +}); + +test('received recorded commands appear in editor', async ({ panelPage }) => { + // Send a message from the service worker to simulate a recorded command + const context = panelPage.context(); + const sw = context.serviceWorkers()[0]; + + await sw.evaluate(() => { + chrome.runtime.sendMessage({ type: 'pw-recorded-command', command: 'click "Submit"' }); + }); + + // Verify command appears in the console output + await panelPage.waitForFunction( + () => document.querySelector('.line-command')?.textContent?.includes('click "Submit"'), + ); + + // Verify command is also appended to the editor + const editorValue = await panelPage.locator('#editor').inputValue(); + expect(editorValue).toContain('click "Submit"'); +}); + // ─── Theme ───────────────────────────────────────────────────────────────── test('applies dark theme based on color scheme', async ({ panelPage }) => { diff --git a/packages/extension/manifest.json b/packages/extension/manifest.json index 739aa4d..c36a680 100644 --- a/packages/extension/manifest.json +++ b/packages/extension/manifest.json @@ -6,7 +6,9 @@ "permissions": [ "activeTab", "tabs", - "sidePanel" + "sidePanel", + "scripting", + "webNavigation" ], "host_permissions": [ "" diff --git a/packages/extension/panel/panel.js b/packages/extension/panel/panel.js index 88fb4e1..90e837c 100644 --- a/packages/extension/panel/panel.js +++ b/packages/extension/panel/panel.js @@ -883,10 +883,50 @@ copyBtn.addEventListener("click", () => { consoleClearBtn.addEventListener("click", clearConsole); -// --- Record button (deferred — recording not yet supported in v3) --- +// --- Record button --- -recordBtn.disabled = true; -recordBtn.title = "Recording not available in side panel mode"; +let isRecording = false; + +recordBtn.addEventListener("click", async () => { + if (isRecording) { + // Stop recording + const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + if (tab) { + chrome.runtime.sendMessage({ type: "pw-record-stop", tabId: tab.id }); + } + recordBtn.classList.remove("recording"); + recordBtn.textContent = "Record"; + recordBtn.title = "Start recording user interactions"; + isRecording = false; + addInfo("Recording stopped"); + } else { + // Start recording + const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + if (!tab) { + addError("No active tab found"); + return; + } + const result = await chrome.runtime.sendMessage({ type: "pw-record-start", tabId: tab.id }); + if (result && !result.ok) { + addError("Recording failed: " + (result.error || "unknown error")); + return; + } + recordBtn.classList.add("recording"); + recordBtn.textContent = "Stop"; + recordBtn.title = "Stop recording"; + isRecording = true; + addInfo("Recording on " + (tab.title || tab.url)); + } +}); + +// --- Receive recorded commands from content script --- + +chrome.runtime.onMessage.addListener((msg) => { + if (msg.type === "pw-recorded-command" && msg.command) { + addCommand(msg.command); + appendToEditor(msg.command); + } +}); // --- Draggable splitter --- diff --git a/packages/extension/test/background.test.js b/packages/extension/test/background.test.js new file mode 100644 index 0000000..5d84fa0 --- /dev/null +++ b/packages/extension/test/background.test.js @@ -0,0 +1,283 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +describe("background.js recording handlers", () => { + let startRecording, stopRecording, injectRecorder; + + beforeEach(async () => { + vi.restoreAllMocks(); + vi.resetModules(); + + // Mock chrome.scripting.executeScript + chrome.scripting = { + executeScript: vi.fn().mockResolvedValue([]), + }; + + // Mock chrome.tabs.onUpdated + chrome.tabs.onUpdated = { + addListener: vi.fn(), + removeListener: vi.fn(), + }; + + // Mock chrome.tabs.onActivated + chrome.tabs.onActivated = { + addListener: vi.fn(), + }; + + // Mock chrome.tabs.get — must return a tab object with url + chrome.tabs.get = vi.fn().mockResolvedValue({ id: 42, url: "https://example.com", title: "Example" }); + + // Mock chrome.webNavigation.onCommitted + chrome.webNavigation = { + onCommitted: { + addListener: vi.fn(), + removeListener: vi.fn(), + }, + }; + + const bg = await import("../background.js"); + startRecording = bg.startRecording; + stopRecording = bg.stopRecording; + injectRecorder = bg.injectRecorder; + }); + + // ─── startRecording ───────────────────────────────────────────────────── + + it("injects recorder.js into the tab", async () => { + const result = await startRecording(42); + expect(result).toEqual({ ok: true }); + expect(chrome.scripting.executeScript).toHaveBeenCalledWith({ + target: { tabId: 42 }, + files: ["content/recorder.js"], + }); + }); + + it("adds tabs.onUpdated and webNavigation.onCommitted listeners", async () => { + await startRecording(42); + expect(chrome.tabs.onUpdated.addListener).toHaveBeenCalledWith( + expect.any(Function), + ); + expect(chrome.webNavigation.onCommitted.addListener).toHaveBeenCalledWith( + expect.any(Function), + ); + }); + + it("returns error on injection failure", async () => { + chrome.scripting.executeScript.mockRejectedValue( + new Error("Cannot access chrome:// URLs"), + ); + const result = await startRecording(42); + expect(result).toEqual({ ok: false, error: "Cannot access chrome:// URLs" }); + }); + + // ─── stopRecording ────────────────────────────────────────────────────── + + it("runs cleanup on the tab", async () => { + await startRecording(42); + const result = await stopRecording(42); + expect(result).toEqual({ ok: true }); + // Second call to executeScript is the cleanup + expect(chrome.scripting.executeScript).toHaveBeenCalledTimes(2); + const cleanupCall = chrome.scripting.executeScript.mock.calls[1][0]; + expect(cleanupCall.target).toEqual({ tabId: 42 }); + expect(typeof cleanupCall.func).toBe("function"); + }); + + it("removes tabs.onUpdated and webNavigation.onCommitted listeners", async () => { + await startRecording(42); + await stopRecording(42); + expect(chrome.tabs.onUpdated.removeListener).toHaveBeenCalledWith( + expect.any(Function), + ); + expect(chrome.webNavigation.onCommitted.removeListener).toHaveBeenCalledWith( + expect.any(Function), + ); + }); + + it("handles cleanup failure gracefully", async () => { + await startRecording(42); + // Make cleanup fail + chrome.scripting.executeScript.mockRejectedValueOnce( + new Error("Tab closed"), + ); + const result = await stopRecording(42); + // Should still return ok (non-fatal) + expect(result).toEqual({ ok: true }); + }); + + // ─── onTabUpdated re-injection ────────────────────────────────────────── + + it("re-injects recorder on tab navigation (status complete)", async () => { + await startRecording(42); + // Get the onUpdated listener that was registered + const listener = chrome.tabs.onUpdated.addListener.mock.calls[0][0]; + chrome.scripting.executeScript.mockClear(); + // Simulate navigation complete + listener(42, { status: "complete" }); + // Wait for the async injection + await vi.waitFor(() => { + expect(chrome.scripting.executeScript).toHaveBeenCalledWith({ + target: { tabId: 42 }, + files: ["content/recorder.js"], + }); + }); + }); + + it("does not re-inject for non-complete status", async () => { + await startRecording(42); + const listener = chrome.tabs.onUpdated.addListener.mock.calls[0][0]; + chrome.scripting.executeScript.mockClear(); + // Simulate loading status (not complete) + listener(42, { status: "loading" }); + expect(chrome.scripting.executeScript).not.toHaveBeenCalled(); + }); + + it("does not re-inject for a different tab", async () => { + await startRecording(42); + const listener = chrome.tabs.onUpdated.addListener.mock.calls[0][0]; + chrome.scripting.executeScript.mockClear(); + // Simulate navigation on a different tab + listener(99, { status: "complete" }); + expect(chrome.scripting.executeScript).not.toHaveBeenCalled(); + }); + + // ─── webNavigation.onCommitted — goto, go-back, go-forward ───────── + + it("emits goto when user types URL in address bar", async () => { + chrome.runtime.sendMessage = vi.fn().mockResolvedValue(undefined); + await startRecording(42); + const navListener = chrome.webNavigation.onCommitted.addListener.mock.calls[0][0]; + + navListener({ + tabId: 42, frameId: 0, url: "https://new-url.com", + transitionType: "typed", transitionQualifiers: ["from_address_bar"], + }); + + expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: "goto https://new-url.com", + }); + }); + + it("does not emit goto for link click navigations", async () => { + chrome.runtime.sendMessage = vi.fn().mockResolvedValue(undefined); + await startRecording(42); + const navListener = chrome.webNavigation.onCommitted.addListener.mock.calls[0][0]; + + navListener({ + tabId: 42, frameId: 0, url: "https://linked-page.com", + transitionType: "link", transitionQualifiers: [], + }); + + expect(chrome.runtime.sendMessage).not.toHaveBeenCalledWith( + expect.objectContaining({ type: "pw-recorded-command" }), + ); + }); + + it("does not emit for same URL", async () => { + chrome.runtime.sendMessage = vi.fn().mockResolvedValue(undefined); + await startRecording(42); + const navListener = chrome.webNavigation.onCommitted.addListener.mock.calls[0][0]; + + navListener({ + tabId: 42, frameId: 0, url: "https://example.com", + transitionType: "typed", transitionQualifiers: [], + }); + + expect(chrome.runtime.sendMessage).not.toHaveBeenCalledWith( + expect.objectContaining({ type: "pw-recorded-command" }), + ); + }); + + it("ignores navigations from a different tab", async () => { + chrome.runtime.sendMessage = vi.fn().mockResolvedValue(undefined); + await startRecording(42); + const navListener = chrome.webNavigation.onCommitted.addListener.mock.calls[0][0]; + + navListener({ + tabId: 99, frameId: 0, url: "https://other.com", + transitionType: "typed", transitionQualifiers: [], + }); + + expect(chrome.runtime.sendMessage).not.toHaveBeenCalledWith( + expect.objectContaining({ type: "pw-recorded-command" }), + ); + }); + + it("ignores subframe navigations", async () => { + chrome.runtime.sendMessage = vi.fn().mockResolvedValue(undefined); + await startRecording(42); + const navListener = chrome.webNavigation.onCommitted.addListener.mock.calls[0][0]; + + navListener({ + tabId: 42, frameId: 1, url: "https://iframe.com", + transitionType: "typed", transitionQualifiers: [], + }); + + expect(chrome.runtime.sendMessage).not.toHaveBeenCalledWith( + expect.objectContaining({ type: "pw-recorded-command" }), + ); + }); + + it("emits go-back on back button navigation", async () => { + chrome.runtime.sendMessage = vi.fn().mockResolvedValue(undefined); + await startRecording(42); + const navListener = chrome.webNavigation.onCommitted.addListener.mock.calls[0][0]; + + // First navigate somewhere via address bar + navListener({ + tabId: 42, frameId: 0, url: "https://page2.com", + transitionType: "typed", transitionQualifiers: ["from_address_bar"], + }); + chrome.runtime.sendMessage.mockClear(); + + // Then press back — URL goes back to example.com + navListener({ + tabId: 42, frameId: 0, url: "https://example.com", + transitionType: "link", transitionQualifiers: ["forward_back"], + }); + + expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: "go-back", + }); + }); + + it("emits go-forward on forward button navigation", async () => { + chrome.runtime.sendMessage = vi.fn().mockResolvedValue(undefined); + await startRecording(42); + const navListener = chrome.webNavigation.onCommitted.addListener.mock.calls[0][0]; + + // Navigate somewhere + navListener({ + tabId: 42, frameId: 0, url: "https://page2.com", + transitionType: "typed", transitionQualifiers: ["from_address_bar"], + }); + // Go back + navListener({ + tabId: 42, frameId: 0, url: "https://example.com", + transitionType: "link", transitionQualifiers: ["forward_back"], + }); + chrome.runtime.sendMessage.mockClear(); + + // Go forward — URL returns to page2.com + navListener({ + tabId: 42, frameId: 0, url: "https://page2.com", + transitionType: "link", transitionQualifiers: ["forward_back"], + }); + + expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: "go-forward", + }); + }); + + // ─── injectRecorder ──────────────────────────────────────────────────── + + it("calls chrome.scripting.executeScript with correct args", async () => { + await injectRecorder(99); + expect(chrome.scripting.executeScript).toHaveBeenCalledWith({ + target: { tabId: 99 }, + files: ["content/recorder.js"], + }); + }); +}); diff --git a/packages/extension/test/panel.test.js b/packages/extension/test/panel.test.js index f539933..686190b 100644 --- a/packages/extension/test/panel.test.js +++ b/packages/extension/test/panel.test.js @@ -127,9 +127,9 @@ describe("panel.js", () => { expect(document.getElementById("open-btn").disabled).toBe(false); }); - it("record button is disabled in side panel mode", async () => { + it("record button is enabled", async () => { await import("../panel/panel.js"); - expect(document.getElementById("record-btn").disabled).toBe(true); + expect(document.getElementById("record-btn").disabled).toBe(false); }); // --- Theme --- diff --git a/packages/extension/test/recorder.test.js b/packages/extension/test/recorder.test.js new file mode 100644 index 0000000..9e50733 --- /dev/null +++ b/packages/extension/test/recorder.test.js @@ -0,0 +1,492 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; + +describe("recorder.js", () => { + let sendMessageSpy; + + beforeEach(() => { + vi.restoreAllMocks(); + vi.resetModules(); + vi.useFakeTimers(); + + // Clear recorder state + delete document.documentElement.dataset.pwRecorderActive; + delete window.__pwRecorderCleanup; + + // Mock chrome.runtime.sendMessage + sendMessageSpy = vi.fn(); + globalThis.chrome = { + runtime: { sendMessage: sendMessageSpy }, + }; + }); + + afterEach(() => { + // Clean up recorder if still active + if (typeof window.__pwRecorderCleanup === "function") { + window.__pwRecorderCleanup(); + } + vi.useRealTimers(); + }); + + async function loadRecorder() { + await import("../content/recorder.js"); + } + + // ─── Initialization ───────────────────────────────────────────────────── + + it("sets dataset.pwRecorderActive on load", async () => { + await loadRecorder(); + expect(document.documentElement.dataset.pwRecorderActive).toBe("true"); + }); + + it("provides __pwRecorderCleanup function", async () => { + await loadRecorder(); + expect(typeof window.__pwRecorderCleanup).toBe("function"); + }); + + it("is idempotent — does not run twice", async () => { + await loadRecorder(); + const firstCleanup = window.__pwRecorderCleanup; + await import("../content/recorder.js"); + expect(window.__pwRecorderCleanup).toBe(firstCleanup); + }); + + // ─── Click ────────────────────────────────────────────────────────────── + + it("records click on a button", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + document.querySelector("button").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'click "Submit"', + }); + }); + + it("records click on a link", async () => { + document.body.innerHTML = 'Learn more'; + await loadRecorder(); + document.querySelector("a").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'click "Learn more"', + }); + }); + + it("skips clicks on non-interactive containers (div, section)", async () => { + document.body.innerHTML = '
content
'; + await loadRecorder(); + document.querySelector("#container").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).not.toHaveBeenCalled(); + }); + + it("uses aria-label for locator when available", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + document.querySelector("button").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'click "Close dialog"', + }); + }); + + it("uses label[for] for locator", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + document.querySelector("input").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith( + expect.objectContaining({ type: "pw-recorded-command" }), + ); + }); + + it("uses placeholder for locator", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + // placeholder is not standard on buttons, so textContent takes priority + document.querySelector("button").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'click "Search..."', + }); + }); + + it("uses title as fallback locator", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + document.querySelector("span").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'click "Info tooltip"', + }); + }); + + it("falls back to tagName locator", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + document.querySelector("span").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'click "span"', + }); + }); + + it("skips click on text input (handled by fill)", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + document.querySelector("input").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).not.toHaveBeenCalled(); + }); + + it("skips click on textarea (handled by fill)", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + document.querySelector("textarea").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).not.toHaveBeenCalled(); + }); + + it("records click on div with role attribute", async () => { + document.body.innerHTML = '
Custom Button
'; + await loadRecorder(); + document.querySelector("div").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'click "Custom Button"', + }); + }); + + it("escapes quotes in locator text", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + document.querySelector("button").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'click "Say \\"Hello\\""', + }); + }); + + it("falls through long text (>80 chars) to title", async () => { + const longText = "A".repeat(100); + document.body.innerHTML = `${longText}`; + await loadRecorder(); + document.querySelector("span").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'click "Short title"', + }); + }); + + it("uses parent label text for locator", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + document.querySelector("span").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'click "Username icon"', + }); + }); + + // ─── Checkbox ─────────────────────────────────────────────────────────── + + it("records check command on checkbox", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + const cb = document.querySelector("input"); + // click() toggles unchecked → checked, handler reads checked=true + cb.click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'check "Accept terms"', + }); + }); + + it("records uncheck command on checkbox", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + const cb = document.querySelector("input"); + // click() toggles checked → unchecked, handler reads checked=false + cb.click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'uncheck "Accept terms"', + }); + }); + + it("detects checkbox via parent label", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + const cb = document.querySelector("input"); + cb.checked = true; + document.querySelector("label").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith( + expect.objectContaining({ + type: "pw-recorded-command", + command: expect.stringContaining("check"), + }), + ); + }); + + // ─── Input / Fill ─────────────────────────────────────────────────────── + + it("records debounced fill command on input", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + const el = document.querySelector("input"); + el.value = "alice"; + el.dispatchEvent(new Event("input", { bubbles: true })); + // Should not fire immediately + expect(sendMessageSpy).not.toHaveBeenCalled(); + // After debounce + vi.advanceTimersByTime(1500); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'fill "Username" "alice"', + }); + }); + + it("click flushes pending fill immediately", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + const el = document.querySelector("input"); + el.value = "test@example.com"; + el.dispatchEvent(new Event("input", { bubbles: true })); + // Click before debounce timeout + document.querySelector("button").click(); + vi.advanceTimersByTime(300); + const calls = sendMessageSpy.mock.calls.map((c) => c[0]); + const fillCall = calls.find((c) => c.command && c.command.startsWith("fill")); + const clickCall = calls.find((c) => c.command && c.command.startsWith("click")); + expect(fillCall).toBeDefined(); + expect(clickCall).toBeDefined(); + }); + + it("records fill on textarea", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + const el = document.querySelector("textarea"); + el.value = "Great product!"; + el.dispatchEvent(new Event("input", { bubbles: true })); + vi.advanceTimersByTime(1500); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'fill "Comments" "Great product!"', + }); + }); + + it("resets debounce timer on continued typing", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + const el = document.querySelector("input"); + el.value = "hel"; + el.dispatchEvent(new Event("input", { bubbles: true })); + vi.advanceTimersByTime(1000); + // Still typing — should not have flushed yet + expect(sendMessageSpy).not.toHaveBeenCalled(); + el.value = "hello"; + el.dispatchEvent(new Event("input", { bubbles: true })); + vi.advanceTimersByTime(1000); + // Timer reset — still waiting + expect(sendMessageSpy).not.toHaveBeenCalled(); + vi.advanceTimersByTime(500); + // Now 1500ms since last input + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'fill "Search" "hello"', + }); + }); + + it("escapes quotes in fill value", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + const el = document.querySelector("input"); + el.value = 'John "Doe"'; + el.dispatchEvent(new Event("input", { bubbles: true })); + vi.advanceTimersByTime(1500); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'fill "Name" "John \\"Doe\\""', + }); + }); + + it("does not record fill for radio inputs", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + const el = document.querySelector("input"); + el.dispatchEvent(new Event("input", { bubbles: true })); + vi.advanceTimersByTime(1500); + const fillCalls = sendMessageSpy.mock.calls.filter( + (c) => c[0].command && c[0].command.startsWith("fill"), + ); + expect(fillCalls).toHaveLength(0); + }); + + it("does not record fill for checkbox inputs", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + const el = document.querySelector("input"); + el.dispatchEvent(new Event("input", { bubbles: true })); + vi.advanceTimersByTime(1500); + const fillCalls = sendMessageSpy.mock.calls.filter( + (c) => c[0].command && c[0].command.startsWith("fill"), + ); + expect(fillCalls).toHaveLength(0); + }); + + // ─── Select ───────────────────────────────────────────────────────────── + + it("records select command on dropdown", async () => { + document.body.innerHTML = ` + `; + await loadRecorder(); + const sel = document.querySelector("select"); + sel.selectedIndex = 1; + sel.dispatchEvent(new Event("change", { bubbles: true })); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'select "Color" "Blue"', + }); + }); + + // ─── Keydown ──────────────────────────────────────────────────────────── + + it("records press Enter", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + document.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: "press Enter", + }); + }); + + it("records press Tab", async () => { + await loadRecorder(); + document.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true })); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: "press Tab", + }); + }); + + it("records press Escape", async () => { + await loadRecorder(); + document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: "press Escape", + }); + }); + + it("does not record regular key presses", async () => { + await loadRecorder(); + document.dispatchEvent(new KeyboardEvent("keydown", { key: "a", bubbles: true })); + expect(sendMessageSpy).not.toHaveBeenCalled(); + }); + + it("keydown flushes pending fill", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + const el = document.querySelector("input"); + el.value = "hello"; + el.dispatchEvent(new Event("input", { bubbles: true })); + document.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + const calls = sendMessageSpy.mock.calls.map((c) => c[0]); + expect(calls.find((c) => c.command === 'fill "Search" "hello"')).toBeDefined(); + expect(calls.find((c) => c.command === "press Enter")).toBeDefined(); + }); + + // ─── Double-click ─────────────────────────────────────────────────────── + + it("records dblclick and suppresses single click", async () => { + document.body.innerHTML = 'Edit'; + await loadRecorder(); + const el = document.querySelector("span"); + // Simulate browser's click → dblclick sequence + el.dispatchEvent(new MouseEvent("click", { bubbles: true })); + el.dispatchEvent(new MouseEvent("dblclick", { bubbles: true })); + vi.advanceTimersByTime(300); + const commands = sendMessageSpy.mock.calls.map((c) => c[0].command); + expect(commands).toContain('dblclick "Edit"'); + expect(commands).not.toContain('click "Edit"'); + }); + + // ─── Context menu (right-click) ───────────────────────────────────────── + + it("records right-click as click --button right", async () => { + document.body.innerHTML = 'Item'; + await loadRecorder(); + const el = document.querySelector("span"); + el.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true })); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'click "Item" --button right', + }); + }); + + // ─── Action button with item context ──────────────────────────────────── + + it("includes item context for action buttons in a list", async () => { + document.body.innerHTML = ` +
    +
  • Buy milk
  • +
`; + await loadRecorder(); + document.querySelector("button").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'click "delete" "Buy milk"', + }); + }); + + // ─── Cleanup ──────────────────────────────────────────────────────────── + + it("cleanup removes listeners and dataset", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + expect(document.documentElement.dataset.pwRecorderActive).toBe("true"); + + window.__pwRecorderCleanup(); + + expect(document.documentElement.dataset.pwRecorderActive).toBeUndefined(); + expect(window.__pwRecorderCleanup).toBeUndefined(); + + // Events should no longer be captured + sendMessageSpy.mockClear(); + document.querySelector("button").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).not.toHaveBeenCalled(); + }); + + it("cleanup flushes pending fill", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + const el = document.querySelector("input"); + el.value = "Bob"; + el.dispatchEvent(new Event("input", { bubbles: true })); + // Cleanup before debounce + window.__pwRecorderCleanup(); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'fill "Name" "Bob"', + }); + }); +}); diff --git a/packages/extension/test/setup.js b/packages/extension/test/setup.js index bd35de7..96f74a4 100644 --- a/packages/extension/test/setup.js +++ b/packages/extension/test/setup.js @@ -2,3 +2,27 @@ import * as chrome from "vitest-chrome/lib/index.esm.js"; // Add chrome object to global scope so imported modules can use it Object.assign(global, chrome); + +// vitest-chrome doesn't include chrome.scripting — add it manually +if (!globalThis.chrome.scripting) { + globalThis.chrome.scripting = { + executeScript: async () => [], + }; +} + +// vitest-chrome doesn't include chrome.sidePanel — add it manually +if (!globalThis.chrome.sidePanel) { + globalThis.chrome.sidePanel = { + setPanelBehavior: () => {}, + }; +} + +// vitest-chrome doesn't include chrome.webNavigation — add it manually +if (!globalThis.chrome.webNavigation) { + globalThis.chrome.webNavigation = { + onCommitted: { + addListener: () => {}, + removeListener: () => {}, + }, + }; +} diff --git a/packages/extension/vitest.config.js b/packages/extension/vitest.config.js index 986afd3..1021876 100644 --- a/packages/extension/vitest.config.js +++ b/packages/extension/vitest.config.js @@ -7,7 +7,7 @@ export default defineConfig({ exclude: ["e2e/**", "node_modules/**"], coverage: { provider: "v8", - include: ["lib/**/*.js", "panel/**/*.js", "background.js"], + include: ["lib/**/*.js", "panel/**/*.js", "content/**/*.js", "background.js"], reporter: ["text", "html"], }, }, From 8d069a14b0d752fe2bbce8959cd9a49bcd9a2901 Mon Sep 17 00:00:00 2001 From: Steve Zhang Date: Sat, 21 Feb 2026 15:34:12 -0500 Subject: [PATCH 16/27] fix: resolve strict mode violations with --nth and skip non-interactive clicks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Recorder now checks if a text locator matches multiple interactive elements. When ambiguous, appends --nth N to disambiguate (e.g. click "Learn more" --nth 1). The --nth flag flows through parser → resolveArgs → buildRunCode → actionByText/fillByText/etc. which chains .nth(n) onto the Playwright locator before acting. Also replaces the blocklist (skipTags) with an allowlist (isClickable) that only records clicks on interactive elements (a, button, input, select, [role=button], etc.) or their children. Prevents accidental recording of clicks on plain text, headings, and paragraphs. Co-Authored-By: Claude Opus 4.6 --- packages/cli/src/repl.mjs | 10 ++- packages/core/src/extension-server.mjs | 7 +- packages/core/src/page-scripts.mjs | 30 +++++-- packages/core/test/page-scripts.test.mjs | 37 ++++++++ packages/extension/content/recorder.js | 65 +++++++++++--- packages/extension/test/recorder.test.js | 103 +++++++++++++++++++++++ 6 files changed, 223 insertions(+), 29 deletions(-) diff --git a/packages/cli/src/repl.mjs b/packages/cli/src/repl.mjs index 887cce5..123ebb3 100644 --- a/packages/cli/src/repl.mjs +++ b/packages/cli/src/repl.mjs @@ -260,12 +260,14 @@ export async function processLine(ctx, line) { const textArg = args._[1]; const extraArgs = args._.slice(2); const fn = textFns[cmdName]; + const nth = args.nth !== undefined ? parseInt(args.nth, 10) : undefined; let runCodeArgs; - if (fn === actionByText) runCodeArgs = buildRunCode(fn, textArg, cmdName); - else if (cmdName === 'fill' || cmdName === 'select') runCodeArgs = buildRunCode(fn, textArg, extraArgs[0] || ''); - else runCodeArgs = buildRunCode(fn, textArg); + if (fn === actionByText) runCodeArgs = buildRunCode(fn, textArg, cmdName, nth); + else if (cmdName === 'fill' || cmdName === 'select') runCodeArgs = buildRunCode(fn, textArg, extraArgs[0] || '', nth); + else runCodeArgs = buildRunCode(fn, textArg, nth); const argsHint = extraArgs.length > 0 ? ` ${extraArgs.join(' ')}` : ''; - ctx.log(`${c.dim}→ ${cmdName} "${textArg}"${argsHint} (via run-code)${c.reset}`); + const nthHint = nth !== undefined ? ` --nth ${nth}` : ''; + ctx.log(`${c.dim}→ ${cmdName} "${textArg}"${argsHint}${nthHint} (via run-code)${c.reset}`); args = runCodeArgs; } diff --git a/packages/core/src/extension-server.mjs b/packages/core/src/extension-server.mjs index bfc94df..191e759 100644 --- a/packages/core/src/extension-server.mjs +++ b/packages/core/src/extension-server.mjs @@ -142,9 +142,10 @@ function resolveArgs(args) { const textArg = args._[1]; const extraArgs = args._.slice(2); const fn = textFns[cmdName]; - if (fn === actionByText) args = buildRunCode(fn, textArg, cmdName); - else if (cmdName === 'fill' || cmdName === 'select') args = buildRunCode(fn, textArg, extraArgs[0] || ''); - else args = buildRunCode(fn, textArg); + const nth = args.nth !== undefined ? parseInt(args.nth, 10) : undefined; + if (fn === actionByText) args = buildRunCode(fn, textArg, cmdName, nth); + else if (cmdName === 'fill' || cmdName === 'select') args = buildRunCode(fn, textArg, extraArgs[0] || '', nth); + else args = buildRunCode(fn, textArg, nth); } // ── go-back / go-forward → evaluate history.back/forward ── diff --git a/packages/core/src/page-scripts.mjs b/packages/core/src/page-scripts.mjs index 0073079..2ad23bc 100644 --- a/packages/core/src/page-scripts.mjs +++ b/packages/core/src/page-scripts.mjs @@ -16,7 +16,8 @@ * So `code` must be a function expression, not an IIFE. */ export function buildRunCode(fn, ...args) { - const serialized = args.map(a => JSON.stringify(a)).join(', '); + const filtered = args.filter(a => a !== undefined); + const serialized = filtered.map(a => JSON.stringify(a)).join(', '); return { _: ['run-code', `async (page) => (${fn.toString()})(page, ${serialized})`] }; } @@ -49,39 +50,52 @@ export async function verifyList(page, ref, items) { // ─── Text locator actions ─────────────────────────────────────────────────── -export async function actionByText(page, text, action) { +export async function actionByText(page, text, action, nth) { let loc = page.getByText(text, { exact: true }); if (await loc.count() === 0) loc = page.getByRole('button', { name: text }); if (await loc.count() === 0) loc = page.getByRole('link', { name: text }); if (await loc.count() === 0) loc = page.getByText(text); + if (nth !== undefined) loc = loc.nth(nth); await loc[action](); } -export async function fillByText(page, text, value) { +export async function fillByText(page, text, value, nth) { let loc = page.getByLabel(text); if (await loc.count() === 0) loc = page.getByPlaceholder(text); if (await loc.count() === 0) loc = page.getByRole('textbox', { name: text }); + if (nth !== undefined) loc = loc.nth(nth); await loc.fill(value); } -export async function selectByText(page, text, value) { +export async function selectByText(page, text, value, nth) { let loc = page.getByLabel(text); if (await loc.count() === 0) loc = page.getByRole('combobox', { name: text }); + if (nth !== undefined) loc = loc.nth(nth); await loc.selectOption(value); } -export async function checkByText(page, text) { +export async function checkByText(page, text, nth) { const item = page.getByRole('listitem').filter({ hasText: text }); - if (await item.count() > 0) { await item.getByRole('checkbox').check(); return; } + if (await item.count() > 0) { + const target = nth !== undefined ? item.nth(nth) : item; + await target.getByRole('checkbox').check(); + return; + } let loc = page.getByLabel(text); if (await loc.count() === 0) loc = page.getByRole('checkbox', { name: text }); + if (nth !== undefined) loc = loc.nth(nth); await loc.check(); } -export async function uncheckByText(page, text) { +export async function uncheckByText(page, text, nth) { const item = page.getByRole('listitem').filter({ hasText: text }); - if (await item.count() > 0) { await item.getByRole('checkbox').uncheck(); return; } + if (await item.count() > 0) { + const target = nth !== undefined ? item.nth(nth) : item; + await target.getByRole('checkbox').uncheck(); + return; + } let loc = page.getByLabel(text); if (await loc.count() === 0) loc = page.getByRole('checkbox', { name: text }); + if (nth !== undefined) loc = loc.nth(nth); await loc.uncheck(); } diff --git a/packages/core/test/page-scripts.test.mjs b/packages/core/test/page-scripts.test.mjs index c0d9d50..8a981df 100644 --- a/packages/core/test/page-scripts.test.mjs +++ b/packages/core/test/page-scripts.test.mjs @@ -35,6 +35,18 @@ describe('buildRunCode', () => { expect(result._[1]).toContain('["item1","item2"]'); }); + it('filters out undefined args', () => { + const result = buildRunCode(actionByText, 'Submit', 'click', undefined); + expect(result._[1]).toContain('(page, "Submit", "click")'); + // Args should end with just the three values, no trailing undefined/comma + expect(result._[1]).toMatch(/\(page, "Submit", "click"\)$/); + }); + + it('includes nth arg when defined', () => { + const result = buildRunCode(actionByText, 'Submit', 'click', 2); + expect(result._[1]).toContain('(page, "Submit", "click", 2)'); + }); + it('produces code callable as (code)(page) by daemon', async () => { const result = buildRunCode(verifyText, 'hello'); const code = result._[1]; @@ -155,6 +167,31 @@ describe('actionByText', () => { await actionByText(page, 'Menu', 'hover'); expect(page._loc.hover).toHaveBeenCalled(); }); + + it('chains .nth() when nth is provided', async () => { + const nthLoc = mockLocator(1); + const loc = mockLocator(3); + loc.nth = vi.fn().mockReturnValue(nthLoc); + const page = { + getByText: vi.fn().mockReturnValue(loc), + getByRole: vi.fn().mockReturnValue(loc), + }; + await actionByText(page, 'Learn more', 'click', 1); + expect(loc.nth).toHaveBeenCalledWith(1); + expect(nthLoc.click).toHaveBeenCalled(); + }); + + it('does not chain .nth() when nth is undefined', async () => { + const loc = mockLocator(1); + loc.nth = vi.fn(); + const page = { + getByText: vi.fn().mockReturnValue(loc), + getByRole: vi.fn().mockReturnValue(loc), + }; + await actionByText(page, 'Submit', 'click'); + expect(loc.nth).not.toHaveBeenCalled(); + expect(loc.click).toHaveBeenCalled(); + }); }); describe('fillByText', () => { diff --git a/packages/extension/content/recorder.js b/packages/extension/content/recorder.js index d1c2c4f..90a95d6 100644 --- a/packages/extension/content/recorder.js +++ b/packages/extension/content/recorder.js @@ -49,6 +49,25 @@ return '"' + s.replace(/"/g, '\\"') + '"'; } + // Check if the locator text matches multiple interactive elements on the page. + // Returns ' --nth N' suffix if ambiguous, '' if unique. + function nthSuffix(el, locator) { + var selector = 'a, button, input, textarea, select, [role=button], [role=link], [role=tab], [role=menuitem], [role=checkbox], [role=option], [aria-label]'; + var candidates = document.querySelectorAll(selector); + var matches = []; + for (var i = 0; i < candidates.length; i++) { + if (getLocator(candidates[i]) === locator) matches.push(candidates[i]); + } + if (matches.length <= 1) return ''; + var idx = matches.indexOf(el); + if (idx === -1) { + for (var j = 0; j < matches.length; j++) { + if (matches[j].contains(el)) { idx = j; break; } + } + } + return idx >= 0 ? ' --nth ' + idx : ''; + } + function send(command) { chrome.runtime.sendMessage({ type: "pw-recorded-command", command }); } @@ -60,15 +79,28 @@ function flushFill() { if (fillTarget && fillValue) { const locator = getLocator(fillTarget); - send('fill ' + locator + ' "' + fillValue.replace(/"/g, '\\"') + '"'); + send('fill ' + locator + nthSuffix(fillTarget, locator) + ' "' + fillValue.replace(/"/g, '\\"') + '"'); } fillTimer = null; fillTarget = null; fillValue = ""; } - // Elements that are non-interactive containers — skip recording clicks on these - var skipTags = new Set(["HTML", "BODY", "MAIN", "FOOTER", "HEADER", "NAV", "SECTION", "ARTICLE", "DIV", "UL", "OL", "FORM", "FIELDSET", "TABLE", "TBODY", "THEAD", "TR"]); + // Only record clicks on interactive elements (or their children) + var clickableTags = new Set(["A", "BUTTON", "INPUT", "SELECT", "TEXTAREA", "SUMMARY", "DETAILS"]); + var clickableRoles = new Set(["button", "link", "tab", "menuitem", "checkbox", "option", "switch", "radio", "treeitem"]); + + function isClickable(el) { + var node = el; + while (node && node !== document.body) { + if (clickableTags.has(node.tagName)) return true; + var role = node.getAttribute && node.getAttribute("role"); + if (role && clickableRoles.has(role)) return true; + if (node.getAttribute && node.getAttribute("onclick")) return true; + node = node.parentElement; + } + return false; + } function findCheckbox(el) { if (el.tagName === "INPUT" && el.type === "checkbox") return el; @@ -98,8 +130,8 @@ // Skip text inputs and textareas — handled by handleInput if ((el.tagName === "INPUT" && el.type !== "checkbox" && el.type !== "radio") || el.tagName === "TEXTAREA") return; - // Skip clicks on non-interactive container elements - if (skipTags.has(el.tagName) && !el.getAttribute("role") && !el.getAttribute("onclick")) return; + // Skip clicks on non-interactive elements + if (!isClickable(el)) return; // Links: emit immediately (page navigates before debounce timer fires) if (el.closest && el.closest("a[href]")) { @@ -130,15 +162,19 @@ if (checkbox) { var cbLabel = getItemContext(checkbox) || ""; if (cbLabel) { - send(checkbox.checked ? 'check "' + cbLabel + '"' : 'uncheck "' + cbLabel + '"'); + var cbLocator = quote(cbLabel); + var cbNth = nthSuffix(checkbox, cbLocator); + send(checkbox.checked ? 'check ' + cbLocator + cbNth : 'uncheck ' + cbLocator + cbNth); } else { var loc = getLocator(checkbox); - send(checkbox.checked ? 'check ' + loc : 'uncheck ' + loc); + var locNth = nthSuffix(checkbox, loc); + send(checkbox.checked ? 'check ' + loc + locNth : 'uncheck ' + loc + locNth); } return; } var locator = getLocator(el); + var nth = nthSuffix(el, locator); var actionWords = new Set(["delete", "remove", "edit", "close", "destroy", "\u00d7", "\u2715", "\u2716", "\u2717", "\u2718", "x"]); var elText = (el.textContent || "").trim().toLowerCase(); var elClass = (el.className || "").toLowerCase(); @@ -152,10 +188,10 @@ if (ctx && isAction) { send('click ' + locator + ' "' + ctx.replace(/"/g, '\\"') + '"'); } else { - send('click ' + locator); + send('click ' + locator + nth); } } catch(ce) { - send('click ' + locator); + send('click ' + locator + nth); } } catch(err) { send("# click recording error: " + err.message); @@ -169,9 +205,9 @@ if (fillTimer) { clearTimeout(fillTimer); flushFill(); } var el = e.target; if (!el || !el.tagName) return; - if (skipTags.has(el.tagName) && !el.getAttribute("role") && !el.getAttribute("onclick")) return; + if (!isClickable(el)) return; var locator = getLocator(el); - send('dblclick ' + locator); + send('dblclick ' + locator + nthSuffix(el, locator)); } catch(err) { send("# dblclick recording error: " + err.message); } @@ -181,9 +217,9 @@ try { var el = e.target; if (!el || !el.tagName) return; - if (skipTags.has(el.tagName) && !el.getAttribute("role") && !el.getAttribute("onclick")) return; + if (!isClickable(el)) return; var locator = getLocator(el); - send('click ' + locator + ' --button right'); + send('click ' + locator + nthSuffix(el, locator) + ' --button right'); } catch(err) { send("# contextmenu recording error: " + err.message); } @@ -204,7 +240,8 @@ if (el.tagName === "SELECT") { const opt = el.options[el.selectedIndex]; const optText = opt ? opt.text.trim() : el.value; - send('select ' + getLocator(el) + ' "' + optText.replace(/"/g, '\\"') + '"'); + const locator = getLocator(el); + send('select ' + locator + nthSuffix(el, locator) + ' "' + optText.replace(/"/g, '\\"') + '"'); } } diff --git a/packages/extension/test/recorder.test.js b/packages/extension/test/recorder.test.js index 9e50733..acbe7b7 100644 --- a/packages/extension/test/recorder.test.js +++ b/packages/extension/test/recorder.test.js @@ -198,6 +198,109 @@ describe("recorder.js", () => { }); }); + // ─── Non-interactive elements (isClickable) ──────────────────────────── + + it("skips clicks on plain span without role", async () => { + document.body.innerHTML = 'just text'; + await loadRecorder(); + document.querySelector("span").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).not.toHaveBeenCalled(); + }); + + it("skips clicks on paragraph text", async () => { + document.body.innerHTML = '

paragraph content

'; + await loadRecorder(); + document.querySelector("p").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).not.toHaveBeenCalled(); + }); + + it("skips clicks on heading text", async () => { + document.body.innerHTML = '

Section Title

'; + await loadRecorder(); + document.querySelector("h2").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).not.toHaveBeenCalled(); + }); + + it("records click on child of a link", async () => { + document.body.innerHTML = 'inner text'; + await loadRecorder(); + document.querySelector("span").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith( + expect.objectContaining({ type: "pw-recorded-command" }), + ); + }); + + it("records click on child of a button", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + document.querySelector("span").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith( + expect.objectContaining({ type: "pw-recorded-command" }), + ); + }); + + it("records click on element with onclick attribute", async () => { + document.body.innerHTML = '
clickable div
'; + await loadRecorder(); + document.querySelector("div").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith( + expect.objectContaining({ type: "pw-recorded-command" }), + ); + }); + + // ─── Nth suffix (uniqueness check) ──────────────────────────────────── + + it("appends --nth when multiple buttons share the same text", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + const buttons = document.querySelectorAll("button"); + buttons[1].click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'click "OK" --nth 1', + }); + }); + + it("appends --nth 0 for the first of multiple matching elements", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + document.querySelectorAll("button")[0].click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'click "Save" --nth 0', + }); + }); + + it("does not append --nth when text is unique", async () => { + document.body.innerHTML = ''; + await loadRecorder(); + document.querySelector("button").click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'click "Submit"', + }); + }); + + it("appends --nth for duplicate links", async () => { + document.body.innerHTML = 'Read moreRead more'; + await loadRecorder(); + document.querySelectorAll("a")[1].click(); + vi.advanceTimersByTime(300); + expect(sendMessageSpy).toHaveBeenCalledWith({ + type: "pw-recorded-command", + command: 'click "Read more" --nth 1', + }); + }); + // ─── Checkbox ─────────────────────────────────────────────────────────── it("records check command on checkbox", async () => { From 09346464e8105e3baae3697cd50a2d981279fcac Mon Sep 17 00:00:00 2001 From: Steve Zhang Date: Sat, 21 Feb 2026 16:36:42 -0500 Subject: [PATCH 17/27] test: add tab command and recording integration E2E tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add 6 tab command tests (tab-list, tab-new, tab-select, tab-close, aliases) - Add 5 recording integration E2E tests (click, fill, press, stop cleanup, re-injection after navigation) exercising the full recorder.js → background.js → panel.js pipeline with real Chrome extension APIs - Unify playwright versions: @playwright/test and playwright both resolve to 1.59.0-alpha, deduped to single copy - Remove redundant root playwright dependency, add peerDependency in core - Fix engine.mjs playwright-core resolution for hoisted node_modules - Consolidate 3 playwright projects into single testDir config - Simplify CI: one Chromium install, one test command Co-Authored-By: Claude Opus 4.6 --- .github/workflows/test.yml | 13 +- package-lock.json | 95 ++------ package.json | 3 - packages/core/package.json | 3 + packages/core/src/engine.mjs | 6 +- .../extension/e2e/commands/commands.test.mjs | 88 +++++++ packages/extension/e2e/recording/fixtures.mjs | 81 +++++++ .../e2e/recording/recording.test.mjs | 214 ++++++++++++++++++ packages/extension/package.json | 2 +- packages/extension/playwright.config.js | 14 +- 10 files changed, 413 insertions(+), 106 deletions(-) create mode 100644 packages/extension/e2e/recording/fixtures.mjs create mode 100644 packages/extension/e2e/recording/recording.test.mjs diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index d1a9a63..5b56ed3 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -28,17 +28,10 @@ jobs: - name: Run tests run: npm test - - name: Install Playwright Chromium (panel tests) + - name: Install Playwright Chromium run: npx playwright install chromium working-directory: packages/extension - - name: Install Playwright Chromium (command tests) - run: node node_modules/playwright/cli.js install chromium - - - name: Run extension panel tests - run: npx playwright test --project=panel - working-directory: packages/extension - - - name: Run command integration tests - run: npx playwright test --project=commands + - name: Run E2E tests + run: npx playwright test working-directory: packages/extension diff --git a/package-lock.json b/package-lock.json index 92d64ff..a13754b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5,12 +5,10 @@ "requires": true, "packages": { "": { + "name": "playwright-repl", "workspaces": [ "packages/*" ], - "dependencies": { - "playwright": "^1.59.0-alpha-1771104257000" - }, "devDependencies": { "@vitest/coverage-v8": "^4.0.18", "vitest": "^4.0.18" @@ -559,38 +557,19 @@ "link": true }, "node_modules/@playwright/test": { - "version": "1.58.2", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.58.2.tgz", - "integrity": "sha512-akea+6bHYBBfA9uQqSYmlJXn61cTa+jbO87xVLCWbTqbWadRVmhxlXATaOjOgcBaWU4ePo0wB41KMFv3o35IXA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "playwright": "1.58.2" - }, - "bin": { - "playwright": "cli.js" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@playwright/test/node_modules/playwright": { - "version": "1.58.2", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.58.2.tgz", - "integrity": "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A==", + "version": "1.59.0-alpha-2026-02-21", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.59.0-alpha-2026-02-21.tgz", + "integrity": "sha512-j9yPOBz/fsALTsUKuOYMDDhI7mrDTdW5OD5KUqxzQh5cC0+nMWeYmjhBIGfprTxOMX+JcwOIMqAlhJSXd8tMTg==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.58.2" + "playwright": "1.59.0-alpha-2026-02-21" }, "bin": { "playwright": "cli.js" }, "engines": { "node": ">=18" - }, - "optionalDependencies": { - "fsevents": "2.3.2" } }, "node_modules/@rollup/pluginutils": { @@ -1579,12 +1558,12 @@ } }, "node_modules/playwright": { - "version": "1.59.0-alpha-1771104257000", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.59.0-alpha-1771104257000.tgz", - "integrity": "sha512-6SCMMMJaDRsSqiKVLmb2nhtLES7iTYawTWWrQK6UdIGNzXi8lka4sLKRec3L4DnTWwddAvCuRn8035dhNiHzbg==", + "version": "1.59.0-alpha-2026-02-21", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.59.0-alpha-2026-02-21.tgz", + "integrity": "sha512-ZZSHXJwIjJ/LnrY/7EI+3fZskVHETHIq+AKOYcHgVBgcmuiiqHI10nfpgcdy299mJkQB6OBxShcneWh2Qxm/yA==", "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.59.0-alpha-1771104257000" + "playwright-core": "1.59.0-alpha-2026-02-21" }, "bin": { "playwright": "cli.js" @@ -1597,10 +1576,9 @@ } }, "node_modules/playwright-core": { - "version": "1.58.2", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.2.tgz", - "integrity": "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==", - "dev": true, + "version": "1.59.0-alpha-2026-02-21", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.59.0-alpha-2026-02-21.tgz", + "integrity": "sha512-+oEepN1820aXYLEm+xfVq/ZDst3W5pjI20umfWHdCoR+JKi5DC9SJwULBae63to4yC1LbAVLYmyZMRz2E9jATQ==", "license": "Apache-2.0", "bin": { "playwright-core": "cli.js" @@ -1627,18 +1605,6 @@ "resolved": "packages/cli", "link": true }, - "node_modules/playwright/node_modules/playwright-core": { - "version": "1.59.0-alpha-1771104257000", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.59.0-alpha-1771104257000.tgz", - "integrity": "sha512-YiXup3pnpQUCBMSIW5zx8CErwRx4K6O5Kojkw2BzJui8MazoMUDU6E3xGsb1kzFviEAE09LFQ+y1a0RhIJQ5SA==", - "license": "Apache-2.0", - "bin": { - "playwright-core": "cli.js" - }, - "engines": { - "node": ">=18" - } - }, "node_modules/postcss": { "version": "8.5.6", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", @@ -2129,37 +2095,7 @@ "vitest": "^4.0.18" }, "engines": { - "node": ">=18.0.0" - } - }, - "packages/cli/node_modules/playwright": { - "version": "1.59.0-alpha-2026-02-19", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.59.0-alpha-2026-02-19.tgz", - "integrity": "sha512-dm0DERszC+UiJVrzFKHRe/rbIHBgWCIac/zT4adN66rqPAeRdmFqCM2D51cb0GWub3z2OGxdhGGcjEzUGp6ChA==", - "license": "Apache-2.0", - "dependencies": { - "playwright-core": "1.59.0-alpha-2026-02-19" - }, - "bin": { - "playwright": "cli.js" - }, - "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "fsevents": "2.3.2" - } - }, - "packages/cli/node_modules/playwright-core": { - "version": "1.59.0-alpha-2026-02-19", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.59.0-alpha-2026-02-19.tgz", - "integrity": "sha512-QStoDtLoeSiFhH5tKUs0O5eeTV2JHFsRNvt1HkX9muOq1L4H4IGt0PtgHgFxCxF68Z15EoGm0H8AtSay42b7bg==", - "license": "Apache-2.0", - "bin": { - "playwright-core": "cli.js" - }, - "engines": { - "node": ">=18" + "node": ">=20.0.0" } }, "packages/core": { @@ -2170,6 +2106,9 @@ }, "devDependencies": { "vitest": "^4.0.18" + }, + "peerDependencies": { + "playwright": ">=1.59.0-alpha-2026-02-01" } }, "packages/crx": { @@ -2190,7 +2129,7 @@ "name": "@playwright-repl/extension", "version": "1.0.0", "devDependencies": { - "@playwright/test": "^1.58.2", + "@playwright/test": ">=1.59.0-alpha-2026-02-01", "@vitest/coverage-v8": "^4.0.18", "happy-dom": "^20.6.1", "vitest": "^4.0.18", diff --git a/package.json b/package.json index c1186e9..c4f2693 100644 --- a/package.json +++ b/package.json @@ -12,8 +12,5 @@ "devDependencies": { "@vitest/coverage-v8": "^4.0.18", "vitest": "^4.0.18" - }, - "dependencies": { - "playwright": "^1.59.0-alpha-1771104257000" } } diff --git a/packages/core/package.json b/packages/core/package.json index 4bd4a5c..8fd6432 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -13,6 +13,9 @@ "dependencies": { "minimist": "^1.2.8" }, + "peerDependencies": { + "playwright": ">=1.59.0-alpha-2026-02-01" + }, "devDependencies": { "vitest": "^4.0.18" } diff --git a/packages/core/src/engine.mjs b/packages/core/src/engine.mjs index f53fc58..0d3580a 100644 --- a/packages/core/src/engine.mjs +++ b/packages/core/src/engine.mjs @@ -25,11 +25,13 @@ function loadDeps() { // Resolve absolute paths to bypass Playwright's exports map. const pwDir = path.dirname(require.resolve('playwright/package.json')); const pwReq = (sub) => require(path.join(pwDir, sub)); + const pwCoreDir = path.dirname(require.resolve('playwright-core/package.json')); + const pwCoreReq = (sub) => require(path.join(pwCoreDir, sub)); _deps = { BrowserServerBackend: pwReq('lib/mcp/browser/browserServerBackend.js').BrowserServerBackend, contextFactory: pwReq('lib/mcp/browser/browserContextFactory.js').contextFactory, - playwright: pwReq('node_modules/playwright-core'), - registry: pwReq('node_modules/playwright-core/lib/server/registry/index.js').registry, + playwright: require('playwright-core'), + registry: pwCoreReq('lib/server/registry/index.js').registry, resolveConfig: pwReq('lib/mcp/browser/config.js').resolveConfig, commands: pwReq('lib/cli/daemon/commands.js').commands, parseCommand: pwReq('lib/cli/daemon/command.js').parseCommand, diff --git a/packages/extension/e2e/commands/commands.test.mjs b/packages/extension/e2e/commands/commands.test.mjs index dc2b029..f54e582 100644 --- a/packages/extension/e2e/commands/commands.test.mjs +++ b/packages/extension/e2e/commands/commands.test.mjs @@ -229,6 +229,94 @@ test('alias c for click', async ({ run }) => { expect(result.isError).toBeFalsy(); }); +// ─── Tab commands ──────────────────────────────────────────────────────────── + +/** + * Count tab entries in tab-list output. + * Format: "- N: [Title](URL)" or "- N: (current) [Title](URL)" + */ +function countTabs(tabListText) { + return tabListText.split('\n').filter(l => /^- \d+:/.test(l)).length; +} + +test('tab-list shows open tabs', async ({ run }) => { + await run('goto https://example.com'); + const result = await run('tab-list'); + expect(result.isError).toBeFalsy(); + expect(result.text).toContain('example.com'); + expect(result.text).toMatch(/- 0:.*\(current\)/); +}); + +test('tab-new opens a new tab', async ({ run }) => { + await run('goto https://example.com'); + const before = await run('tab-list'); + const tabsBefore = countTabs(before.text); + + const result = await run('tab-new'); + expect(result.isError).toBeFalsy(); + + const after = await run('tab-list'); + const tabsAfter = countTabs(after.text); + expect(tabsAfter).toBe(tabsBefore + 1); + // New tab becomes current + expect(after.text).toMatch(/- 1:.*\(current\)/); +}); + +test('tab-select switches to a tab by index', async ({ run }) => { + await run('goto https://example.com'); + await run('tab-new'); + // New tab is current — switch back to first tab + const result = await run('tab-select 0'); + expect(result.isError).toBeFalsy(); + + // Verify first tab is now current + const list = await run('tab-list'); + expect(list.text).toMatch(/- 0:.*\(current\).*example\.com/); +}); + +test('tab-close closes the current tab', async ({ run }) => { + await run('goto https://example.com'); + await run('tab-new'); + const before = await run('tab-list'); + const tabsBefore = countTabs(before.text); + + // Close the current tab (the new one) + const result = await run('tab-close'); + expect(result.isError).toBeFalsy(); + + const after = await run('tab-list'); + const tabsAfter = countTabs(after.text); + expect(tabsAfter).toBe(tabsBefore - 1); +}); + +test('tab-new then goto navigates in the new tab', async ({ run }) => { + await run('goto https://example.com'); + await run('tab-new'); + await run('goto https://www.iana.org'); + + const list = await run('tab-list'); + expect(list.text).toContain('example.com'); + expect(list.text).toContain('iana.org'); +}); + +test('tab aliases tl, tn, tc, ts work', async ({ run }) => { + await run('goto https://example.com'); + + const list = await run('tl'); + expect(list.isError).toBeFalsy(); + expect(list.text).toContain('example.com'); + + const newTab = await run('tn'); + expect(newTab.isError).toBeFalsy(); + + const select = await run('ts 0'); + expect(select.isError).toBeFalsy(); + + const close = await run('ts 1'); + expect(close.isError).toBeFalsy(); + await run('tc'); +}); + // ─── Errors ───────────────────────────────────────────────────────────────── test('unknown command returns error', async ({ run }) => { diff --git a/packages/extension/e2e/recording/fixtures.mjs b/packages/extension/e2e/recording/fixtures.mjs new file mode 100644 index 0000000..17282ee --- /dev/null +++ b/packages/extension/e2e/recording/fixtures.mjs @@ -0,0 +1,81 @@ +/** + * Recording integration E2E fixtures. + * + * Launches Chromium with the real extension loaded, opens a panel page + * and a target page. Tests verify that user interactions on the target + * page produce recorded commands visible in the panel editor. + * + * Unlike the panel tests (which mock chrome APIs), these tests exercise + * the real background.js + recorder.js + panel.js message flow. + */ + +import { test as base, chromium } from '@playwright/test'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const EXTENSION_PATH = path.resolve(__dirname, '../..'); + +export const test = base.extend({ + // Worker-scoped: browser context with extension loaded + extensionContext: [async ({}, use) => { + const headlessArgs = process.env.HEADED ? [] : ['--headless=new']; + + const context = await chromium.launchPersistentContext('', { + headless: false, + args: [ + ...headlessArgs, + `--disable-extensions-except=${EXTENSION_PATH}`, + `--load-extension=${EXTENSION_PATH}`, + '--no-first-run', + '--no-default-browser-check', + ], + }); + + let sw = context.serviceWorkers()[0]; + if (!sw) sw = await context.waitForEvent('serviceworker'); + const extensionId = sw.url().split('/')[2]; + + await use({ context, extensionId, sw }); + await context.close(); + }, { scope: 'worker' }], + + // Test-scoped: panel page + target page pair + recordingPages: async ({ extensionContext }, use) => { + const { context, extensionId, sw } = extensionContext; + + // Mock /health and /run so panel initializes (recording is extension-side only) + const panelPage = await context.newPage(); + + await panelPage.route('**/health', (route) => { + route.fulfill({ + contentType: 'application/json', + body: JSON.stringify({ status: 'ok', version: '0.4.0-test' }), + }); + }); + await panelPage.route('**/run', async (route) => { + await route.fulfill({ + contentType: 'application/json', + body: JSON.stringify({ text: 'OK', isError: false }), + }); + }); + + await panelPage.goto(`chrome-extension://${extensionId}/panel/panel.html`); + await panelPage.waitForSelector('.line-info', { timeout: 10000 }); + + // Open a target page with a simple test form + const targetPage = await context.newPage(); + await targetPage.goto('https://example.com'); + await targetPage.waitForLoadState('domcontentloaded'); + + // Bring target page to front so it's the "active tab" for chrome.tabs.query + await targetPage.bringToFront(); + + await use({ panelPage, targetPage, extensionId, sw, context }); + + await targetPage.close(); + await panelPage.close(); + }, +}); + +export { expect } from '@playwright/test'; diff --git a/packages/extension/e2e/recording/recording.test.mjs b/packages/extension/e2e/recording/recording.test.mjs new file mode 100644 index 0000000..3c1b23f --- /dev/null +++ b/packages/extension/e2e/recording/recording.test.mjs @@ -0,0 +1,214 @@ +/** + * Recording integration E2E tests. + * + * Tests the full recording pipeline with the real extension: + * recorder.js (content script) → chrome.runtime.sendMessage → panel.js + * + * Key challenge: In E2E tests the panel runs as a regular tab + * (not a real side panel), so we trigger recording via the service worker + * directly rather than clicking the Record button (which queries the active tab). + */ + +import { test, expect } from './fixtures.mjs'; + +// ─── Helpers ──────────────────────────────────────────────────────────────── + +/** + * Start recording on the target page by calling startRecording() + * directly in the service worker context. + */ +async function startRecordingOn(sw, targetPage) { + const targetUrl = targetPage.url(); + const result = await sw.evaluate(async (url) => { + // Find the target tab by URL + const tabs = await chrome.tabs.query({}); + const tab = tabs.find(t => t.url && t.url.startsWith(url)); + if (!tab) return { ok: false, error: 'Target tab not found for ' + url }; + // Call startRecording directly (defined in background.js scope) + return await startRecording(tab.id); + }, targetUrl); + return result; +} + +/** + * Stop recording on the target page. + */ +async function stopRecordingOn(sw, targetPage) { + const targetUrl = targetPage.url(); + return await sw.evaluate(async (url) => { + const tabs = await chrome.tabs.query({}); + const tab = tabs.find(t => t.url && t.url.startsWith(url)); + if (!tab) return { ok: true }; + return await stopRecording(tab.id); + }, targetUrl); +} + +/** + * Wait for a command matching a pattern to appear in the panel's editor. + */ +async function waitForRecordedCommand(panelPage, pattern, timeoutMs = 10000) { + await panelPage.waitForFunction( + ([pat]) => { + const editor = document.getElementById('editor'); + return editor && new RegExp(pat).test(editor.value); + }, + [pattern], + { timeout: timeoutMs }, + ); +} + +/** + * Wait for a command matching a pattern to appear in the panel's console output. + */ +async function waitForConsoleCommand(panelPage, pattern, timeoutMs = 10000) { + await panelPage.waitForFunction( + ([pat]) => { + const cmds = document.querySelectorAll('.line-command'); + return [...cmds].some(el => new RegExp(pat).test(el.textContent)); + }, + [pattern], + { timeout: timeoutMs }, + ); +} + +// ─── Tests ────────────────────────────────────────────────────────────────── + +test('recorder injects and captures a click on a link', async ({ recordingPages }) => { + const { panelPage, targetPage, sw } = recordingPages; + + // Start recording on the target page + const result = await startRecordingOn(sw, targetPage); + expect(result.ok).toBe(true); + + // Bring target page to front and click the link + await targetPage.bringToFront(); + await targetPage.locator('a').first().click(); + + // The recorder should capture the click and send it to the panel + await panelPage.bringToFront(); + await waitForConsoleCommand(panelPage, 'click'); + + // Verify it also appeared in the editor + const editorValue = await panelPage.locator('#editor').inputValue(); + expect(editorValue).toContain('click'); + + await stopRecordingOn(sw, targetPage); +}); + +test('recorder captures input/fill events', async ({ recordingPages }) => { + const { panelPage, targetPage, sw } = recordingPages; + + // Navigate to a page with an input field + await targetPage.goto('https://demo.playwright.dev/todomvc/'); + await targetPage.waitForLoadState('domcontentloaded'); + + const result = await startRecordingOn(sw, targetPage); + expect(result.ok).toBe(true); + + // Type into the input field — recorder debounces fill after 1500ms + await targetPage.bringToFront(); + const input = targetPage.locator('.new-todo'); + await input.fill('Buy groceries'); + + // Wait for the debounced fill to flush (1500ms debounce + buffer) + await targetPage.waitForTimeout(2500); + + await panelPage.bringToFront(); + await waitForConsoleCommand(panelPage, 'fill.*Buy groceries'); + + const editorValue = await panelPage.locator('#editor').inputValue(); + expect(editorValue).toContain('fill'); + expect(editorValue).toContain('Buy groceries'); + + await stopRecordingOn(sw, targetPage); +}); + +test('recorder captures keyboard press events', async ({ recordingPages }) => { + const { panelPage, targetPage, sw } = recordingPages; + + // Navigate to a page with an input + await targetPage.goto('https://demo.playwright.dev/todomvc/'); + await targetPage.waitForLoadState('domcontentloaded'); + + const result = await startRecordingOn(sw, targetPage); + expect(result.ok).toBe(true); + + // Type and press Enter + await targetPage.bringToFront(); + const input = targetPage.locator('.new-todo'); + await input.fill('Test item'); + await input.press('Enter'); + + await panelPage.bringToFront(); + await waitForConsoleCommand(panelPage, 'press Enter'); + + const editorValue = await panelPage.locator('#editor').inputValue(); + expect(editorValue).toContain('press Enter'); + + await stopRecordingOn(sw, targetPage); +}); + +test('stop recording cleans up — no more commands captured', async ({ recordingPages }) => { + const { panelPage, targetPage, sw } = recordingPages; + + const result = await startRecordingOn(sw, targetPage); + expect(result.ok).toBe(true); + + // Click while recording — should be captured + await targetPage.bringToFront(); + await targetPage.locator('a').first().click(); + await panelPage.bringToFront(); + await waitForConsoleCommand(panelPage, 'click'); + + // Stop recording + await stopRecordingOn(sw, targetPage); + + // Clear editor to check for new commands + await panelPage.evaluate(() => { + document.getElementById('editor').value = ''; + }); + + // Navigate back and click again — should NOT be captured + await targetPage.bringToFront(); + await targetPage.goBack(); + await targetPage.waitForLoadState('domcontentloaded'); + await targetPage.locator('a').first().click(); + + // Wait a bit and verify no new commands appeared in editor + await panelPage.bringToFront(); + await panelPage.waitForTimeout(2000); + const editorValue = await panelPage.locator('#editor').inputValue(); + expect(editorValue).toBe(''); +}); + +test('recorder re-injects after page navigation', async ({ recordingPages }) => { + const { panelPage, targetPage, sw } = recordingPages; + + const result = await startRecordingOn(sw, targetPage); + expect(result.ok).toBe(true); + + // Click a link that navigates to a new page + await targetPage.bringToFront(); + await targetPage.locator('a').first().click(); + await targetPage.waitForLoadState('domcontentloaded'); + + // Wait for re-injection (tabs.onUpdated fires on 'complete') + await targetPage.waitForTimeout(1000); + + // Clear the editor to isolate new commands + await panelPage.bringToFront(); + await panelPage.evaluate(() => { + document.getElementById('editor').value = ''; + }); + + // Now interact with the new page — recorder should still work + await targetPage.bringToFront(); + + // Press Tab on the new page to trigger a keyboard event + await targetPage.keyboard.press('Tab'); + + await panelPage.bringToFront(); + await waitForConsoleCommand(panelPage, 'press Tab'); + + await stopRecordingOn(sw, targetPage); +}); diff --git a/packages/extension/package.json b/packages/extension/package.json index 8b50358..886b65f 100644 --- a/packages/extension/package.json +++ b/packages/extension/package.json @@ -10,7 +10,7 @@ "test:coverage": "vitest run --coverage" }, "devDependencies": { - "@playwright/test": "^1.58.2", + "@playwright/test": ">=1.59.0-alpha-2026-02-01", "@vitest/coverage-v8": "^4.0.18", "happy-dom": "^20.6.1", "vitest": "^4.0.18", diff --git a/packages/extension/playwright.config.js b/packages/extension/playwright.config.js index b7daede..a8ef72f 100644 --- a/packages/extension/playwright.config.js +++ b/packages/extension/playwright.config.js @@ -1,17 +1,7 @@ import { defineConfig } from '@playwright/test'; export default defineConfig({ - timeout: 30000, + testDir: './e2e', + timeout: 60000, retries: 0, - projects: [ - { - name: 'panel', - testDir: './e2e/panel', - }, - { - name: 'commands', - testDir: './e2e/commands', - timeout: 60000, - }, - ], }); From 445163f17f7be94d042683e8fb5de0148c99f3eb Mon Sep 17 00:00:00 2001 From: Steve Zhang Date: Sat, 21 Feb 2026 17:23:09 -0500 Subject: [PATCH 18/27] test: add --nth and non-interactive click recording E2E tests Add two recording E2E tests: - Verify --nth suffix is appended when clicking ambiguous locators (duplicate "npm" tabs on playwright.dev/docs/intro) - Verify clicks on non-interactive elements (headings) are ignored Also remove unused waitForRecordedCommand helper. Co-Authored-By: Claude Opus 4.6 --- .../e2e/recording/recording.test.mjs | 63 ++++++++++++++----- 1 file changed, 49 insertions(+), 14 deletions(-) diff --git a/packages/extension/e2e/recording/recording.test.mjs b/packages/extension/e2e/recording/recording.test.mjs index 3c1b23f..09c2c1a 100644 --- a/packages/extension/e2e/recording/recording.test.mjs +++ b/packages/extension/e2e/recording/recording.test.mjs @@ -43,20 +43,6 @@ async function stopRecordingOn(sw, targetPage) { }, targetUrl); } -/** - * Wait for a command matching a pattern to appear in the panel's editor. - */ -async function waitForRecordedCommand(panelPage, pattern, timeoutMs = 10000) { - await panelPage.waitForFunction( - ([pat]) => { - const editor = document.getElementById('editor'); - return editor && new RegExp(pat).test(editor.value); - }, - [pattern], - { timeout: timeoutMs }, - ); -} - /** * Wait for a command matching a pattern to appear in the panel's console output. */ @@ -95,6 +81,55 @@ test('recorder injects and captures a click on a link', async ({ recordingPages await stopRecordingOn(sw, targetPage); }); +test('recorder appends --nth for ambiguous locators', async ({ recordingPages }) => { + const { panelPage, targetPage, sw } = recordingPages; + + // Navigate to a page with multiple duplicate tab buttons (npm/yarn tabs) + await targetPage.goto('https://playwright.dev/docs/intro'); + await targetPage.waitForLoadState('domcontentloaded'); + + const result = await startRecordingOn(sw, targetPage); + expect(result.ok).toBe(true); + + // Click the second "npm" tab — multiple tab buttons share the same "npm" text. + // The recorder's nthSuffix only counts interactive elements (role=tab, button, a, etc.) + // so non-clickable "npm" text in code blocks is ignored. + await targetPage.bringToFront(); + const npmTabs = targetPage.locator('role=tab', { hasText: /^npm$/ }); + const count = await npmTabs.count(); + expect(count).toBeGreaterThan(1); // confirm duplicates exist + await npmTabs.nth(1).click(); + + await panelPage.bringToFront(); + await waitForConsoleCommand(panelPage, 'click.*--nth 1'); + + const editorValue = await panelPage.locator('#editor').inputValue(); + expect(editorValue).toContain('--nth 1'); + await stopRecordingOn(sw, targetPage); +}); + +test('recorder ignores clicks on non-interactive elements', async ({ recordingPages }) => { + const { panelPage, targetPage, sw } = recordingPages; + + await targetPage.goto('https://playwright.dev/docs/intro'); + await targetPage.waitForLoadState('domcontentloaded'); + + const result = await startRecordingOn(sw, targetPage); + expect(result.ok).toBe(true); + + // Click a heading — non-interactive, recorder should ignore it + await targetPage.bringToFront(); + await targetPage.locator('h1').first().click(); + + // Wait and verify no command was recorded + await panelPage.bringToFront(); + await panelPage.waitForTimeout(2000); + const editorValue = await panelPage.locator('#editor').inputValue(); + expect(editorValue).not.toContain('click'); + + await stopRecordingOn(sw, targetPage); +}); + test('recorder captures input/fill events', async ({ recordingPages }) => { const { panelPage, targetPage, sw } = recordingPages; From 252eb80fc8e4bd98e57d02071fae88076bc87374 Mon Sep 17 00:00:00 2001 From: Steve Zhang Date: Sat, 21 Feb 2026 17:37:56 -0500 Subject: [PATCH 19/27] fix: use auto-retrying assertion in clear test for headed mode Replace immediate count check with toHaveCount(0) which retries until the DOM update completes, fixing flaky failure in headed mode. Co-Authored-By: Claude Opus 4.6 --- packages/extension/e2e/panel/panel.test.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/extension/e2e/panel/panel.test.mjs b/packages/extension/e2e/panel/panel.test.mjs index fcee979..cb266bd 100644 --- a/packages/extension/e2e/panel/panel.test.mjs +++ b/packages/extension/e2e/panel/panel.test.mjs @@ -110,8 +110,8 @@ test('clear empties the output', async ({ panelPage }) => { await input.fill('clear'); await input.press('Enter'); - const lines = panelPage.locator('#output .line'); - expect(await lines.count()).toBe(0); + // Wait for the output to be cleared + await expect(panelPage.locator('#output .line')).toHaveCount(0); }); test('comments display without server call', async ({ panelPage }) => { From b7b77446e91f31bcd58052c2d70e70ae3dcfa913 Mon Sep 17 00:00:00 2001 From: Steve Zhang Date: Sat, 21 Feb 2026 22:43:19 -0500 Subject: [PATCH 20/27] chore: TypeScript migration + fix --nth timeout + extension save - Migrate packages/core and packages/cli from .mjs to .ts - Add tsconfig.base.json, per-package tsconfig.json - Build with tsc to dist/, update CI with build + type check steps - page-scripts.ts kept as plain JS (@ts-nocheck) since functions are stringified via fn.toString() for Playwright's browser_run_code - Fix --nth timeout on pages with hidden tab panels - Add .filter({ visible: true }) before .nth() in all text locator functions (actionByText, fillByText, selectByText, etc.) - Prevents clicking hidden elements in inactive tab panels - Fix extension Save button producing UUID filenames - Replace broken a.download and chrome.downloads approaches with window.showSaveFilePicker() (File System Access API) - Applied to .pw save, inline screenshot save, and lightbox save Co-Authored-By: Claude Opus 4.6 --- .github/workflows/test.yml | 8 +- .gitignore | 3 + CLAUDE.md | 80 +- PLAN-CRX.md | 376 + PLAN-RECORDING.md | 122 + PLAN-TYPESCRIPT.md | 172 + PLAN.md | 3 + package-lock.json | 24 +- package.json | 4 + packages/cli/examples/07-test-click-nth.pw | 17 + packages/cli/package.json | 11 +- packages/cli/src/{index.mjs => index.ts} | 4 +- .../playwright-repl.ts} | 34 +- .../cli/src/{recorder.mjs => recorder.ts} | 79 +- packages/cli/src/{repl.mjs => repl.ts} | 181 +- .../test/{index.test.mjs => index.test.ts} | 2 +- .../{recorder.test.mjs => recorder.test.ts} | 2 +- ...-helpers.test.mjs => repl-helpers.test.ts} | 2 +- ...tion.test.mjs => repl-integration.test.ts} | 4 +- ...line.test.mjs => repl-processline.test.ts} | 4 +- ...rtrepl.test.mjs => repl-startrepl.test.ts} | 2 +- packages/cli/tsconfig.json | 11 + .../{vitest.config.mjs => vitest.config.ts} | 2 +- packages/core/.gitgnore | 1 + packages/core/package.json | 6 +- packages/core/src/{colors.mjs => colors.ts} | 2 +- ...completion-data.mjs => completion-data.ts} | 7 +- packages/core/src/{engine.mjs => engine.ts} | 124 +- ...tension-server.mjs => extension-server.ts} | 88 +- packages/core/src/index.mjs | 14 - packages/core/src/index.ts | 17 + .../src/{page-scripts.mjs => page-scripts.ts} | 23 +- packages/core/src/{parser.mjs => parser.ts} | 19 +- packages/core/src/{resolve.mjs => resolve.ts} | 15 +- ...-data.test.mjs => completion-data.test.ts} | 4 +- .../test/{engine.test.mjs => engine.test.ts} | 2 +- ...rver.test.mjs => extension-server.test.ts} | 2 +- ...-scripts.test.mjs => page-scripts.test.ts} | 2 +- .../test/{parser.test.mjs => parser.test.ts} | 2 +- packages/core/tsconfig.json | 9 + .../{vitest.config.mjs => vitest.config.ts} | 2 +- packages/extension/e2e/commands/fixtures.mjs | 3 +- packages/extension/panel/panel.js | 67 +- .../extension/test-results/.last-run.json | 4 + packages/extension/test/panel.test.js | 14 +- packages/repl-ext/dist/background.js | 143614 --------------- packages/repl-ext/dist/background.js.map | 1 - packages/repl-ext/dist/manifest.json | 17 - packages/repl-ext/dist/panel.css | 233 - packages/repl-ext/dist/panel.html | 57 - packages/repl-ext/dist/panel.js | 174 - packages/repl-ext/dist/panel.js.map | 1 - sidepanel-mockup.png | Bin 0 -> 35674 bytes tsconfig.base.json | 15 + 54 files changed, 1235 insertions(+), 144451 deletions(-) create mode 100644 PLAN-CRX.md create mode 100644 PLAN-RECORDING.md create mode 100644 PLAN-TYPESCRIPT.md create mode 100644 packages/cli/examples/07-test-click-nth.pw rename packages/cli/src/{index.mjs => index.ts} (76%) rename packages/cli/{bin/playwright-repl.mjs => src/playwright-repl.ts} (81%) rename packages/cli/src/{recorder.mjs => recorder.ts} (79%) rename packages/cli/src/{repl.mjs => repl.ts} (78%) rename packages/cli/test/{index.test.mjs => index.test.ts} (95%) rename packages/cli/test/{recorder.test.mjs => recorder.test.ts} (99%) rename packages/cli/test/{repl-helpers.test.mjs => repl-helpers.test.ts} (98%) rename packages/cli/test/{repl-integration.test.mjs => repl-integration.test.ts} (99%) rename packages/cli/test/{repl-processline.test.mjs => repl-processline.test.ts} (99%) rename packages/cli/test/{repl-startrepl.test.mjs => repl-startrepl.test.ts} (98%) create mode 100644 packages/cli/tsconfig.json rename packages/cli/{vitest.config.mjs => vitest.config.ts} (84%) create mode 100644 packages/core/.gitgnore rename packages/core/src/{colors.mjs => colors.ts} (87%) rename packages/core/src/{completion-data.mjs => completion-data.ts} (94%) rename packages/core/src/{engine.mjs => engine.ts} (75%) rename packages/core/src/{extension-server.mjs => extension-server.ts} (67%) delete mode 100644 packages/core/src/index.mjs create mode 100644 packages/core/src/index.ts rename packages/core/src/{page-scripts.mjs => page-scripts.ts} (78%) rename packages/core/src/{parser.mjs => parser.ts} (90%) rename packages/core/src/{resolve.mjs => resolve.ts} (89%) rename packages/core/test/{completion-data.test.mjs => completion-data.test.ts} (92%) rename packages/core/test/{engine.test.mjs => engine.test.ts} (99%) rename packages/core/test/{extension-server.test.mjs => extension-server.test.ts} (98%) rename packages/core/test/{page-scripts.test.mjs => page-scripts.test.ts} (99%) rename packages/core/test/{parser.test.mjs => parser.test.ts} (99%) create mode 100644 packages/core/tsconfig.json rename packages/core/{vitest.config.mjs => vitest.config.ts} (84%) create mode 100644 packages/extension/test-results/.last-run.json delete mode 100644 packages/repl-ext/dist/background.js delete mode 100644 packages/repl-ext/dist/background.js.map delete mode 100644 packages/repl-ext/dist/manifest.json delete mode 100644 packages/repl-ext/dist/panel.css delete mode 100644 packages/repl-ext/dist/panel.html delete mode 100644 packages/repl-ext/dist/panel.js delete mode 100644 packages/repl-ext/dist/panel.js.map create mode 100644 sidepanel-mockup.png create mode 100644 tsconfig.base.json diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 5b56ed3..c42d319 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -25,8 +25,14 @@ jobs: - name: Install dependencies run: npm ci + - name: Build + run: npm run build + + - name: Type check + run: npx tsc --noEmit -p packages/core && npx tsc --noEmit -p packages/cli + - name: Run tests - run: npm test + run: npm test --workspaces --if-present - name: Install Playwright Chromium run: npx playwright install chromium diff --git a/.gitignore b/.gitignore index b9d2b3c..8d8574d 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,6 @@ node_modules/ .playwright-cli/ coverage/ .playwright-mcp/ +dist/ +packages/*/dist/ +*.tsbuildinfo diff --git a/CLAUDE.md b/CLAUDE.md index 3952253..2e0b315 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,25 +11,27 @@ Think of it as a **keyword-driven test runner** (like Robot Framework) backed by ``` playwright-repl/ ├── package.json # Root workspace config (npm workspaces) +├── tsconfig.base.json # Shared TypeScript compiler options ├── packages/ -│ ├── core/ # Shared engine + utilities +│ ├── core/ # Shared engine + utilities (TypeScript) │ │ ├── src/ -│ │ │ ├── engine.mjs # Wraps BrowserServerBackend in-process -│ │ │ ├── parser.mjs # Command parsing + alias resolution -│ │ │ ├── page-scripts.mjs # Text locators + assertion helpers -│ │ │ ├── completion-data.mjs # Ghost completion items -│ │ │ ├── extension-server.mjs # WebSocket server for extension CDP relay -│ │ │ ├── colors.mjs # ANSI color helpers -│ │ │ └── resolve.mjs # COMMANDS map, minimist re-export +│ │ │ ├── engine.ts # Wraps BrowserServerBackend in-process +│ │ │ ├── parser.ts # Command parsing + alias resolution +│ │ │ ├── page-scripts.ts # Text locators + assertion helpers +│ │ │ ├── completion-data.ts # Ghost completion items +│ │ │ ├── extension-server.ts # HTTP server for extension commands +│ │ │ ├── colors.ts # ANSI color helpers +│ │ │ └── resolve.ts # COMMANDS map, minimist re-export +│ │ ├── dist/ # Compiled output (gitignored) │ │ └── test/ │ │ │ ├── cli/ # Terminal REPL (published as "playwright-repl") -│ ├── bin/ -│ │ └── playwright-repl.mjs # CLI entry point │ ├── src/ -│ │ ├── repl.mjs # Interactive readline loop -│ │ ├── recorder.mjs # Session recording/replay -│ │ └── index.mjs # Public API exports +│ │ ├── playwright-repl.ts # CLI entry point (compiles to dist/) +│ │ ├── repl.ts # Interactive readline loop +│ │ ├── recorder.ts # Session recording/replay +│ │ └── index.ts # Public API exports +│ ├── dist/ # Compiled output (gitignored) │ ├── test/ │ └── examples/ # .pw session files │ @@ -88,7 +90,7 @@ browser: locator.click() Chrome: actual DOM click event ``` -### Engine (packages/core/src/engine.mjs) +### Engine (packages/core/src/engine.ts) The `Engine` class wraps Playwright's `BrowserServerBackend` in-process: @@ -113,31 +115,30 @@ Key Playwright internals used (via `createRequire`): - `playwright/lib/mcp/terminal/commands` → `commands` map - `playwright/lib/mcp/terminal/command` → `parseCommand` -### ExtensionServer (packages/core/src/extension-server.mjs) +### CommandServer (packages/core/src/extension-server.ts) -When `--extension` mode is used, `ExtensionServer` starts an HTTP + WebSocket server: +When `--extension` mode is used, `CommandServer` starts an HTTP server: ``` -┌─────────────────────────────────────────────────────────┐ -│ Chrome Extension (DevTools Panel) │ -│ panel.js ──sendMessage──► background.js │ -│ ▲ │ ▲ │ -│ │ port.postMessage │ │ chrome.debugger │ -└───────────────────────────────┼──┼──────────────────────┘ - WebSocket │ │ - ▼ │ -┌───────────────────────────────────────────────────────────┐ -│ ExtensionServer │ -│ ├── /extension WS ← background.js connects here │ -│ ├── HTTP /json/* ← Playwright CDP discovery │ -│ └── /devtools/* ← Playwright CDP WebSocket │ -│ Engine → connectOverCDP → local proxy → relay → ext │ -└───────────────────────────────────────────────────────────┘ +┌──────────────────────────────────────────────┐ +│ Chrome Extension (Side Panel) │ +│ panel.js ─── fetch POST /run ───────────┐ │ +│ ▲ │ │ +│ │ JSON response │ │ +└─────┼────────────────────────────────────┼───┘ + │ │ + │ ▼ +┌─────────────────────────────────────────────────────┐ +│ CommandServer (HTTP :3000) │ +│ ├── POST /run ← panel sends commands here │ +│ └── GET /health ← panel checks server status │ +│ Engine → connectOverCDP → CDP :3001 → Chrome │ +└─────────────────────────────────────────────────────┘ ``` -- **CDP relay**: background.js bridges `chrome.debugger` ↔ WebSocket so Playwright can control the user's browser -- **Command channel**: panel sends commands via background.js → server → `Engine.run()` → results back -- **Recording**: stays extension-side (inject recorder.js, listen for `__pw:` events) +- **Direct CDP**: Engine connects to Chrome via `--remote-debugging-port` (no relay) +- **Command channel**: panel sends commands via `fetch()` → CommandServer → `Engine.run()` → results back +- **Recording**: extension-side (inject recorder.js via `chrome.scripting.executeScript`) ### Element Refs (e1, e5, etc.) @@ -177,17 +178,18 @@ async function processQueue() { ## Tech Stack -- **Runtime**: Node.js (ESM modules, `.mjs`) -- **Dependencies**: `minimist` (command parsing), `playwright@>=1.59.0-alpha` (browser engine), `ws` (WebSocket server for extension mode) +- **Runtime**: Node.js (ESM modules) +- **Language**: TypeScript for `packages/core` and `packages/cli` (compiled to `dist/` via `tsc`); plain JS for `packages/extension` +- **Build**: `tsc` with project references (`tsconfig.base.json` → per-package `tsconfig.json`). Run `npm run build` at root. +- **Dependencies**: `minimist` (command parsing), `playwright@>=1.59.0-alpha` (browser engine) - **Monorepo**: npm workspaces (`packages/core`, `packages/cli`, `packages/extension`) -- **Testing**: vitest +- **Testing**: vitest (unit tests), Playwright Test (extension E2E) - **Key insight**: `playwright@1.59.0-alpha` includes `lib/mcp/browser/` (BrowserServerBackend, contextFactory). The stable `playwright@1.58` does NOT. Once 1.59 goes stable, the alpha pin can be removed. -- No build step — plain ESM JavaScript ## Code Style - ESM imports (`import ... from`) +- TypeScript with `"module": "Node16"` — relative imports use `.js` extensions (resolved to `.ts` at compile time) - Async/await throughout -- No TypeScript (keep it simple, scripting-oriented) - Sections separated by `// ─── Section Name ───` comments diff --git a/PLAN-CRX.md b/PLAN-CRX.md new file mode 100644 index 0000000..be9b1ef --- /dev/null +++ b/PLAN-CRX.md @@ -0,0 +1,376 @@ +# New Package: `packages/repl-ext` — playwright-crx REPL Extension + +## How playwright-crx Works + +### The Problem It Solves + +Normal Playwright runs in **Node.js** and talks to Chrome via a **WebSocket CDP connection** +(either by launching Chrome with `--remote-debugging-port` or via `connectOverCDP()`). +A Chrome extension can't do this — it has no Node.js, no WebSocket server, no TCP port. +But it **does** have `chrome.debugger`, which is a direct CDP API built into the extension platform. + +playwright-crx bridges this gap: it bundles the entire Playwright runtime into a single JS +file that runs inside a Chrome extension's **service worker**, replacing the WebSocket +transport with direct `chrome.debugger` API calls. + +### Architecture Diagram + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ Chrome Extension Service Worker (background.js) │ +│ │ +│ ┌──────────────────────────────────────────────────────────┐ │ +│ │ index.ts (entry point) │ │ +│ │ │ │ +│ │ ┌─────────────┐ sync dispatch ┌───────────────┐ │ │ +│ │ │ CLIENT │ ◄════════════════► │ SERVER │ │ │ +│ │ │ │ │ │ │ │ +│ │ │ CrxConnect- │ message ──────► │ Dispatcher- │ │ │ +│ │ │ ion │ │ Connection │ │ │ +│ │ │ │ ◄────── message │ │ │ │ +│ │ │ Crx │ │ RootDispatch │ │ │ +│ │ │ CrxApp │ │ CrxPlaywright│ │ │ +│ │ │ Page │ │ Crx │ │ │ +│ │ │ BrowserCtx │ │ CrxApp │ │ │ +│ │ └─────────────┘ └──────┬───────┘ │ │ +│ │ │ │ │ +│ │ Exported API: │ │ │ +│ │ export const { crx } = playwrightAPI; │ │ │ +│ │ crx.start() → CrxApplication │ │ │ +│ │ crxApp.attach(tabId) → Page │ │ │ +│ └──────────────────────────────────────────────┼───────────┘ │ +│ │ │ +│ ┌──────────────────────────────────────────────┼───────────┐ │ +│ │ CrxTransport (implements ConnectionTransport)│ │ │ +│ │ ▼ │ │ +│ │ send(message) ──────────────────────────────────────► │ │ +│ │ ├─ Target.setAutoAttach → add filters, sendCommand │ │ +│ │ ├─ Target.createTarget → chrome.tabs.create │ │ +│ │ ├─ Target.closeTarget → chrome.tabs.remove │ │ +│ │ ├─ Browser.getVersion → navigator.userAgent │ │ +│ │ ├─ Emulation.setMedia → no-op (avoid crash) │ │ +│ │ └─ everything else → chrome.debugger.sendCommand │ │ +│ │ │ │ +│ │ chrome.debugger.onEvent ──────────────────────────────► │ │ +│ │ → onmessage(response) → back to Playwright server │ │ +│ │ │ │ +│ │ attach(tabId): │ │ +│ │ 1. chrome.debugger.attach({tabId}, '1.3') │ │ +│ │ 2. Target.getTargetInfo → get targetId, contextId │ │ +│ │ 3. emit Target.attachedToTarget → Playwright creates │ │ +│ │ CRPage internally │ │ +│ │ 4. Map: tabId ↔ targetId ↔ sessionId(crx-tab-N) │ │ +│ └──────────────────────────────────────────────────────────┘ │ +│ │ +│ chrome.debugger.sendCommand({tabId}, method, params) │ +│ │ ▲ │ +└─────────┼──────────────────────────────┼────────────────────────┘ + ▼ │ +┌─────────────────────────────────────────────────────────────────┐ +│ Chrome Browser Tab │ +│ ┌───────────────────────────────────────────────────────────┐ │ +│ │ Page DOM, JavaScript runtime, network, etc. │ │ +│ │ CDP protocol exposed via chrome.debugger privilege │ │ +│ └───────────────────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────────────┘ +``` + +### Key Components + +**1. Entry Point (`src/index.ts`)** + +The magic: client and server run **in the same process** (the service worker), +connected by synchronous in-memory dispatch — no WebSocket, no IPC: + +```ts +const playwright = new CrxPlaywright(); // Server-side +const clientConnection = new CrxConnection(); // Client-side +const dispatcherConnection = new DispatcherConnection(); // Server dispatcher + +// Wire them together — messages pass in-memory +dispatcherConnection.onmessage = msg => clientConnection.dispatch(msg); +clientConnection.onmessage = msg => dispatcherConnection.dispatch(msg); + +// Export the client API +export const { crx } = playwrightAPI; +``` + +**2. CrxTransport (`src/server/transport/crxTransport.ts`)** + +Implements Playwright's `ConnectionTransport` interface using `chrome.debugger`: + +| Normal Playwright | playwright-crx | +|---|---| +| `WebSocketTransport.send()` | `chrome.debugger.sendCommand()` | +| WebSocket `onmessage` | `chrome.debugger.onEvent` listener | +| TCP connection to `localhost:9222` | Extension `"debugger"` permission | +| Session IDs from Chrome | Synthetic `crx-tab-{tabId}` session IDs | + +It also handles CDP commands that `chrome.debugger` doesn't support: +- `Target.setAutoAttach` → forwards with filter (excludes service workers) +- `Target.createTarget` → `chrome.tabs.create()` + attach +- `Target.closeTarget` → `chrome.tabs.remove()` +- `Browser.getVersion` → `navigator.userAgent` +- `Emulation.setEmulatedMedia` → no-op (avoids detach crash) +- `Storage.getCookies` → `Network.getCookies` per-page (chrome.debugger bug) + +**3. Crx + CrxApplication (`src/server/crx.ts`)** + +```ts +crx.start() + → creates CrxTransport + → CRBrowser.connect(transport) // Playwright's browser object + → returns CrxApplication + +crxApp.attach(tabId) + → transport.attach(tabId) // chrome.debugger.attach + Target.getTargetInfo + → emits Target.attachedToTarget // Playwright creates CRPage + → page.waitForInitializedOrError() // waits for page to be ready + → returns Page // full Playwright Page object! +``` + +**4. Vite Build** + +The entire Playwright core (~5MB) is bundled via Vite with Node.js shims: +- `fs` → in-memory filesystem (memfs) +- `child_process`, `net`, `tls` → stubs (no spawning in extensions) +- `crypto` → crypto-browserify +- `buffer`, `stream`, `path`, `os` → browserified versions + +Result: a single `background.js` file that runs in a Chrome service worker. + +### Why This Fixes Our Timeout Problem + +Our old CDP relay approach: +``` +Node.js Playwright → WebSocket → CDPRelayServer → WebSocket → Extension → chrome.debugger + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + Translation layer: drops events, mishandles sessions, + swallows Target.setAutoAttach, misses lifecycle events +``` + +playwright-crx approach: +``` +Playwright (in service worker) → CrxTransport → chrome.debugger + ^^^^^^^^^^^^^ + Direct call, no translation, + handles all CDP edge cases +``` + +The timeout happened because our relay didn't properly handle: +1. `Target.setAutoAttach` filtering (service workers interfered) +2. Synthetic session ID mapping +3. Page lifecycle events for already-loaded pages + +CrxTransport handles all of these because it was built specifically for `chrome.debugger`. + +### Comparison: Three Approaches + +``` +LAUNCH MODE (works): + Node.js → Playwright → launch Chrome → WebSocket CDP → new browser + ✓ Playwright controls entire browser lifecycle + +RELAY MODE (broken): + Node.js → Playwright → connectOverCDP → WS → relay → WS → ext → chrome.debugger + ✗ Too many translation layers, events get lost + +PLAYWRIGHT-CRX MODE (new): + Extension service worker → Playwright (bundled) → chrome.debugger → existing tab + ✓ Direct connection, no relay, designed for chrome.debugger +``` + +## Context + +The current extension mode uses a CDP relay (WebSocket bridge between Node.js Playwright +and `chrome.debugger`). This fails because Playwright never sees page lifecycle events +for already-loaded pages, causing snapshot timeouts. + +**playwright-crx** solves this by running Playwright directly inside the extension's +service worker via `CrxTransport` (implements Playwright's `ConnectionTransport` using +`chrome.debugger`). No relay, no WebSocket bridge, no `connectOverCDP`. + +The existing launch/connect modes (Engine + BrowserServerBackend + MCP API) remain +unchanged. This new package is extension-mode only. + +## Architecture + +``` +packages/repl-ext/ (NEW — Vite-built extension) + src/ + background.ts Service worker: playwright-crx + command handler + commands.ts Thin layer: REPL commands → Playwright Page API + snapshot.ts Accessibility tree walker + ref assignment + panel/ + panel.ts Side panel UI (adapted from packages/extension/panel/) + panel.html + panel.css + public/ + manifest.json Manifest V3 with sidePanel + dist/ Vite build output (loadable as extension) + vite.config.ts + tsconfig.json + package.json + +Flow: + Side Panel (panel.ts) + ↓ chrome.runtime.sendMessage({ type: 'run', command: 'click e5' }) + Service Worker (background.ts) + ↓ import { crx } from 'playwright-crx' + ↓ commandHandler.execute('click e5') + commands.ts + ↓ parse command → resolve ref → page.getByRole(role, {name}).click() + CrxTransport → chrome.debugger → tab +``` + +## Steps + +### Step 1: Scaffold package + Vite build + +Create `packages/repl-ext/` with: + +- `package.json`: depends on `playwright-crx` (file: reference to local fork) +- `tsconfig.json`: ES2020, bundler moduleResolution +- `vite.config.ts`: background.ts entry + panel HTML entry, no minify, sourcemaps +- `public/manifest.json`: Manifest V3, permissions: debugger, tabs, sidePanel, activeTab + +**Verify**: `npm run build` in packages/repl-ext produces `dist/background.js` + `dist/panel.html` + +### Step 2: background.ts — playwright-crx lifecycle + +Implement service worker: + +```ts +import { crx } from 'playwright-crx'; +import type { CrxApplication, Page } from 'playwright-crx'; + +let crxApp: CrxApplication | null = null; +let activePage: Page | null = null; + +// Click extension icon → open side panel +chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }); + +// Handle commands from panel +chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => { + if (msg.type === 'run') handleCommand(msg.command).then(sendResponse); + if (msg.type === 'attach') attachToTab(msg.tabId).then(sendResponse); + return true; // async +}); + +async function attachToTab(tabId: number) { + if (!crxApp) crxApp = await crx.start(); + activePage = await crxApp.attach(tabId); + return { ok: true, url: activePage.url() }; +} +``` + +**Verify**: Load extension → click icon → side panel opens → no errors in service worker console + +### Step 3: commands.ts — thin command layer + +Map REPL keywords to Playwright Page API calls: + +```ts +export async function execute(command: string, page: Page): Promise { + const [keyword, ...args] = command.trim().split(/\s+/); + switch (keyword) { + case 'snapshot': return snapshot(page); + case 'goto': return goto(page, args.join(' ')); + case 'click': return click(page, args[0]); + case 'fill': return fill(page, args[0], args.slice(1).join(' ')); + case 'type': return type(page, args[0], args.slice(1).join(' ')); + case 'press': return press(page, args[0], args.slice(1).join(' ')); + case 'hover': return hover(page, args[0]); + case 'screenshot': return screenshot(page); + case 'back': return goBack(page); + case 'forward': return goForward(page); + case 'reload': return reload(page); + // ... more commands + } +} +``` + +**Verify**: `snapshot` and `goto` work from panel + +### Step 4: snapshot.ts — ref system + +Walk `page.accessibility.snapshot()` tree, assign refs (e1, e2, ...), format output: + +```ts +let refMap = new Map(); +let refCounter = 0; + +export async function snapshot(page: Page): Promise { + const tree = await page.accessibility.snapshot(); + refMap.clear(); + refCounter = 0; + const formatted = formatNode(tree, 0); + return { text: formatted, isError: false }; +} + +function formatNode(node: AXNode, indent: number): string { + // Assign ref to interactive elements + if (isInteractive(node)) { + const ref = `e${++refCounter}`; + refMap.set(ref, node); + // Format: "- role "name" [ref=e5]" + } + // Recurse children +} + +export function resolveRef(ref: string): AXNode { + const node = refMap.get(ref); + if (!node) throw new Error(`Unknown ref: ${ref}`); + return node; +} +``` + +For ref → locator resolution, use `page.getByRole(role, { name, exact: true })`. +If ambiguous (multiple matches), fall back to nth() or more specific selectors. + +**Verify**: `snapshot` shows tree with refs → `click e5` clicks the right element + +### Step 5: panel.html/ts/css — side panel UI + +Adapt from existing `packages/extension/panel/`: +- Remove `chrome.devtools` dependencies +- Use `chrome.tabs.query({ active: true, currentWindow: true })` for tab ID +- Use `chrome.runtime.sendMessage()` to send commands to background.ts +- Keep: editor, console output, toolbar (run/step/record/open/save/export/copy) +- Add: connected tab indicator + +**Verify**: Full panel UI works — type commands, see results, run editor scripts + +### Step 6: Add to monorepo workspace + +- Add `"packages/repl-ext"` to root package.json workspaces +- `npm install` to link + +**Verify**: `npm run build -w packages/repl-ext` works from root + +## Key files + +| File | Purpose | +|------|---------| +| `packages/repl-ext/package.json` | Package config, playwright-crx dependency | +| `packages/repl-ext/vite.config.ts` | Vite build: background.ts + panel entry | +| `packages/repl-ext/tsconfig.json` | TypeScript config | +| `packages/repl-ext/public/manifest.json` | Manifest V3 with sidePanel | +| `packages/repl-ext/src/background.ts` | Service worker: crx lifecycle + message handler | +| `packages/repl-ext/src/commands.ts` | Command → Playwright API mapping | +| `packages/repl-ext/src/snapshot.ts` | Accessibility tree + ref system | +| `packages/repl-ext/src/panel/panel.ts` | Side panel UI logic | +| `packages/repl-ext/src/panel/panel.html` | Side panel HTML | +| `packages/repl-ext/src/panel/panel.css` | Side panel styles | + +## Verification + +1. `cd packages/repl-ext && npm run build` → produces `dist/` with all files +2. Load `dist/` as unpacked extension in Chrome +3. Navigate to https://example.com +4. Click extension icon → side panel opens +5. Type `snapshot` → shows accessibility tree with refs +6. Type `click e1` → clicks the element +7. Type `goto https://playwright.dev` → tab navigates +8. Type `screenshot` → shows screenshot in panel +9. Existing CLI modes (`playwright-repl`, `playwright-repl --connect`) still work unchanged diff --git a/PLAN-RECORDING.md b/PLAN-RECORDING.md new file mode 100644 index 0000000..ffd7c41 --- /dev/null +++ b/PLAN-RECORDING.md @@ -0,0 +1,122 @@ +# Re-implement Recording for Extension v3 + +## Context + +Recording was deferred when the extension was rewritten from v1/v2 (CDP relay via `chrome.debugger`) to v3 (side panel + direct CDP). The old approach used `chrome.debugger` to inject `recorder.js` via CDP `Runtime.evaluate` and captured events via `console.debug("__pw:")` — requiring the `debugger` permission which shows a scary yellow "being controlled" banner. + +v3 replaces this with the modern MV3 approach: `chrome.scripting.executeScript` + `chrome.runtime.sendMessage`. No debugger permission, no banner, simpler code. + +## Architecture + +``` +panel.js ──sendMessage({ type: 'pw-record-start', tabId })──► background.js + │ + chrome.scripting.executeScript() + │ + ▼ + recorder.js (content script) + │ + chrome.runtime.sendMessage() + │ +panel.js ◄──onMessage({ type: 'pw-recorded-command', command })────┘ +``` + +Key simplification: `pw-recorded-command` messages go directly from content script → panel.js (side panel pages receive content script messages in MV3). No background relay needed for the data path. + +## What Changes + +| v1/v2 (old) | v3 (new) | +|---|---| +| `chrome.debugger.attach` + CDP `Runtime.evaluate` | `chrome.scripting.executeScript({ files: [...] })` | +| `console.debug("__pw:" + cmd)` | `chrome.runtime.sendMessage({ type, command })` | +| CDP `Runtime.consoleAPICalled` event listener | `chrome.runtime.onMessage` in panel.js | +| `debugger` permission (yellow banner) | `scripting` permission (no banner) | +| `Page.addScriptToEvaluateOnNewDocument` | `chrome.tabs.onUpdated` listener re-injects | + +## Steps + +### Step 1: Create `packages/extension/content/recorder.js` + +Restore from git commit `d11ae61` with these changes: +- Replace `console.debug("__pw:" + command)` → `chrome.runtime.sendMessage({ type: 'pw-recorded-command', command })` +- Replace `window.__pwRecorderActive` → `document.documentElement.dataset.pwRecorderActive` (survives across worlds) +- Keep ALL DOM event logic unchanged: `handleClick`, `handleInput`, `handleChange`, `handleKeydown`, `getLocator`, `getItemContext`, `findCheckbox`, `flushFill` + +### Step 2: Add `scripting` permission to `packages/extension/manifest.json` + +Add `"scripting"` to the permissions array. No `web_accessible_resources` needed (files injected via `chrome.scripting.executeScript` don't need it). + +### Step 3: Expand `packages/extension/background.js` + +From 2 lines → ~60 lines. Add: +- `chrome.runtime.onMessage` listener for `pw-record-start` / `pw-record-stop` +- `startRecording(tabId)`: inject `recorder.js` via `chrome.scripting.executeScript`, add `tabs.onUpdated` listener +- `stopRecording(tabId)`: execute cleanup function on tab, remove listener +- `onTabUpdated(tabId, changeInfo)`: re-inject `recorder.js` when recording tab navigates (status `complete`) +- Export `startRecording`, `stopRecording`, `onTabUpdated` for testing + +### Step 4: Update `packages/extension/panel/panel.js` + +Replace lines 886-889 (disabled button) with: +- Record button click handler: toggles `isRecording` state + - Start: `chrome.tabs.query` for active tab → `sendMessage({ type: 'pw-record-start', tabId })` → add `.recording` class → change text to "Stop" + - Stop: `sendMessage({ type: 'pw-record-stop', tabId })` → remove `.recording` class → change text to "Record" +- `chrome.runtime.onMessage` listener: on `pw-recorded-command`, call `addCommand(command)` + `appendToEditor(command)` (both functions already exist at lines 183 and 338) +- Use `addInfo()` (line 195) and `addError()` (line 191) for status messages + +### Step 5: Create `packages/extension/test/recorder.test.js` + +Unit tests for recorder.js (~25 tests). Mock `chrome.runtime.sendMessage`. Key tests: +- Sets `dataset.pwRecorderActive` on load, provides cleanup function +- Idempotency (doesn't run twice) +- Click → `sendMessage({ type: 'pw-recorded-command', command: 'click "Submit"' })` +- Checkbox → `check`/`uncheck` commands +- Input → debounced `fill` command +- Select → `select` command +- Enter/Tab/Escape → `press` command +- Locator resolution: aria-label, label[for], placeholder, text, title fallbacks +- Action button with item context +- Click flushes pending fill +- Cleanup removes listeners and dataset + +### Step 6: Create `packages/extension/test/background.test.js` + +Unit tests for background.js recording handlers. Mock `chrome.scripting.executeScript`, `chrome.tabs.onUpdated`. Key tests: +- `startRecording` injects recorder.js, adds `onUpdated` listener +- `startRecording` returns error on injection failure (chrome:// pages) +- `stopRecording` runs cleanup, removes listener +- `stopRecording` handles cleanup failure gracefully +- `onTabUpdated` re-injects on `status: complete` for recording tab only + +### Step 7: Update existing tests + +- `test/panel.test.js` line 130-133: change "record button is disabled" → "record button is enabled" +- `test/setup.js`: add `chrome.scripting` mock (vitest-chrome doesn't include it) +- `e2e/panel/panel.test.mjs` line 22-25: change `isDisabled()` → `isEnabled()` + +### Step 8: Run all tests and verify + +1. `npm test` — unit tests pass (recorder, background, panel) +2. `npx playwright test --project=panel` — E2E panel tests pass +3. Manual: load extension → click Record → interact with page → commands appear in editor + +## Files + +| File | Action | +|------|--------| +| `packages/extension/content/recorder.js` | Create — restored from d11ae61 + sendMessage | +| `packages/extension/manifest.json` | Modify — add `scripting` permission | +| `packages/extension/background.js` | Modify — add recording handlers (~60 lines) | +| `packages/extension/panel/panel.js` | Modify — enable record button + onMessage listener | +| `packages/extension/test/recorder.test.js` | Create — ~25 unit tests | +| `packages/extension/test/background.test.js` | Create — ~9 unit tests | +| `packages/extension/test/panel.test.js` | Modify — update disabled → enabled test | +| `packages/extension/test/setup.js` | Modify — add chrome.scripting mock | +| `packages/extension/e2e/panel/panel.test.mjs` | Modify — update disabled → enabled assertion | + +## No changes needed + +- `panel/panel.html` — record button HTML already exists +- `panel/panel.css` — `.recording` styles already exist (line 175-179, red highlight) +- `packages/core/` — recording is entirely extension-side +- `packages/cli/` — CLI recording is separate and already works diff --git a/PLAN-TYPESCRIPT.md b/PLAN-TYPESCRIPT.md new file mode 100644 index 0000000..59ff45f --- /dev/null +++ b/PLAN-TYPESCRIPT.md @@ -0,0 +1,172 @@ +# TypeScript Migration: packages/core + packages/cli + +## Context + +The codebase is stable with 59 E2E tests + 389 unit tests passing. All features (recording, tabs, commands) are shipped. This is a good pause point to migrate `packages/core` (8 source files, 939 lines) and `packages/cli` (3 source files + 1 bin entry, 927 lines) from plain `.mjs` to TypeScript for type safety. + +The extension (`packages/extension`) stays as plain JS for now — React + Vite migration is planned separately. + +## Strategy + +- **Rename** `.mjs` → `.ts` for all source and test files +- **Build** with `tsc` to `dist/` — required because the CLI bin entry (`playwright-repl`) must run as plain Node.js +- **Type gradually** — start with `any` for Playwright internals (no public types for internal APIs), add proper types for our own interfaces +- **Migrate one package at a time** — core first, then cli + +## Key Challenge: createRequire Hack + +`engine.mjs` uses `createRequire(import.meta.url)` to bypass Playwright's exports map and import internal modules (`lib/mcp/browser/browserServerBackend.js`, etc.). These have no type definitions. + +**Solution**: Create a `src/playwright-internals.d.ts` declaring the shapes we use with minimal types. The `loadDeps()` function returns a typed object instead of `any`. + +## Files to Rename + +### packages/core/src/ (8 files) +- `engine.mjs` → `engine.ts` +- `parser.mjs` → `parser.ts` +- `extension-server.mjs` → `extension-server.ts` +- `resolve.mjs` → `resolve.ts` +- `page-scripts.mjs` → `page-scripts.ts` +- `completion-data.mjs` → `completion-data.ts` +- `colors.mjs` → `colors.ts` +- `index.mjs` → `index.ts` + +### packages/core/test/ (5 files) +- `engine.test.mjs` → `engine.test.ts` +- `parser.test.mjs` → `parser.test.ts` +- `extension-server.test.mjs` → `extension-server.test.ts` +- `completion-data.test.mjs` → `completion-data.test.ts` +- `page-scripts.test.mjs` → `page-scripts.test.ts` + +### packages/cli/src/ (3 files) +- `repl.mjs` → `repl.ts` +- `recorder.mjs` → `recorder.ts` +- `index.mjs` → `index.ts` + +### packages/cli/test/ (6 files) +- `repl-processline.test.mjs` → `repl-processline.test.ts` +- `repl-integration.test.mjs` → `repl-integration.test.ts` +- `recorder.test.mjs` → `recorder.test.ts` +- `repl-helpers.test.mjs` → `repl-helpers.test.ts` +- `repl-startrepl.test.mjs` → `repl-startrepl.test.ts` +- `index.test.mjs` → `index.test.ts` + +### packages/cli/bin/ (1 file) +- `playwright-repl.mjs` → `playwright-repl.ts` — compiled to `dist/` by tsc, `bin` field points to `dist/playwright-repl.js` + +## Steps + +### Step 1: Add TypeScript infrastructure + +**New files:** +- `tsconfig.base.json` (root) — shared compiler options +- `packages/core/tsconfig.json` — extends base +- `packages/cli/tsconfig.json` — extends base, references core + +**Root tsconfig.base.json:** +```json +{ + "compilerOptions": { + "target": "ES2022", + "module": "Node16", + "moduleResolution": "Node16", + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "outDir": "dist", + "rootDir": "src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true + } +} +``` + +**Install:** `npm install -D typescript @types/node @types/minimist` at root + +### Step 2: Migrate packages/core + +1. `git mv` all `.mjs` → `.ts` (source + test files) +2. Create `src/playwright-internals.d.ts` — type stubs for Playwright internal APIs +3. Add type annotations to all exported functions and classes +4. Update internal imports: `'./resolve.mjs'` → `'./resolve.js'` (TypeScript with Node16 resolution requires `.js` extensions in imports, which resolve to `.ts` at compile time) +5. Update `package.json`: + - `"main": "./dist/index.js"` + - `"exports": { ".": "./dist/index.js" }` + - `"types": "./dist/index.d.ts"` + - Add `"build": "tsc"` script +6. Update `vitest.config.mjs` → `vitest.config.ts`: change include to `['test/**/*.test.ts']` +7. Run `tsc --noEmit` to check types, fix errors +8. Run `npm test -w packages/core` to verify all 167 tests pass + +### Step 3: Migrate packages/cli + +1. `git mv` all `.mjs` → `.ts` (source + test files) +2. Add type annotations to exported functions +3. Update imports: + - `'@playwright-repl/core'` stays the same + - `'./recorder.mjs'` → `'./recorder.js'` + - `'./repl.mjs'` → `'./repl.js'` +4. `git mv bin/playwright-repl.mjs` → `src/playwright-repl.ts`: + - Move into `src/` so tsc compiles it to `dist/playwright-repl.js` + - Update import: `'../src/repl.mjs'` → `'./repl.js'` (same directory after compilation) + - Update import: `from '@playwright-repl/core'` stays the same + - Keep the `#!/usr/bin/env node` shebang — tsc preserves it + - Delete `bin/` directory (no longer needed) +5. Update `package.json`: + - `"main": "./dist/index.js"` + - `"exports": { ".": "./dist/index.js" }` + - `"types": "./dist/index.d.ts"` + - `"bin": { "playwright-repl": "./dist/playwright-repl.js" }` (points to compiled output) + - `"files": ["dist/"]` (ship compiled JS only) + - Add `"build": "tsc"` script +6. Update `vitest.config.mjs` → `vitest.config.ts` +7. Run `tsc --noEmit`, fix errors +8. Run `npm test -w packages/cli` to verify all 222 tests pass + +### Step 4: Update extension E2E imports + +Current: +```js +import { Engine } from '../../../core/src/engine.mjs'; +import { CommandServer } from '../../../core/src/extension-server.mjs'; +``` + +Change to use the package name (works via npm workspaces): +```js +import { Engine, CommandServer } from '@playwright-repl/core'; +``` + +### Step 5: Update root package.json and CI + +- Add root scripts: `"build": "npm run build --workspaces --if-present"` +- Update `.github/workflows/test.yml`: add build step before tests +- Add `.gitignore` entries for `packages/*/dist/` +- Add `tsc --noEmit` type checking step to CI + +### Step 6: Verify everything + +1. `npm run build` — both packages compile cleanly +2. `npm test` — all 389 unit tests pass +3. `npx playwright test` (in packages/extension) — all 59 E2E tests pass +4. `npx playwright-repl --help` — CLI works +5. `tsc --noEmit` — no type errors + +## Import Extension Convention + +TypeScript with `"module": "Node16"` requires `.js` extensions in relative imports (even though the source files are `.ts`). This is by design — TypeScript doesn't rewrite import specifiers, and at runtime the files will be `.js`. + +```ts +// In source .ts files: +import { parseInput } from './parser.js'; // resolves to parser.ts at compile time +import { Engine } from './engine.js'; // resolves to engine.ts at compile time +``` + +## What Does NOT Change + +- `packages/extension/` — stays as plain JS +- `packages/extension/e2e/` test files — stay as `.mjs` +- `packages/extension/test/` unit tests — stay as `.js` +- `packages/cli/bin/` directory — deleted, bin entry moves to `src/playwright-repl.ts` and compiles to `dist/` diff --git a/PLAN.md b/PLAN.md index 81cadfd..3e3dbbf 100644 --- a/PLAN.md +++ b/PLAN.md @@ -336,3 +336,6 @@ Phases 7 and 8 are independent of each other. Phase 9 after all modes are verifi - [ ] npx support (`npx playwright-repl`) - [ ] Config file support (.playwright-repl.json) - [ ] Plugin system for custom commands +- [ ] **CLI strict mode violation hint**: When a text locator command (e.g., `click "npm"`) fails with a strict mode violation (multiple elements match), detect the error and suggest using `--nth 0`, `--nth 1`, etc. The recorder already handles this proactively via `nthSuffix()`, but the CLI gives no guidance when users type commands manually. +- [ ] **Clean up verbose goto output**: `goto` currently dumps the full accessibility tree (snapshot) because `filterResponse` keeps the `### Snapshot` section for all commands. Suppress the snapshot for non-snapshot commands so `goto` only shows page URL/title. +- [ ] **CLI replay regression tests**: Support running `.pw` example files as regression tests via the CLI. Accept a file, a folder (runs all `.pw` files), or multiple files. E.g. `playwright-repl --replay examples/` runs all scripts in the folder sequentially, reporting pass/fail per file. Use this to run `packages/cli/examples/*.pw` as integration tests against a real browser. diff --git a/package-lock.json b/package-lock.json index a13754b..e0dce16 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,7 +10,10 @@ "packages/*" ], "devDependencies": { + "@types/minimist": "^1.2.5", + "@types/node": "^25.3.0", "@vitest/coverage-v8": "^4.0.18", + "typescript": "^5.9.3", "vitest": "^4.0.18" } }, @@ -1034,14 +1037,21 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/minimist": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/@types/minimist/-/minimist-1.2.5.tgz", + "integrity": "sha512-hov8bUuiLiyFPGyFPE1lwWhmzYbirOXQNNo40+y3zow8aFVTeyn3VWL0VFFfdNddA8S4Vf0Tc062rzyNr7Paag==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/node": { - "version": "25.2.3", - "resolved": "https://registry.npmjs.org/@types/node/-/node-25.2.3.tgz", - "integrity": "sha512-m0jEgYlYz+mDJZ2+F4v8D1AyQb+QzsNqRuI7xg1VQX/KlKS0qT9r1Mo16yo5F/MtifXFgaofIFsdFMox2SxIbQ==", + "version": "25.3.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.3.0.tgz", + "integrity": "sha512-4K3bqJpXpqfg2XKGK9bpDTc6xO/xoUP/RBWS7AtRMug6zZFaRekiLzjVtAoZMquxoAbzBvy5nxQ7veS5eYzf8A==", "dev": true, "license": "MIT", "dependencies": { - "undici-types": "~7.16.0" + "undici-types": "~7.18.0" } }, "node_modules/@types/whatwg-mimetype": { @@ -1802,9 +1812,9 @@ } }, "node_modules/undici-types": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", - "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "version": "7.18.2", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", + "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", "dev": true, "license": "MIT" }, diff --git a/package.json b/package.json index c4f2693..f4c62d7 100644 --- a/package.json +++ b/package.json @@ -5,12 +5,16 @@ "packages/*" ], "scripts": { + "build": "npm run build --workspaces --if-present", "test": "npm test --workspaces --if-present", "test:core": "npm test -w packages/core", "test:cli": "npm test -w packages/cli" }, "devDependencies": { + "@types/minimist": "^1.2.5", + "@types/node": "^25.3.0", "@vitest/coverage-v8": "^4.0.18", + "typescript": "^5.9.3", "vitest": "^4.0.18" } } diff --git a/packages/cli/examples/07-test-click-nth.pw b/packages/cli/examples/07-test-click-nth.pw new file mode 100644 index 0000000..0d9ba67 --- /dev/null +++ b/packages/cli/examples/07-test-click-nth.pw @@ -0,0 +1,17 @@ +goto https://playwright.dev/ +click "Get started" +click "npm" --nth 0 +click "yarn" --nth 0 +click "pnpm" --nth 0 +click "npm" --nth 1 +click "yarn" --nth 1 +click "pnpm" --nth 1 +click "npm" --nth 2 +click "yarn" --nth 2 +click "pnpm" --nth 2 +click "npm" --nth 3 +click "yarn" --nth 3 +click "pnpm" --nth 3 +click "npm" --nth 4 +click "yarn" --nth 4 +click "pnpm" --nth 4 \ No newline at end of file diff --git a/packages/cli/package.json b/packages/cli/package.json index a022fdb..123c232 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -4,13 +4,15 @@ "description": "Interactive REPL for Playwright browser automation — keyword-driven testing from your terminal", "type": "module", "bin": { - "playwright-repl": "./bin/playwright-repl.mjs" + "playwright-repl": "./dist/playwright-repl.js" }, - "main": "./src/index.mjs", + "main": "./dist/index.js", "exports": { - ".": "./src/index.mjs" + ".": "./dist/index.js" }, + "types": "./dist/index.d.ts", "scripts": { + "build": "tsc", "test": "vitest run" }, "keywords": [ @@ -29,8 +31,7 @@ "url": "git+https://github.com/stevez/playwright-repl.git" }, "files": [ - "bin/", - "src/" + "dist/" ], "engines": { "node": ">=20.0.0" diff --git a/packages/cli/src/index.mjs b/packages/cli/src/index.ts similarity index 76% rename from packages/cli/src/index.mjs rename to packages/cli/src/index.ts index a4cb49a..0c48228 100644 --- a/packages/cli/src/index.mjs +++ b/packages/cli/src/index.ts @@ -12,5 +12,5 @@ export { parseInput, ALIASES, ALL_COMMANDS, buildCompletionItems, Engine } from '@playwright-repl/core'; // CLI-specific -export { SessionRecorder, SessionPlayer } from './recorder.mjs'; -export { startRepl } from './repl.mjs'; +export { SessionRecorder, SessionPlayer } from './recorder.js'; +export { startRepl } from './repl.js'; diff --git a/packages/cli/bin/playwright-repl.mjs b/packages/cli/src/playwright-repl.ts similarity index 81% rename from packages/cli/bin/playwright-repl.mjs rename to packages/cli/src/playwright-repl.ts index 0e655fb..81c1bdb 100644 --- a/packages/cli/bin/playwright-repl.mjs +++ b/packages/cli/src/playwright-repl.ts @@ -11,7 +11,7 @@ */ import { minimist } from '@playwright-repl/core'; -import { startRepl } from '../src/repl.mjs'; +import { startRepl } from './repl.js'; const args = minimist(process.argv.slice(2), { boolean: ['headed', 'persistent', 'extension', 'help', 'step', 'silent', 'spawn'], @@ -22,7 +22,7 @@ const args = minimist(process.argv.slice(2), { // --connect without a value → default port 9222 if (args.connect === '') args.connect = 9222; -else if (args.connect) args.connect = parseInt(args.connect, 10) || 9222; +else if (args.connect) args.connect = parseInt(args.connect as string, 10) || 9222; if (args.help) { console.log(` @@ -78,22 +78,22 @@ Examples: } startRepl({ - session: args.session, - headed: args.headed, - browser: args.browser, - persistent: args.persistent, - profile: args.profile, - connect: args.connect, - extension: args.extension, + session: args.session as string, + headed: args.headed as boolean, + browser: args.browser as string, + persistent: args.persistent as boolean, + profile: args.profile as string, + connect: args.connect as number | undefined, + extension: args.extension as boolean, spawn: args.spawn === true, - port: args.port ? parseInt(args.port, 10) : undefined, - cdpPort: args['cdp-port'] ? parseInt(args['cdp-port'], 10) : undefined, - config: args.config, - replay: args.replay, - record: args.record, - step: args.step, - silent: args.silent, -}).catch((err) => { + port: args.port ? parseInt(args.port as string, 10) : undefined, + cdpPort: args['cdp-port'] ? parseInt(args['cdp-port'] as string, 10) : undefined, + config: args.config as string, + replay: args.replay as string, + record: args.record as string, + step: args.step as boolean, + silent: args.silent as boolean, +}).catch((err: Error) => { console.error(`Fatal: ${err.message}`); process.exit(1); }); diff --git a/packages/cli/src/recorder.mjs b/packages/cli/src/recorder.ts similarity index 79% rename from packages/cli/src/recorder.mjs rename to packages/cli/src/recorder.ts index de58ec0..9dad04e 100644 --- a/packages/cli/src/recorder.mjs +++ b/packages/cli/src/recorder.ts @@ -28,18 +28,15 @@ import path from 'node:path'; // ─── Session Recorder ──────────────────────────────────────────────────────── export class SessionRecorder { - constructor() { - this.commands = []; - this.recording = false; - this.filename = null; - this.paused = false; - } + commands: string[] = []; + recording = false; + filename: string | null = null; + paused = false; /** * Start recording commands. - * @param {string} [filename] - Output file path. If not provided, uses a timestamp. */ - start(filename) { + start(filename?: string): string { this.filename = filename || `session-${new Date().toISOString().replace(/[:.]/g, '-')}.pw`; this.commands = []; this.recording = true; @@ -51,7 +48,7 @@ export class SessionRecorder { * Record a command (called after each successful REPL command). * Skips meta-commands (lines starting with .). */ - record(line) { + record(line: string): void { if (!this.recording || this.paused) return; const trimmed = line.trim(); if (!trimmed || trimmed.startsWith('.')) return; @@ -61,16 +58,15 @@ export class SessionRecorder { /** * Pause recording (toggle). */ - pause() { + pause(): boolean { this.paused = !this.paused; return this.paused; } /** * Stop recording and save to file. - * @returns {{ filename: string, count: number }} */ - save() { + save(): { filename: string; count: number } { if (!this.recording) throw new Error('Not recording'); const header = [ @@ -82,14 +78,14 @@ export class SessionRecorder { const content = [...header, ...this.commands, ''].join('\n'); // Ensure directory exists - const dir = path.dirname(this.filename); + const dir = path.dirname(this.filename!); if (dir && dir !== '.') { fs.mkdirSync(dir, { recursive: true }); } - fs.writeFileSync(this.filename, content, 'utf-8'); + fs.writeFileSync(this.filename!, content, 'utf-8'); - const result = { filename: this.filename, count: this.commands.length }; + const result = { filename: this.filename!, count: this.commands.length }; this.recording = false; this.commands = []; @@ -102,20 +98,20 @@ export class SessionRecorder { /** * Discard recording without saving. */ - discard() { + discard(): void { this.recording = false; this.commands = []; this.filename = null; this.paused = false; } - get status() { + get status(): string { if (!this.recording) return 'idle'; if (this.paused) return 'paused'; return 'recording'; } - get commandCount() { + get commandCount(): number { return this.commands.length; } } @@ -123,12 +119,14 @@ export class SessionRecorder { // ─── Session Player ────────────────────────────────────────────────────────── export class SessionPlayer { + filename: string; + commands: string[]; + index = 0; + /** * Load commands from a .pw file. - * @param {string} filename - * @returns {string[]} Array of command lines */ - static load(filename) { + static load(filename: string): string[] { if (!fs.existsSync(filename)) { throw new Error(`File not found: ${filename}`); } @@ -144,30 +142,29 @@ export class SessionPlayer { * Create a player that yields commands one at a time. * Supports step-through mode where it pauses between commands. */ - constructor(filename) { + constructor(filename: string) { this.filename = filename; this.commands = SessionPlayer.load(filename); - this.index = 0; } - get done() { + get done(): boolean { return this.index >= this.commands.length; } - get current() { + get current(): string | null { return this.commands[this.index] || null; } - get progress() { + get progress(): string { return `[${this.index}/${this.commands.length}]`; } - next() { + next(): string | null { if (this.done) return null; return this.commands[this.index++]; } - reset() { + reset(): void { this.index = 0; } } @@ -180,62 +177,62 @@ export class SessionPlayer { export class SessionManager { #recorder = new SessionRecorder(); - #player = null; + #player: SessionPlayer | null = null; #step = false; /** Current mode: 'idle' | 'recording' | 'paused' | 'replaying' */ - get mode() { + get mode(): string { if (this.#player && !this.#player.done) return 'replaying'; return this.#recorder.status; } // ── Recording ────────────────────────────────────────────────── - startRecording(filename) { + startRecording(filename?: string): string { if (this.mode !== 'idle') throw new Error(`Cannot record while ${this.mode}`); return this.#recorder.start(filename); } - save() { + save(): { filename: string; count: number } { if (this.mode !== 'recording' && this.mode !== 'paused') throw new Error('Not recording'); return this.#recorder.save(); } - togglePause() { + togglePause(): boolean { if (this.mode !== 'recording' && this.mode !== 'paused') throw new Error('Not recording'); return this.#recorder.pause(); } - discard() { + discard(): void { if (this.mode !== 'recording' && this.mode !== 'paused') throw new Error('Not recording'); this.#recorder.discard(); } /** Called after each successful command — records if active. */ - record(line) { + record(line: string): void { this.#recorder.record(line); } - get recordingFilename() { return this.#recorder.filename; } - get recordedCount() { return this.#recorder.commandCount; } + get recordingFilename(): string | null { return this.#recorder.filename; } + get recordedCount(): number { return this.#recorder.commandCount; } // ── Playback ─────────────────────────────────────────────────── - startReplay(filename, step = false) { + startReplay(filename: string, step = false): SessionPlayer { if (this.mode !== 'idle') throw new Error(`Cannot replay while ${this.mode}`); this.#player = new SessionPlayer(filename); this.#step = step; return this.#player; } - endReplay() { + endReplay(): void { this.#player = null; this.#step = false; } - get player() { return this.#player; } - get step() { return this.#step; } + get player(): SessionPlayer | null { return this.#player; } + get step(): boolean { return this.#step; } } diff --git a/packages/cli/src/repl.mjs b/packages/cli/src/repl.ts similarity index 78% rename from packages/cli/src/repl.mjs rename to packages/cli/src/repl.ts index 123ebb3..4be53be 100644 --- a/packages/cli/src/repl.mjs +++ b/packages/cli/src/repl.ts @@ -14,13 +14,35 @@ import { actionByText, fillByText, selectByText, checkByText, uncheckByText, Engine, } from '@playwright-repl/core'; -import { SessionManager } from './recorder.mjs'; +import type { EngineOpts, ParsedArgs } from '@playwright-repl/core'; +import { SessionManager } from './recorder.js'; +import type { CompletionItem } from '@playwright-repl/core'; + +// ─── Types ────────────────────────────────────────────────────────────────── + +export interface ReplOpts extends EngineOpts { + session?: string; + replay?: string; + record?: string; + step?: boolean; + silent?: boolean; +} + +export interface ReplContext { + conn: Engine; + session: SessionManager; + rl: readline.Interface | null; + opts: ReplOpts; + log: (...args: unknown[]) => void; + historyFile: string; + commandCount: number; +} // ─── Response filtering ───────────────────────────────────────────────────── -export function filterResponse(text) { +export function filterResponse(text: string): string | null { const sections = text.split(/^### /m).slice(1); - const kept = []; + const kept: string[] = []; for (const section of sections) { const newline = section.indexOf('\n'); if (newline === -1) continue; @@ -36,9 +58,9 @@ export function filterResponse(text) { // ─── Meta-command handlers ────────────────────────────────────────────────── -export function showHelp() { +export function showHelp(): void { console.log(`\n${c.bold}Available commands:${c.reset}`); - const categories = { + const categories: Record = { 'Navigation': ['open', 'goto', 'go-back', 'go-forward', 'reload'], 'Interaction': ['click', 'dblclick', 'fill', 'type', 'press', 'hover', 'select', 'check', 'uncheck', 'drag'], 'Inspection': ['snapshot', 'screenshot', 'eval', 'console', 'network', 'run-code'], @@ -61,9 +83,9 @@ export function showHelp() { console.log(` .exit Exit REPL\n`); } -export function showAliases() { +export function showAliases(): void { console.log(`\n${c.bold}Command aliases:${c.reset}`); - const groups = {}; + const groups: Record = {}; for (const [alias, cmd] of Object.entries(ALIASES)) { if (!groups[cmd]) groups[cmd] = []; groups[cmd].push(alias); @@ -74,7 +96,7 @@ export function showAliases() { console.log(); } -export function showStatus(ctx) { +export function showStatus(ctx: ReplContext): void { const { conn, session } = ctx; console.log(`Connected: ${conn.connected ? `${c.green}yes${c.reset}` : `${c.red}no${c.reset}`}`); console.log(`Commands sent: ${ctx.commandCount}`); @@ -86,41 +108,41 @@ export function showStatus(ctx) { // ─── Session-level commands ───────────────────────────────────────────────── -export async function handleKillAll(ctx) { +export async function handleKillAll(ctx: ReplContext): Promise { try { await ctx.conn.close(); console.log(`${c.green}✓${c.reset} Browser closed`); - } catch (err) { - console.error(`${c.red}Error:${c.reset} ${err.message}`); + } catch (err: unknown) { + console.error(`${c.red}Error:${c.reset} ${(err as Error).message}`); } } -export async function handleClose(ctx) { +export async function handleClose(ctx: ReplContext): Promise { try { await ctx.conn.close(); console.log(`${c.green}✓${c.reset} Browser closed`); - } catch (err) { - console.error(`${c.red}Error:${c.reset} ${err.message}`); + } catch (err: unknown) { + console.error(`${c.red}Error:${c.reset} ${(err as Error).message}`); } } // ─── Session meta-commands (.record, .save, .pause, .discard, .replay) ────── -export function handleSessionCommand(ctx, line) { +export function handleSessionCommand(ctx: ReplContext, line: string): boolean { const { session } = ctx; if (line.startsWith('.record')) { const filename = line.split(/\s+/)[1] || undefined; const file = session.startRecording(filename); console.log(`${c.red}⏺${c.reset} Recording to ${c.bold}${file}${c.reset}`); - ctx.rl.setPrompt(promptStr(ctx)); + ctx.rl!.setPrompt(promptStr(ctx)); return true; } if (line === '.save') { const { filename, count } = session.save(); console.log(`${c.green}✓${c.reset} Saved ${count} commands to ${c.bold}${filename}${c.reset}`); - ctx.rl.setPrompt(promptStr(ctx)); + ctx.rl!.setPrompt(promptStr(ctx)); return true; } @@ -133,7 +155,7 @@ export function handleSessionCommand(ctx, line) { if (line === '.discard') { session.discard(); console.log(`${c.yellow}Recording discarded${c.reset}`); - ctx.rl.setPrompt(promptStr(ctx)); + ctx.rl!.setPrompt(promptStr(ctx)); return true; } @@ -142,7 +164,7 @@ export function handleSessionCommand(ctx, line) { // ─── Process a single line ────────────────────────────────────────────────── -export async function processLine(ctx, line) { +export async function processLine(ctx: ReplContext, line: string): Promise { line = line.trim(); if (!line) return; @@ -162,8 +184,8 @@ export async function processLine(ctx, line) { try { await ctx.conn.start(ctx.opts); console.log(`${c.green}✓${c.reset} Reconnected`); - } catch (err) { - console.error(`${c.red}✗${c.reset} ${err.message}`); + } catch (err: unknown) { + console.error(`${c.red}✗${c.reset} ${(err as Error).message}`); } return; } @@ -173,8 +195,8 @@ export async function processLine(ctx, line) { if (line.startsWith('.')) { try { if (handleSessionCommand(ctx, line)) return; - } catch (err) { - console.log(`${c.yellow}${err.message}${c.reset}`); + } catch (err: unknown) { + console.log(`${c.yellow}${(err as Error).message}${c.reset}`); return; } } @@ -191,14 +213,14 @@ export async function processLine(ctx, line) { const player = ctx.session.startReplay(filename); console.log(`${c.blue}▶${c.reset} Replaying ${c.bold}${filename}${c.reset} (${player.commands.length} commands)\n`); while (!player.done) { - const cmd = player.next(); + const cmd = player.next()!; console.log(`${c.dim}${player.progress}${c.reset} ${cmd}`); await processLine(ctx, cmd); } ctx.session.endReplay(); console.log(`\n${c.green}✓${c.reset} Replay complete`); - } catch (err) { - console.error(`${c.red}Error:${c.reset} ${err.message}`); + } catch (err: unknown) { + console.error(`${c.red}Error:${c.reset} ${(err as Error).message}`); ctx.session.endReplay(); } return; @@ -206,7 +228,7 @@ export async function processLine(ctx, line) { // ── Regular command — parse and send ───────────────────────────── - let args = parseInput(line); + let args: ParsedArgs | null = parseInput(line); if (!args) return; const cmdName = args._[0]; @@ -222,20 +244,21 @@ export async function processLine(ctx, line) { } // ── Session-level commands (not forwarded to daemon) ────────── - if (cmdName === 'kill-all') return handleKillAll(ctx); - if (cmdName === 'close' || cmdName === 'close-all') return handleClose(ctx); + if (cmdName === 'kill-all') return handleKillAll(ctx) as unknown as void; + if (cmdName === 'close' || cmdName === 'close-all') return handleClose(ctx) as unknown as void; // ── Verify commands → run-code translation ────────────────── - const verifyFns = { - 'verify-text': verifyText, - 'verify-element': verifyElement, - 'verify-value': verifyValue, - 'verify-list': verifyList, + type PageScriptFn = (...fnArgs: unknown[]) => Promise; + const verifyFns: Record = { + 'verify-text': verifyText as PageScriptFn, + 'verify-element': verifyElement as PageScriptFn, + 'verify-value': verifyValue as PageScriptFn, + 'verify-list': verifyList as PageScriptFn, }; if (verifyFns[cmdName]) { const pos = args._.slice(1); const fn = verifyFns[cmdName]; - let translated = null; + let translated: ParsedArgs | null = null; if (cmdName === 'verify-text') { const text = pos.join(' '); if (text) translated = buildRunCode(fn, text); @@ -252,16 +275,16 @@ export async function processLine(ctx, line) { } // ── Auto-resolve text to native Playwright locator ───────── - const textFns = { - click: actionByText, dblclick: actionByText, hover: actionByText, - fill: fillByText, select: selectByText, check: checkByText, uncheck: uncheckByText, + const textFns: Record = { + click: actionByText as PageScriptFn, dblclick: actionByText as PageScriptFn, hover: actionByText as PageScriptFn, + fill: fillByText as PageScriptFn, select: selectByText as PageScriptFn, check: checkByText as PageScriptFn, uncheck: uncheckByText as PageScriptFn, }; if (textFns[cmdName] && args._[1] && !/^e\d+$/.test(args._[1])) { const textArg = args._[1]; const extraArgs = args._.slice(2); const fn = textFns[cmdName]; - const nth = args.nth !== undefined ? parseInt(args.nth, 10) : undefined; - let runCodeArgs; + const nth = args.nth !== undefined ? parseInt(String(args.nth), 10) : undefined; + let runCodeArgs: ParsedArgs; if (fn === actionByText) runCodeArgs = buildRunCode(fn, textArg, cmdName, nth); else if (cmdName === 'fill' || cmdName === 'select') runCodeArgs = buildRunCode(fn, textArg, extraArgs[0] || '', nth); else runCodeArgs = buildRunCode(fn, textArg, nth); @@ -292,11 +315,11 @@ export async function processLine(ctx, line) { ctx.commandCount++; ctx.session.record(line); - if (elapsed > 500) { + if (Number(elapsed) > 500) { ctx.log(`${c.dim}(${elapsed}ms)${c.reset}`); } - } catch (err) { - console.error(`${c.red}Error:${c.reset} ${err.message}`); + } catch (err: unknown) { + console.error(`${c.red}Error:${c.reset} ${(err as Error).message}`); if (!ctx.conn.connected) { console.log(`${c.yellow}Browser disconnected. Trying to restart...${c.reset}`); try { @@ -311,17 +334,17 @@ export async function processLine(ctx, line) { // ─── Replay mode (non-interactive, --replay flag) ─────────────────────────── -export async function runReplayMode(ctx, replayFile, step) { +export async function runReplayMode(ctx: ReplContext, replayFile: string, step: boolean): Promise { try { const player = ctx.session.startReplay(replayFile, step); console.log(`${c.blue}▶${c.reset} Replaying ${c.bold}${replayFile}${c.reset} (${player.commands.length} commands)\n`); while (!player.done) { - const cmd = player.next(); + const cmd = player.next()!; console.log(`${c.dim}${player.progress}${c.reset} ${cmd}`); await processLine(ctx, cmd); if (ctx.session.step && !player.done) { - await new Promise((resolve) => { + await new Promise((resolve) => { process.stdout.write(`${c.dim} Press Enter to continue...${c.reset}`); process.stdin.once('data', () => { process.stdout.write('\r\x1b[K'); @@ -334,8 +357,8 @@ export async function runReplayMode(ctx, replayFile, step) { console.log(`\n${c.green}✓${c.reset} Replay complete`); ctx.conn.close(); process.exit(0); - } catch (err) { - console.error(`${c.red}Error:${c.reset} ${err.message}`); + } catch (err: unknown) { + console.error(`${c.red}Error:${c.reset} ${(err as Error).message}`); ctx.conn.close(); process.exit(1); } @@ -343,35 +366,35 @@ export async function runReplayMode(ctx, replayFile, step) { // ─── Command loop (interactive) ───────────────────────────────────────────── -export function startCommandLoop(ctx) { +export function startCommandLoop(ctx: ReplContext): void { let processing = false; - const commandQueue = []; + const commandQueue: string[] = []; async function processQueue() { if (processing) return; processing = true; while (commandQueue.length > 0) { - const line = commandQueue.shift(); + const line = commandQueue.shift()!; await processLine(ctx, line); if (line.trim()) { try { fs.mkdirSync(path.dirname(ctx.historyFile), { recursive: true }); fs.appendFileSync(ctx.historyFile, line.trim() + '\n'); - } catch {} + } catch { /* ignore */ } } } processing = false; - ctx.rl.prompt(); + ctx.rl!.prompt(); } - ctx.rl.prompt(); + ctx.rl!.prompt(); - ctx.rl.on('line', (line) => { + ctx.rl!.on('line', (line: string) => { commandQueue.push(line); processQueue(); }); - ctx.rl.on('close', async () => { + ctx.rl!.on('close', async () => { while (processing || commandQueue.length > 0) { await new Promise(r => setTimeout(r, 50)); } @@ -381,7 +404,7 @@ export function startCommandLoop(ctx) { }); let lastSigint = 0; - ctx.rl.on('SIGINT', () => { + ctx.rl!.on('SIGINT', () => { if (ctx.opts?.extension) { ctx.conn.close(); process.exit(0); @@ -393,13 +416,13 @@ export function startCommandLoop(ctx) { } lastSigint = now; ctx.log(`\n${c.dim}(Ctrl+C again to exit, or type .exit)${c.reset}`); - ctx.rl.prompt(); + ctx.rl!.prompt(); }); } // ─── Prompt string ────────────────────────────────────────────────────────── -export function promptStr(ctx) { +export function promptStr(ctx: ReplContext): string { if (ctx.opts?.extension) return ''; const mode = ctx.session.mode; const prefix = mode === 'recording' ? `${c.red}⏺${c.reset} ` @@ -410,22 +433,12 @@ export function promptStr(ctx) { // ─── Ghost completion (inline suggestion) ─────────────────────────────────── -/** - * Attaches ghost-text completion to a readline interface. - * Shows dimmed inline suggestion after the cursor; Tab or Right Arrow accepts it. - * - * Uses _ttyWrite wrapper instead of _writeToOutput because Node 22+ optimizes - * single-character appends and doesn't always trigger a full line refresh. - * - * @param {readline.Interface} rl - * @param {Array<{cmd: string, desc: string}>} items - from buildCompletionItems() - */ /** * Returns matching commands for ghost completion. * When the input exactly matches a command AND there are longer matches, * the exact match is included so the user can cycle through all options. */ -export function getGhostMatches(cmds, input) { +export function getGhostMatches(cmds: string[], input: string): string[] { if (input.length > 0 && !input.includes(' ')) { const longer = cmds.filter(cmd => cmd.startsWith(input) && cmd !== input); if (longer.length > 0 && cmds.includes(input)) longer.push(input); @@ -434,21 +447,22 @@ export function getGhostMatches(cmds, input) { return []; } -function attachGhostCompletion(rl, items) { +/* eslint-disable @typescript-eslint/no-explicit-any */ +function attachGhostCompletion(rl: any, items: CompletionItem[]): void { if (!process.stdin.isTTY) return; // no ghost text for piped input - const cmds = items.map(i => i.cmd); + const cmds = items.map((i: CompletionItem) => i.cmd); let ghost = ''; - let matches = []; // all matching commands for current input + let matches: string[] = []; // all matching commands for current input let matchIdx = 0; // which match is currently shown - function renderGhost(suffix) { + function renderGhost(suffix: string) { ghost = suffix; rl.output.write(`\x1b[2m${ghost}\x1b[0m\x1b[${ghost.length}D`); } const origTtyWrite = rl._ttyWrite.bind(rl); - rl._ttyWrite = function (s, key) { + rl._ttyWrite = function (s: string, key: { name: string }) { // Tab handling — based on matches, not ghost text if (key && key.name === 'tab') { // Cycle through multiple matches @@ -503,12 +517,13 @@ function attachGhostCompletion(rl, items) { } }; } +/* eslint-enable @typescript-eslint/no-explicit-any */ // ─── REPL ──────────────────────────────────────────────────────────────────── -export async function startRepl(opts = {}) { +export async function startRepl(opts: ReplOpts = {}): Promise { const silent = opts.silent || false; - const log = (...args) => { if (!silent) console.log(...args); }; + const log = (...args: unknown[]) => { if (!silent) console.log(...args); }; log(`${c.bold}${c.magenta}🎭 Playwright REPL${c.reset} ${c.dim}v${replVersion}${c.reset}`); @@ -528,8 +543,8 @@ export async function startRepl(opts = {}) { log(`${c.green}✓${c.reset} Extension connected, ready for commands\n`); else log(`${c.green}✓${c.reset} Browser ready\n`); - } catch (err) { - console.error(`${c.red}✗${c.reset} Failed to start: ${err.message}`); + } catch (err: unknown) { + console.error(`${c.red}✗${c.reset} Failed to start: ${(err as Error).message}`); process.exit(1); } @@ -538,7 +553,7 @@ export async function startRepl(opts = {}) { const session = new SessionManager(); const historyDir = path.join(os.homedir(), '.playwright-repl'); const historyFile = path.join(historyDir, '.repl-history'); - const ctx = { conn, session, rl: null, opts, log, historyFile, commandCount: 0 }; + const ctx: ReplContext = { conn, session, rl: null, opts, log, historyFile, commandCount: 0 }; // Auto-start recording if --record was passed if (opts.record) { @@ -556,15 +571,15 @@ export async function startRepl(opts = {}) { try { const hist = fs.readFileSync(historyFile, 'utf-8').split('\n').filter(Boolean).reverse(); - for (const line of hist) rl.history.push(line); - } catch {} + for (const line of hist) (rl as readline.Interface & { history: string[] }).history.push(line); + } catch { /* ignore */ } attachGhostCompletion(rl, buildCompletionItems()); // ─── Start ─────────────────────────────────────────────────────── if (opts.replay) { - await runReplayMode(ctx, opts.replay, opts.step); + await runReplayMode(ctx, opts.replay, opts.step || false); } else { startCommandLoop(ctx); } diff --git a/packages/cli/test/index.test.mjs b/packages/cli/test/index.test.ts similarity index 95% rename from packages/cli/test/index.test.mjs rename to packages/cli/test/index.test.ts index 31d9db2..af65923 100644 --- a/packages/cli/test/index.test.mjs +++ b/packages/cli/test/index.test.ts @@ -2,7 +2,7 @@ * Tests that index.mjs re-exports all public API. */ import { describe, it, expect } from 'vitest'; -import * as api from '../src/index.mjs'; +import * as api from '../src/index.js'; describe('index.mjs exports', () => { it('exports Engine', () => { diff --git a/packages/cli/test/recorder.test.mjs b/packages/cli/test/recorder.test.ts similarity index 99% rename from packages/cli/test/recorder.test.mjs rename to packages/cli/test/recorder.test.ts index c909ccc..e7eb168 100644 --- a/packages/cli/test/recorder.test.mjs +++ b/packages/cli/test/recorder.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import fs from 'node:fs'; import path from 'node:path'; import os from 'node:os'; -import { SessionRecorder, SessionPlayer, SessionManager } from '../src/recorder.mjs'; +import { SessionRecorder, SessionPlayer, SessionManager } from '../src/recorder.js'; // ─── SessionRecorder ──────────────────────────────────────────────────────── diff --git a/packages/cli/test/repl-helpers.test.mjs b/packages/cli/test/repl-helpers.test.ts similarity index 98% rename from packages/cli/test/repl-helpers.test.mjs rename to packages/cli/test/repl-helpers.test.ts index f41cd67..12ac92d 100644 --- a/packages/cli/test/repl-helpers.test.mjs +++ b/packages/cli/test/repl-helpers.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { filterResponse, getGhostMatches } from '../src/repl.mjs'; +import { filterResponse, getGhostMatches } from '../src/repl.js'; import { c, buildRunCode, actionByText, fillByText, selectByText, checkByText, uncheckByText, diff --git a/packages/cli/test/repl-integration.test.mjs b/packages/cli/test/repl-integration.test.ts similarity index 99% rename from packages/cli/test/repl-integration.test.mjs rename to packages/cli/test/repl-integration.test.ts index 0e2c6ca..9297a61 100644 --- a/packages/cli/test/repl-integration.test.mjs +++ b/packages/cli/test/repl-integration.test.ts @@ -7,14 +7,14 @@ import { EventEmitter } from 'node:events'; import fs from 'node:fs'; import path from 'node:path'; import os from 'node:os'; -import { SessionManager } from '../src/recorder.mjs'; +import { SessionManager } from '../src/recorder.js'; import { handleKillAll, handleClose, startCommandLoop, runReplayMode, -} from '../src/repl.mjs'; +} from '../src/repl.js'; // ─── Helpers ──────────────────────────────────────────────────────────────── diff --git a/packages/cli/test/repl-processline.test.mjs b/packages/cli/test/repl-processline.test.ts similarity index 99% rename from packages/cli/test/repl-processline.test.mjs rename to packages/cli/test/repl-processline.test.ts index b17ee98..d3ac0d7 100644 --- a/packages/cli/test/repl-processline.test.mjs +++ b/packages/cli/test/repl-processline.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { SessionManager } from '../src/recorder.mjs'; +import { SessionManager } from '../src/recorder.js'; import { processLine, handleSessionCommand, @@ -7,7 +7,7 @@ import { showAliases, showStatus, promptStr, -} from '../src/repl.mjs'; +} from '../src/repl.js'; // ─── Mock ctx factory ─────────────────────────────────────────────────────── diff --git a/packages/cli/test/repl-startrepl.test.mjs b/packages/cli/test/repl-startrepl.test.ts similarity index 98% rename from packages/cli/test/repl-startrepl.test.mjs rename to packages/cli/test/repl-startrepl.test.ts index b0487d8..3ce0179 100644 --- a/packages/cli/test/repl-startrepl.test.mjs +++ b/packages/cli/test/repl-startrepl.test.ts @@ -38,7 +38,7 @@ vi.mock('node:readline', () => ({ })); import { Engine } from '@playwright-repl/core'; -import { startRepl } from '../src/repl.mjs'; +import { startRepl } from '../src/repl.js'; // ─── Tests ────────────────────────────────────────────────────────────────── diff --git a/packages/cli/tsconfig.json b/packages/cli/tsconfig.json new file mode 100644 index 0000000..ba7e01e --- /dev/null +++ b/packages/cli/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist" + }, + "include": ["src"], + "references": [ + { "path": "../core" } + ] +} diff --git a/packages/cli/vitest.config.mjs b/packages/cli/vitest.config.ts similarity index 84% rename from packages/cli/vitest.config.mjs rename to packages/cli/vitest.config.ts index 26c18fe..ecb2a09 100644 --- a/packages/cli/vitest.config.mjs +++ b/packages/cli/vitest.config.ts @@ -2,7 +2,7 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { - include: ['test/**/*.test.mjs'], + include: ['test/**/*.test.ts'], coverage: { provider: 'v8', include: ['src/**'], diff --git a/packages/core/.gitgnore b/packages/core/.gitgnore new file mode 100644 index 0000000..849ddff --- /dev/null +++ b/packages/core/.gitgnore @@ -0,0 +1 @@ +dist/ diff --git a/packages/core/package.json b/packages/core/package.json index 8fd6432..3c00600 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -3,11 +3,13 @@ "version": "0.3.0", "private": true, "type": "module", - "main": "./src/index.mjs", + "main": "./dist/index.js", "exports": { - ".": "./src/index.mjs" + ".": "./dist/index.js" }, + "types": "./dist/index.d.ts", "scripts": { + "build": "tsc", "test": "vitest run" }, "dependencies": { diff --git a/packages/core/src/colors.mjs b/packages/core/src/colors.ts similarity index 87% rename from packages/core/src/colors.mjs rename to packages/core/src/colors.ts index d90c130..11f5a84 100644 --- a/packages/core/src/colors.mjs +++ b/packages/core/src/colors.ts @@ -3,7 +3,7 @@ * No dependency — just ANSI escape codes. */ -export const c = { +export const c: Record = { reset: '\x1b[0m', bold: '\x1b[1m', dim: '\x1b[2m', diff --git a/packages/core/src/completion-data.mjs b/packages/core/src/completion-data.ts similarity index 94% rename from packages/core/src/completion-data.mjs rename to packages/core/src/completion-data.ts index 13897b7..e91f82b 100644 --- a/packages/core/src/completion-data.mjs +++ b/packages/core/src/completion-data.ts @@ -4,7 +4,7 @@ * Sources: COMMANDS from resolve.mjs plus REPL meta-commands (.help, .exit, etc.). */ -import { COMMANDS } from './resolve.mjs'; +import { COMMANDS } from './resolve.js'; // ─── Meta-commands ─────────────────────────────────────────────────────────── @@ -28,6 +28,11 @@ const EXTRA_COMMANDS = [ { cmd: 'verify-list', desc: 'Assert list contains expected items' }, ]; +export interface CompletionItem { + cmd: string; + desc: string; +} + // ─── Build completion items ────────────────────────────────────────────────── /** diff --git a/packages/core/src/engine.mjs b/packages/core/src/engine.ts similarity index 75% rename from packages/core/src/engine.mjs rename to packages/core/src/engine.ts index 0d3580a..90c7bd5 100644 --- a/packages/core/src/engine.mjs +++ b/packages/core/src/engine.ts @@ -13,20 +13,61 @@ import { createRequire } from 'node:module'; import path from 'node:path'; import url from 'node:url'; -import { replVersion } from './resolve.mjs'; +import { replVersion } from './resolve.js'; + +// ─── Types ─────────────────────────────────────────────────────────────────── + +export interface EngineOpts { + headed?: boolean; + browser?: string; + connect?: number | boolean; + extension?: boolean; + spawn?: boolean; + port?: number; + cdpPort?: number; + persistent?: boolean; + profile?: string; + cwd?: string; + [key: string]: unknown; +} + +export interface EngineResult { + text?: string; + image?: string; + isError?: boolean; +} + +export interface ParsedArgs { + _: string[]; + cwd?: string; + nth?: string | number; + [key: string]: unknown; +} + +/* eslint-disable @typescript-eslint/no-explicit-any */ +interface PlaywrightDeps { + BrowserServerBackend: new (config: any, factory: any, opts: any) => any; + contextFactory: (config: any) => { createContext: (info: any, signal: AbortSignal, opts: any) => Promise<{ browserContext: any; close: () => Promise }> }; + playwright: any; + registry: { findExecutable: (name: string) => { executablePath: () => string | undefined } | undefined }; + resolveConfig: (config: any) => Promise | any; + commands: Record; + parseCommand: (command: any, args: any) => { toolName: string; toolParams: Record }; +} +/* eslint-enable @typescript-eslint/no-explicit-any */ // ─── Lazy-loaded Playwright dependencies ──────────────────────────────────── -let _deps; +let _deps: PlaywrightDeps | undefined; -function loadDeps() { +function loadDeps(): PlaywrightDeps { if (_deps) return _deps; const require = createRequire(import.meta.url); // Resolve absolute paths to bypass Playwright's exports map. const pwDir = path.dirname(require.resolve('playwright/package.json')); - const pwReq = (sub) => require(path.join(pwDir, sub)); + const pwReq = (sub: string) => require(path.join(pwDir, sub)); const pwCoreDir = path.dirname(require.resolve('playwright-core/package.json')); - const pwCoreReq = (sub) => require(path.join(pwCoreDir, sub)); + const pwCoreReq = (sub: string) => require(path.join(pwCoreDir, sub)); _deps = { BrowserServerBackend: pwReq('lib/mcp/browser/browserServerBackend.js').BrowserServerBackend, contextFactory: pwReq('lib/mcp/browser/browserContextFactory.js').contextFactory, @@ -42,26 +83,28 @@ function loadDeps() { // ─── Engine ───────────────────────────────────────────────────────────────── export class Engine { - /** - * @param {object} [deps] — Playwright dependencies (injected for testing). - */ - constructor(deps) { + /* eslint-disable @typescript-eslint/no-explicit-any */ + private _deps: PlaywrightDeps | undefined; + private _backend: any = null; + private _browserContext: any = null; + private _close: (() => Promise) | null = null; + private _connected = false; + private _commandServer: { close: () => Promise } | null = null; + private _chromeProc: { kill: () => void; unref: () => void } | null = null; + /* eslint-enable @typescript-eslint/no-explicit-any */ + + constructor(deps?: PlaywrightDeps) { this._deps = deps; - this._backend = null; - this._browserContext = null; - this._close = null; - this._connected = false; } - get connected() { + get connected(): boolean { return this._connected; } /** * Start the engine with given options. - * @param {object} opts - CLI options (headed, browser, connect, etc.) */ - async start(opts = {}) { + async start(opts: EngineOpts = {}): Promise { const deps = this._deps || loadDeps(); const config = await this._buildConfig(opts, deps); @@ -74,15 +117,15 @@ export class Engine { }; // Choose context factory based on mode. - let factory; if (opts.extension) { const serverPort = opts.port || 6781; const cdpPort = opts.cdpPort || 9222; // 1. Start CommandServer for panel HTTP commands. - const { CommandServer } = await import('./extension-server.mjs'); - this._commandServer = new CommandServer(this); - await this._commandServer.start(serverPort); + const { CommandServer } = await import('./extension-server.js'); + const cmdServer = new CommandServer(this); + await cmdServer.start(serverPort); + this._commandServer = cmdServer; console.log(`CommandServer listening on http://localhost:${serverPort}`); // 2. Spawn Chrome (only with --spawn). @@ -125,14 +168,14 @@ export class Engine { try { const res = await fetch(`${cdpUrl}/json/version`); if (res.ok) break; - } catch {} + } catch { /* retry */ } await new Promise(r => setTimeout(r, 500)); } console.log('Chrome CDP ready. Connecting Playwright...'); // 4. Connect Playwright via CDP. - config.browser.cdpEndpoint = cdpUrl; - factory = deps.contextFactory(config); + (config as any).browser.cdpEndpoint = cdpUrl; + const factory = deps.contextFactory(config); const { browserContext, close } = await factory.createContext( clientInfo, new AbortController().signal, {}, ); @@ -158,7 +201,7 @@ export class Engine { if (state === 'visible' && selectedIdx === -1) { selectedIdx = i; } - } catch {} + } catch { /* skip */ } } if (selectedIdx > 0) { await this._backend.callTool('browser_tabs', { action: 'select', index: selectedIdx }); @@ -171,7 +214,7 @@ export class Engine { }); } else { // Launch/connect mode: eagerly create context for immediate feedback. - factory = deps.contextFactory(config); + const factory = deps.contextFactory(config); const { browserContext, close } = await factory.createContext( clientInfo, new AbortController().signal, {}, ); @@ -195,7 +238,7 @@ export class Engine { * Run a command given minimist-parsed args. * Returns { text, isError } matching DaemonConnection.run() shape. */ - async run(args) { + async run(args: ParsedArgs): Promise { if (!this._backend) throw new Error('Engine not started'); @@ -220,16 +263,16 @@ export class Engine { * Select the Playwright page matching the given URL. * Uses backend.callTool('browser_tabs') to properly update the tab tracker. */ - async selectPageByUrl(targetUrl) { + async selectPageByUrl(targetUrl: string): Promise { if (!this._browserContext || !this._backend || !targetUrl) return; const pages = this._browserContext.pages(); - const normalize = (u) => u.replace(/\/+$/, ''); + const normalize = (u: string) => u.replace(/\/+$/, ''); const target = normalize(targetUrl); for (let i = 0; i < pages.length; i++) { if (normalize(pages[i].url()) === target) { try { await this._backend.callTool('browser_tabs', { action: 'select', index: i }); - } catch {} + } catch { /* ignore */ } return; } } @@ -238,7 +281,7 @@ export class Engine { /** * Shut down the browser and backend. */ - async close() { + async close(): Promise { this._connected = false; if (this._commandServer) { await this._commandServer.close(); @@ -253,25 +296,27 @@ export class Engine { this._close = null; } if (this._chromeProc) { - try { this._chromeProc.kill(); } catch {} + try { this._chromeProc.kill(); } catch { /* ignore */ } this._chromeProc = null; } } // ─── Config builder ─────────────────────────────────────────────────────── - async _buildConfig(opts, deps) { + private async _buildConfig(opts: EngineOpts, deps: PlaywrightDeps) { const config = { browser: { browserName: 'chromium', launchOptions: { - channel: 'chrome', + channel: 'chrome' as string | undefined, headless: !opts.headed, }, contextOptions: { - viewport: null, + viewport: null as null, }, isolated: false, + userDataDir: undefined as string | undefined, + cdpEndpoint: undefined as string | undefined, }, server: {}, network: {}, @@ -320,10 +365,15 @@ export class Engine { // ─── Helpers ──────────────────────────────────────────────────────────────── -function formatResult(result) { +interface ToolResult { + content: Array<{ type: string; text?: string; data?: string; mimeType?: string }>; + isError?: boolean; +} + +function formatResult(result: ToolResult): EngineResult { const isError = result.isError; - let text; - let image; + let text: string | undefined; + let image: string | undefined; for (const item of result.content) { if (item.type === 'text' && !text) text = item.text; if (item.type === 'image' && !image) image = `data:${item.mimeType || 'image/png'};base64,${item.data}`; diff --git a/packages/core/src/extension-server.mjs b/packages/core/src/extension-server.ts similarity index 67% rename from packages/core/src/extension-server.mjs rename to packages/core/src/extension-server.ts index 191e759..7221cf4 100644 --- a/packages/core/src/extension-server.mjs +++ b/packages/core/src/extension-server.ts @@ -6,47 +6,58 @@ * GET /health Panel checks if server is running */ -import { createServer } from 'node:http'; -import { parseInput } from './parser.mjs'; -import { replVersion } from './resolve.mjs'; +import { createServer, type IncomingMessage, type ServerResponse, type Server } from 'node:http'; +import { parseInput } from './parser.js'; +import { replVersion } from './resolve.js'; import { buildRunCode, verifyText, verifyElement, verifyValue, verifyList, actionByText, fillByText, selectByText, checkByText, uncheckByText, -} from './page-scripts.mjs'; +} from './page-scripts.js'; +import type { ParsedArgs, EngineResult } from './engine.js'; + +// ─── Types ────────────────────────────────────────────────────────────────── + +interface EngineInterface { + run: (args: ParsedArgs) => Promise; + selectPageByUrl: (url: string) => Promise; + connected: boolean; +} // ─── CommandServer ────────────────────────────────────────────────────────── export class CommandServer { - constructor(engine) { + private _engine: EngineInterface; + private _server: Server | null = null; + private _port: number | null = null; + + constructor(engine: EngineInterface) { this._engine = engine; - this._server = null; - this._port = null; } - get port() { return this._port; } + get port(): number | null { return this._port; } - async start(port = 6781) { + async start(port = 6781): Promise { this._server = createServer((req, res) => this._handleHttp(req, res)); - return new Promise((resolve, reject) => { - this._server.listen(port, () => { - this._port = this._server.address().port; + return new Promise((resolve, reject) => { + this._server!.listen(port, () => { + this._port = (this._server!.address() as { port: number }).port; resolve(); }); - this._server.on('error', reject); + this._server!.on('error', reject); }); } - async close() { + async close(): Promise { if (this._server) { - await new Promise((resolve) => this._server.close(resolve)); + await new Promise((resolve) => this._server!.close(() => resolve())); this._server = null; } } // ─── HTTP handler ─────────────────────────────────────────────────────── - async _handleHttp(req, res) { + private async _handleHttp(req: IncomingMessage, res: ServerResponse): Promise { // CORS — allow chrome-extension:// origins res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'POST, GET'); @@ -58,7 +69,7 @@ export class CommandServer { return; } - const urlPath = req.url.replace(/\/+$/, ''); + const urlPath = (req.url || '').replace(/\/+$/, ''); // Health check endpoint if (req.method === 'GET' && urlPath === '/health') { @@ -89,9 +100,10 @@ export class CommandServer { const result = await withTimeout(this._engine.run(args), 30000); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(result)); - } catch (e) { + } catch (e: unknown) { + const message = e instanceof Error ? e.message : String(e); res.writeHead(500, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ text: e.message, isError: true })); + res.end(JSON.stringify({ text: message, isError: true })); } return; } @@ -103,26 +115,28 @@ export class CommandServer { // ─── REPL-level argument transformations ──────────────────────────────────── +type PageScriptFn = (...args: unknown[]) => Promise; + /** * Apply the same transformations the CLI REPL does before engine.run(): * - Verify commands → run-code with page scripts * - Text locators → run-code with actionByText/fillByText/etc. * - Auto-wrap run-code body with async (page) => { ... } */ -function resolveArgs(args) { +function resolveArgs(args: ParsedArgs): ParsedArgs { const cmdName = args._[0]; // ── Verify commands → run-code translation ────────────────── - const verifyFns = { - 'verify-text': verifyText, - 'verify-element': verifyElement, - 'verify-value': verifyValue, - 'verify-list': verifyList, + const verifyFns: Record = { + 'verify-text': verifyText as PageScriptFn, + 'verify-element': verifyElement as PageScriptFn, + 'verify-value': verifyValue as PageScriptFn, + 'verify-list': verifyList as PageScriptFn, }; if (verifyFns[cmdName]) { const pos = args._.slice(1); const fn = verifyFns[cmdName]; - let translated = null; + let translated: ParsedArgs | null = null; if (cmdName === 'verify-text') { const text = pos.join(' '); if (text) translated = buildRunCode(fn, text); @@ -134,23 +148,21 @@ function resolveArgs(args) { } // ── Auto-resolve text to native Playwright locator ───────── - const textFns = { - click: actionByText, dblclick: actionByText, hover: actionByText, - fill: fillByText, select: selectByText, check: checkByText, uncheck: uncheckByText, + const textFns: Record = { + click: actionByText as PageScriptFn, dblclick: actionByText as PageScriptFn, hover: actionByText as PageScriptFn, + fill: fillByText as PageScriptFn, select: selectByText as PageScriptFn, check: checkByText as PageScriptFn, uncheck: uncheckByText as PageScriptFn, }; if (textFns[cmdName] && args._[1] && !/^e\d+$/.test(args._[1])) { const textArg = args._[1]; const extraArgs = args._.slice(2); const fn = textFns[cmdName]; - const nth = args.nth !== undefined ? parseInt(args.nth, 10) : undefined; + const nth = args.nth !== undefined ? parseInt(String(args.nth), 10) : undefined; if (fn === actionByText) args = buildRunCode(fn, textArg, cmdName, nth); else if (cmdName === 'fill' || cmdName === 'select') args = buildRunCode(fn, textArg, extraArgs[0] || '', nth); else args = buildRunCode(fn, textArg, nth); } // ── go-back / go-forward → evaluate history.back/forward ── - // Playwright's page.goBack() waits for load which can hang with bfcache in CDP mode. - // Use history API directly — the user sees the browser live, no need to wait. if (cmdName === 'go-back') { args = { _: ['run-code', 'async (page) => { await page.evaluate(() => history.back()); return "Navigated back"; }'] }; } @@ -172,20 +184,20 @@ function resolveArgs(args) { // ─── Helpers ──────────────────────────────────────────────────────────────── -function readBody(req) { +function readBody(req: IncomingMessage): Promise { return new Promise((resolve) => { let data = ''; - req.on('data', (chunk) => data += chunk); + req.on('data', (chunk: Buffer) => data += chunk); req.on('end', () => resolve(data)); }); } -function withTimeout(promise, ms) { - let timer; +function withTimeout(promise: Promise, ms: number): Promise { + let timer: ReturnType; return Promise.race([ promise, - new Promise((_, reject) => { + new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`Command timed out after ${ms / 1000}s`)), ms); }), - ]).finally(() => clearTimeout(timer)); + ]).finally(() => clearTimeout(timer!)); } diff --git a/packages/core/src/index.mjs b/packages/core/src/index.mjs deleted file mode 100644 index 3c3fa52..0000000 --- a/packages/core/src/index.mjs +++ /dev/null @@ -1,14 +0,0 @@ -/** - * @playwright-repl/core — shared engine, parser, and utilities. - */ - -export { minimist, replVersion, packageLocation, COMMANDS } from './resolve.mjs'; -export { parseInput, ALIASES, ALL_COMMANDS, booleanOptions } from './parser.mjs'; -export { buildCompletionItems } from './completion-data.mjs'; -export { c } from './colors.mjs'; -export { - buildRunCode, verifyText, verifyElement, verifyValue, verifyList, - actionByText, fillByText, selectByText, checkByText, uncheckByText, -} from './page-scripts.mjs'; -export { Engine } from './engine.mjs'; -export { CommandServer } from './extension-server.mjs'; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts new file mode 100644 index 0000000..e60b761 --- /dev/null +++ b/packages/core/src/index.ts @@ -0,0 +1,17 @@ +/** + * @playwright-repl/core — shared engine, parser, and utilities. + */ + +export { minimist, replVersion, packageLocation, COMMANDS } from './resolve.js'; +export { parseInput, ALIASES, ALL_COMMANDS, booleanOptions } from './parser.js'; +export { buildCompletionItems } from './completion-data.js'; +export { c } from './colors.js'; +export { + buildRunCode, verifyText, verifyElement, verifyValue, verifyList, + actionByText, fillByText, selectByText, checkByText, uncheckByText, +} from './page-scripts.js'; +export { Engine } from './engine.js'; +export type { EngineOpts, EngineResult, ParsedArgs } from './engine.js'; +export { CommandServer } from './extension-server.js'; +export type { CompletionItem } from './completion-data.js'; +export type { CommandInfo } from './resolve.js'; diff --git a/packages/core/src/page-scripts.mjs b/packages/core/src/page-scripts.ts similarity index 78% rename from packages/core/src/page-scripts.mjs rename to packages/core/src/page-scripts.ts index 2ad23bc..1613789 100644 --- a/packages/core/src/page-scripts.mjs +++ b/packages/core/src/page-scripts.ts @@ -1,9 +1,18 @@ +// @ts-nocheck — This file is intentionally untyped JavaScript. +// Functions here are stringified via fn.toString() and sent to Playwright's +// browser_run_code tool. Type annotations would appear in the stringified output. + /** * Page-context functions for run-code commands. * * Each function is a real, testable async function that takes (page, ...args). * buildRunCode() converts them to code strings via Function.toString(), * following the same pattern as playwright-repl-extension/lib/page-scripts.js. + * + * IMPORTANT: This file must remain plain JavaScript — NOT TypeScript. + * These functions are stringified via fn.toString() and sent to Playwright's + * browser_run_code tool for evaluation. TypeScript annotations would break + * the stringified output. */ // ─── Helper ───────────────────────────────────────────────────────────────── @@ -55,7 +64,7 @@ export async function actionByText(page, text, action, nth) { if (await loc.count() === 0) loc = page.getByRole('button', { name: text }); if (await loc.count() === 0) loc = page.getByRole('link', { name: text }); if (await loc.count() === 0) loc = page.getByText(text); - if (nth !== undefined) loc = loc.nth(nth); + if (nth !== undefined) loc = loc.filter({ visible: true }).nth(nth); await loc[action](); } @@ -63,39 +72,39 @@ export async function fillByText(page, text, value, nth) { let loc = page.getByLabel(text); if (await loc.count() === 0) loc = page.getByPlaceholder(text); if (await loc.count() === 0) loc = page.getByRole('textbox', { name: text }); - if (nth !== undefined) loc = loc.nth(nth); + if (nth !== undefined) loc = loc.filter({ visible: true }).nth(nth); await loc.fill(value); } export async function selectByText(page, text, value, nth) { let loc = page.getByLabel(text); if (await loc.count() === 0) loc = page.getByRole('combobox', { name: text }); - if (nth !== undefined) loc = loc.nth(nth); + if (nth !== undefined) loc = loc.filter({ visible: true }).nth(nth); await loc.selectOption(value); } export async function checkByText(page, text, nth) { const item = page.getByRole('listitem').filter({ hasText: text }); if (await item.count() > 0) { - const target = nth !== undefined ? item.nth(nth) : item; + const target = nth !== undefined ? item.filter({ visible: true }).nth(nth) : item; await target.getByRole('checkbox').check(); return; } let loc = page.getByLabel(text); if (await loc.count() === 0) loc = page.getByRole('checkbox', { name: text }); - if (nth !== undefined) loc = loc.nth(nth); + if (nth !== undefined) loc = loc.filter({ visible: true }).nth(nth); await loc.check(); } export async function uncheckByText(page, text, nth) { const item = page.getByRole('listitem').filter({ hasText: text }); if (await item.count() > 0) { - const target = nth !== undefined ? item.nth(nth) : item; + const target = nth !== undefined ? item.filter({ visible: true }).nth(nth) : item; await target.getByRole('checkbox').uncheck(); return; } let loc = page.getByLabel(text); if (await loc.count() === 0) loc = page.getByRole('checkbox', { name: text }); - if (nth !== undefined) loc = loc.nth(nth); + if (nth !== undefined) loc = loc.filter({ visible: true }).nth(nth); await loc.uncheck(); } diff --git a/packages/core/src/parser.mjs b/packages/core/src/parser.ts similarity index 90% rename from packages/core/src/parser.mjs rename to packages/core/src/parser.ts index f34d8a4..63ad252 100644 --- a/packages/core/src/parser.mjs +++ b/packages/core/src/parser.ts @@ -7,11 +7,12 @@ * parseCliCommand() which maps it to a tool call. */ -import { minimist, COMMANDS } from './resolve.mjs'; +import { minimist, COMMANDS } from './resolve.js'; +import type { ParsedArgs } from './engine.js'; // ─── Command aliases ───────────────────────────────────────────────────────── -export const ALIASES = { +export const ALIASES: Record = { // Navigation 'o': 'open', 'g': 'goto', @@ -65,7 +66,7 @@ export const booleanOptions = new Set([ // ─── All known commands ────────────────────────────────────────────────────── -export const ALL_COMMANDS = Object.keys(COMMANDS); +export const ALL_COMMANDS: string[] = Object.keys(COMMANDS); // ─── Tokenizer ─────────────────────────────────────────────────────────────── @@ -73,10 +74,10 @@ export const ALL_COMMANDS = Object.keys(COMMANDS); * Tokenize input respecting quoted strings. * "fill e7 'hello world'" → ["fill", "e7", "hello world"] */ -function tokenize(line) { - const tokens = []; +function tokenize(line: string): string[] { + const tokens: string[] = []; let current = ''; - let inQuote = null; + let inQuote: string | null = null; for (let i = 0; i < line.length; i++) { const ch = line[i]; @@ -110,7 +111,7 @@ function tokenize(line) { // Commands where everything after the keyword is a single raw argument const RAW_COMMANDS = new Set(['run-code', 'eval']); -export function parseInput(line) { +export function parseInput(line: string): ParsedArgs | null { const tokens = tokenize(line); if (tokens.length === 0) return null; @@ -120,13 +121,13 @@ export function parseInput(line) { // For run-code / eval, preserve the rest of the line as a single raw string if (RAW_COMMANDS.has(tokens[0])) { - const cmdLen = line.match(/^\s*\S+/)[0].length; + const cmdLen = line.match(/^\s*\S+/)![0].length; const rest = line.slice(cmdLen).trim(); return rest ? { _: [tokens[0], rest] } : { _: [tokens[0]] }; } // Parse with minimist (same lib and boolean set as playwright-cli) - const args = minimist(tokens, { boolean: [...booleanOptions] }); + const args = minimist(tokens, { boolean: [...booleanOptions] }) as ParsedArgs; // Stringify non-boolean values (playwright-cli does this) for (const key of Object.keys(args)) { diff --git a/packages/core/src/resolve.mjs b/packages/core/src/resolve.ts similarity index 89% rename from packages/core/src/resolve.mjs rename to packages/core/src/resolve.ts index a2735f9..7b55556 100644 --- a/packages/core/src/resolve.mjs +++ b/packages/core/src/resolve.ts @@ -10,17 +10,24 @@ const require = createRequire(import.meta.url); // ─── Own dependencies ──────────────────────────────────────────────────────── -export const minimist = require('minimist'); +// eslint-disable-next-line @typescript-eslint/no-require-imports +export const minimist: (args: string[], opts?: Record) => Record & { _: string[] } = require('minimist'); const pkgUrl = new URL('../package.json', import.meta.url); -export const replVersion = require('../../cli/package.json').version; +// eslint-disable-next-line @typescript-eslint/no-require-imports +export const replVersion: string = require('../../cli/package.json').version; // Must match what daemon-launcher.cjs computes via require.resolve('../package.json') -export const packageLocation = fileURLToPath(pkgUrl); +export const packageLocation: string = fileURLToPath(pkgUrl); // ─── Command vocabulary ────────────────────────────────────────────────────── -export const COMMANDS = { +export interface CommandInfo { + desc: string; + options: string[]; +} + +export const COMMANDS: Record = { 'open': { desc: 'Open the browser', options: [] }, 'close': { desc: 'Close the browser', options: [] }, 'goto': { desc: 'Navigate to a URL', options: [] }, diff --git a/packages/core/test/completion-data.test.mjs b/packages/core/test/completion-data.test.ts similarity index 92% rename from packages/core/test/completion-data.test.mjs rename to packages/core/test/completion-data.test.ts index c1d314d..b4ff37f 100644 --- a/packages/core/test/completion-data.test.mjs +++ b/packages/core/test/completion-data.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from 'vitest'; -import { buildCompletionItems } from '../src/completion-data.mjs'; -import { COMMANDS } from '../src/resolve.mjs'; +import { buildCompletionItems } from '../src/completion-data.js'; +import { COMMANDS } from '../src/resolve.js'; describe('buildCompletionItems', () => { const items = buildCompletionItems(); diff --git a/packages/core/test/engine.test.mjs b/packages/core/test/engine.test.ts similarity index 99% rename from packages/core/test/engine.test.mjs rename to packages/core/test/engine.test.ts index add5152..62a85bb 100644 --- a/packages/core/test/engine.test.mjs +++ b/packages/core/test/engine.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { Engine } from '../src/engine.mjs'; +import { Engine } from '../src/engine.js'; // ─── Mock Playwright dependencies (injected via Engine constructor) ────────── diff --git a/packages/core/test/extension-server.test.mjs b/packages/core/test/extension-server.test.ts similarity index 98% rename from packages/core/test/extension-server.test.mjs rename to packages/core/test/extension-server.test.ts index eb7ca62..01bf18d 100644 --- a/packages/core/test/extension-server.test.mjs +++ b/packages/core/test/extension-server.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { CommandServer } from '../src/extension-server.mjs'; +import { CommandServer } from '../src/extension-server.js'; // ─── Helper: create a mock engine ───────────────────────────────────────────── diff --git a/packages/core/test/page-scripts.test.mjs b/packages/core/test/page-scripts.test.ts similarity index 99% rename from packages/core/test/page-scripts.test.mjs rename to packages/core/test/page-scripts.test.ts index 8a981df..9c8f1ba 100644 --- a/packages/core/test/page-scripts.test.mjs +++ b/packages/core/test/page-scripts.test.ts @@ -3,7 +3,7 @@ import { buildRunCode, verifyText, verifyElement, verifyValue, verifyList, actionByText, fillByText, selectByText, checkByText, uncheckByText, -} from '../src/page-scripts.mjs'; +} from '../src/page-scripts.js'; // ─── buildRunCode ─────────────────────────────────────────────────────────── diff --git a/packages/core/test/parser.test.mjs b/packages/core/test/parser.test.ts similarity index 99% rename from packages/core/test/parser.test.mjs rename to packages/core/test/parser.test.ts index dcace77..d65ee88 100644 --- a/packages/core/test/parser.test.mjs +++ b/packages/core/test/parser.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { parseInput, ALIASES, ALL_COMMANDS, booleanOptions } from '../src/parser.mjs'; +import { parseInput, ALIASES, ALL_COMMANDS, booleanOptions } from '../src/parser.js'; describe('parseInput', () => { it('parses a basic command', () => { diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json new file mode 100644 index 0000000..0496317 --- /dev/null +++ b/packages/core/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist", + "composite": true + }, + "include": ["src"] +} diff --git a/packages/core/vitest.config.mjs b/packages/core/vitest.config.ts similarity index 84% rename from packages/core/vitest.config.mjs rename to packages/core/vitest.config.ts index 26c18fe..ecb2a09 100644 --- a/packages/core/vitest.config.mjs +++ b/packages/core/vitest.config.ts @@ -2,7 +2,7 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { - include: ['test/**/*.test.mjs'], + include: ['test/**/*.test.ts'], coverage: { provider: 'v8', include: ['src/**'], diff --git a/packages/extension/e2e/commands/fixtures.mjs b/packages/extension/e2e/commands/fixtures.mjs index 7126533..882519e 100644 --- a/packages/extension/e2e/commands/fixtures.mjs +++ b/packages/extension/e2e/commands/fixtures.mjs @@ -6,8 +6,7 @@ */ import { test as base } from '@playwright/test'; -import { Engine } from '../../../core/src/engine.mjs'; -import { CommandServer } from '../../../core/src/extension-server.mjs'; +import { Engine, CommandServer } from '@playwright-repl/core'; export const test = base.extend({ // Worker-scoped: one Engine + CommandServer per worker diff --git a/packages/extension/panel/panel.js b/packages/extension/panel/panel.js index 90e837c..73e1922 100644 --- a/packages/extension/panel/panel.js +++ b/packages/extension/panel/panel.js @@ -225,11 +225,20 @@ function addScreenshot(base64) { const saveBtnEl = document.createElement("button"); saveBtnEl.className = "screenshot-btn"; saveBtnEl.textContent = "Save"; - saveBtnEl.addEventListener("click", () => { - const a = document.createElement("a"); - a.href = dataUrl; - a.download = "screenshot-" + new Date().toISOString().slice(0, 19).replace(/:/g, "-") + ".png"; - a.click(); + saveBtnEl.addEventListener("click", async () => { + try { + const handle = await window.showSaveFilePicker({ + suggestedName: "screenshot-" + new Date().toISOString().slice(0, 19).replace(/:/g, "-") + ".png", + types: [{ description: "PNG images", accept: { "image/png": [".png"] } }], + }); + const res = await fetch(dataUrl); + const blob = await res.blob(); + const writable = await handle.createWritable(); + await writable.write(blob); + await writable.close(); + } catch (e) { + if (e.name !== "AbortError") console.error("Save failed:", e); + } }); actions.appendChild(saveBtnEl); @@ -829,7 +838,7 @@ openBtn.addEventListener("click", () => { // --- Save button --- -saveBtn.addEventListener("click", () => { +saveBtn.addEventListener("click", async () => { const content = editor.value; if (!content.trim()) { addInfo("Nothing to save."); @@ -837,19 +846,20 @@ saveBtn.addEventListener("click", () => { } const defaultName = currentFilename || "commands-" + new Date().toISOString().slice(0, 10) + ".pw"; - const filename = prompt("Save as:", defaultName); - if (!filename) return; - const finalName = filename.endsWith(".pw") ? filename : filename + ".pw"; - const blob = new Blob([content], { type: "text/plain" }); - const url = URL.createObjectURL(blob); - const a = document.createElement("a"); - a.href = url; - a.download = finalName; - a.click(); - URL.revokeObjectURL(url); - currentFilename = finalName; - updateFileInfo(); - addSuccess("Saved as " + finalName); + try { + const handle = await window.showSaveFilePicker({ + suggestedName: defaultName, + types: [{ description: "PW command files", accept: { "text/plain": [".pw"] } }], + }); + const writable = await handle.createWritable(); + await writable.write(content); + await writable.close(); + currentFilename = handle.name; + updateFileInfo(); + addSuccess("Saved as " + handle.name); + } catch (e) { + if (e.name !== "AbortError") addError("Save failed: " + e.message); + } }); // --- Export button --- @@ -980,11 +990,20 @@ lightboxCloseBtn.addEventListener("click", () => { lightboxImg.src = ""; }); -lightboxSaveBtn.addEventListener("click", () => { - const a = document.createElement("a"); - a.href = lightboxImg.src; - a.download = "screenshot-" + new Date().toISOString().slice(0, 19).replace(/:/g, "-") + ".png"; - a.click(); +lightboxSaveBtn.addEventListener("click", async () => { + try { + const handle = await window.showSaveFilePicker({ + suggestedName: "screenshot-" + new Date().toISOString().slice(0, 19).replace(/:/g, "-") + ".png", + types: [{ description: "PNG images", accept: { "image/png": [".png"] } }], + }); + const res = await fetch(lightboxImg.src); + const blob = await res.blob(); + const writable = await handle.createWritable(); + await writable.write(blob); + await writable.close(); + } catch (e) { + if (e.name !== "AbortError") console.error("Save failed:", e); + } }); document.addEventListener("keydown", (e) => { diff --git a/packages/extension/test-results/.last-run.json b/packages/extension/test-results/.last-run.json new file mode 100644 index 0000000..cbcc1fb --- /dev/null +++ b/packages/extension/test-results/.last-run.json @@ -0,0 +1,4 @@ +{ + "status": "passed", + "failedTests": [] +} \ No newline at end of file diff --git a/packages/extension/test/panel.test.js b/packages/extension/test/panel.test.js index 686190b..5c32e6d 100644 --- a/packages/extension/test/panel.test.js +++ b/packages/extension/test/panel.test.js @@ -711,16 +711,22 @@ describe("panel.js", () => { // --- Save button --- it("save button saves editor content", async () => { - window.prompt = vi.fn().mockReturnValue("test.pw"); + const mockWritable = { write: vi.fn(), close: vi.fn() }; + const mockHandle = { name: "test.pw", createWritable: vi.fn().mockResolvedValue(mockWritable) }; + window.showSaveFilePicker = vi.fn().mockResolvedValue(mockHandle); await import("../panel/panel.js"); const editor = document.getElementById("editor"); editor.value = "goto https://example.com"; editor.dispatchEvent(new Event("input")); document.getElementById("save-btn").click(); - expect(document.getElementById("output").textContent).toContain( - "Saved as test.pw" - ); + await vi.waitFor(() => { + expect(document.getElementById("output").textContent).toContain( + "Saved as test.pw" + ); + }); + expect(mockWritable.write).toHaveBeenCalledWith("goto https://example.com"); + expect(mockWritable.close).toHaveBeenCalled(); }); // --- Open button --- diff --git a/packages/repl-ext/dist/background.js b/packages/repl-ext/dist/background.js deleted file mode 100644 index f389a28..0000000 --- a/packages/repl-ext/dist/background.js +++ /dev/null @@ -1,143614 +0,0 @@ -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$1(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$1) { - const base64 = requireBase64Js(); - const ieee7542 = requireIeee754(); - const customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; - exports$1.Buffer = Buffer2; - exports$1.SlowBuffer = SlowBuffer; - exports$1.INSPECT_MAX_BYTES = 50; - const K_MAX_LENGTH = 2147483647; - exports$1.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$1.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$1) { - Object.defineProperty(exports$1, "__esModule", { value: true }); - exports$1.bufferFrom = exports$1.bufferAllocUnsafe = exports$1.Buffer = void 0; - const buffer_1 = requireBuffer$2(); - Object.defineProperty(exports$1, "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$1.bufferAllocUnsafe = bufferAllocUnsafe; - const bufferFrom = buffer_1.Buffer.from || bufferV0P12Ponyfill; - exports$1.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$1) { - 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$1.isArgumentsObject = isArgumentsObject; - exports$1.isGeneratorFunction = isGeneratorFunction2; - exports$1.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$1.isPromise = isPromise; - function isArrayBufferView(value) { - if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { - return ArrayBuffer.isView(value); - } - return isTypedArray2(value) || isDataView(value); - } - exports$1.isArrayBufferView = isArrayBufferView; - function isUint8Array(value) { - return whichTypedArray2(value) === "Uint8Array"; - } - exports$1.isUint8Array = isUint8Array; - function isUint8ClampedArray(value) { - return whichTypedArray2(value) === "Uint8ClampedArray"; - } - exports$1.isUint8ClampedArray = isUint8ClampedArray; - function isUint16Array(value) { - return whichTypedArray2(value) === "Uint16Array"; - } - exports$1.isUint16Array = isUint16Array; - function isUint32Array(value) { - return whichTypedArray2(value) === "Uint32Array"; - } - exports$1.isUint32Array = isUint32Array; - function isInt8Array(value) { - return whichTypedArray2(value) === "Int8Array"; - } - exports$1.isInt8Array = isInt8Array; - function isInt16Array(value) { - return whichTypedArray2(value) === "Int16Array"; - } - exports$1.isInt16Array = isInt16Array; - function isInt32Array(value) { - return whichTypedArray2(value) === "Int32Array"; - } - exports$1.isInt32Array = isInt32Array; - function isFloat32Array(value) { - return whichTypedArray2(value) === "Float32Array"; - } - exports$1.isFloat32Array = isFloat32Array; - function isFloat64Array(value) { - return whichTypedArray2(value) === "Float64Array"; - } - exports$1.isFloat64Array = isFloat64Array; - function isBigInt64Array(value) { - return whichTypedArray2(value) === "BigInt64Array"; - } - exports$1.isBigInt64Array = isBigInt64Array; - function isBigUint64Array(value) { - return whichTypedArray2(value) === "BigUint64Array"; - } - exports$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.isSharedArrayBuffer = isSharedArrayBuffer; - function isAsyncFunction(value) { - return ObjectToString(value) === "[object AsyncFunction]"; - } - exports$1.isAsyncFunction = isAsyncFunction; - function isMapIterator(value) { - return ObjectToString(value) === "[object Map Iterator]"; - } - exports$1.isMapIterator = isMapIterator; - function isSetIterator(value) { - return ObjectToString(value) === "[object Set Iterator]"; - } - exports$1.isSetIterator = isSetIterator; - function isGeneratorObject(value) { - return ObjectToString(value) === "[object Generator]"; - } - exports$1.isGeneratorObject = isGeneratorObject; - function isWebAssemblyCompiledModule(value) { - return ObjectToString(value) === "[object WebAssembly.Module]"; - } - exports$1.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; - function isNumberObject(value) { - return checkBoxedPrimitive(value, numberValue); - } - exports$1.isNumberObject = isNumberObject; - function isStringObject(value) { - return checkBoxedPrimitive(value, stringValue); - } - exports$1.isStringObject = isStringObject; - function isBooleanObject(value) { - return checkBoxedPrimitive(value, booleanValue); - } - exports$1.isBooleanObject = isBooleanObject; - function isBigIntObject(value) { - return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); - } - exports$1.isBigIntObject = isBigIntObject; - function isSymbolObject(value) { - return SymbolSupported && checkBoxedPrimitive(value, symbolValue); - } - exports$1.isSymbolObject = isSymbolObject; - function isBoxedPrimitive(value) { - return isNumberObject(value) || isStringObject(value) || isBooleanObject(value) || isBigIntObject(value) || isSymbolObject(value); - } - exports$1.isBoxedPrimitive = isBoxedPrimitive; - function isAnyArrayBuffer(value) { - return typeof Uint8Array !== "undefined" && (isArrayBuffer(value) || isSharedArrayBuffer(value)); - } - exports$1.isAnyArrayBuffer = isAnyArrayBuffer; - ["isProxy", "isExternal", "isModuleNamespaceObject"].forEach(function(method) { - Object.defineProperty(exports$1, 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$1) { - 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$1.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$1.deprecate = function(fn, msg) { - if (typeof process !== "undefined" && process.noDeprecation === true) { - return fn; - } - if (typeof process === "undefined") { - return function() { - return exports$1.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$1.debuglog = function(set2) { - set2 = set2.toUpperCase(); - if (!debugs[set2]) { - if (debugEnvRegex.test(set2)) { - var pid = process.pid; - debugs[set2] = function() { - var msg = exports$1.format.apply(exports$1, 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$1._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$1.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$1.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$1.types = requireTypes(); - function isArray2(ar) { - return Array.isArray(ar); - } - exports$1.isArray = isArray2; - function isBoolean(arg) { - return typeof arg === "boolean"; - } - exports$1.isBoolean = isBoolean; - function isNull(arg) { - return arg === null; - } - exports$1.isNull = isNull; - function isNullOrUndefined(arg) { - return arg == null; - } - exports$1.isNullOrUndefined = isNullOrUndefined; - function isNumber(arg) { - return typeof arg === "number"; - } - exports$1.isNumber = isNumber; - function isString2(arg) { - return typeof arg === "string"; - } - exports$1.isString = isString2; - function isSymbol(arg) { - return typeof arg === "symbol"; - } - exports$1.isSymbol = isSymbol; - function isUndefined(arg) { - return arg === void 0; - } - exports$1.isUndefined = isUndefined; - function isRegExp2(re2) { - return isObject2(re2) && objectToString(re2) === "[object RegExp]"; - } - exports$1.isRegExp = isRegExp2; - exports$1.types.isRegExp = isRegExp2; - function isObject2(arg) { - return typeof arg === "object" && arg !== null; - } - exports$1.isObject = isObject2; - function isDate2(d) { - return isObject2(d) && objectToString(d) === "[object Date]"; - } - exports$1.isDate = isDate2; - exports$1.types.isDate = isDate2; - function isError2(e) { - return isObject2(e) && (objectToString(e) === "[object Error]" || e instanceof Error); - } - exports$1.isError = isError2; - exports$1.types.isNativeError = isError2; - function isFunction(arg) { - return typeof arg === "function"; - } - exports$1.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$1.isPrimitive = isPrimitive; - exports$1.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$1.log = function() { - console.log("%s - %s", timestamp2(), exports$1.format.apply(exports$1, arguments)); - }; - exports$1.inherits = requireInherits_browser$1(); - exports$1._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$1.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$1.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$1.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$1) { - Object.defineProperty(exports$1, "__esModule", { value: true }); - exports$1.E = exports$1.AssertionError = exports$1.message = exports$1.RangeError = exports$1.TypeError = exports$1.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$1.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$1.Error.captureStackTrace(this, options2.stackStartFunction); - } - } - exports$1.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$1.message = message; - function E(sym, val) { - messages2[sym] = typeof val === "function" ? val : String(val); - } - exports$1.E = E; - exports$1.Error = makeNodeError(g.Error); - exports$1.TypeError = makeNodeError(g.TypeError); - exports$1.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$1) { - Object.defineProperty(exports$1, "__esModule", { value: true }); - exports$1.strToEncoding = exports$1.assertEncoding = exports$1.ENCODING_UTF8 = void 0; - const buffer_1 = requireBuffer$1(); - const errors2 = requireErrors$1(); - exports$1.ENCODING_UTF8 = "utf8"; - function assertEncoding(encoding2) { - if (encoding2 && !buffer_1.Buffer.isEncoding(encoding2)) - throw new errors2.TypeError("ERR_INVALID_OPT_VALUE_ENCODING", encoding2); - } - exports$1.assertEncoding = assertEncoding; - function strToEncoding(str, encoding2) { - if (!encoding2 || encoding2 === exports$1.ENCODING_UTF8) - return str; - if (encoding2 === "buffer") - return new buffer_1.Buffer(str); - return new buffer_1.Buffer(str).toString(encoding2); - } - exports$1.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$1) { - var formatRegExp = /%[sdj%]/g; - exports$1.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$1.deprecate = function(fn, msg) { - if (isUndefined(commonjsGlobal.process)) { - return function() { - return exports$1.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$1.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$1.format.apply(exports$1, 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$1._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$1.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$1.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$1.isArray = isArray2; - function isBoolean(arg) { - return typeof arg === "boolean"; - } - exports$1.isBoolean = isBoolean; - function isNull(arg) { - return arg === null; - } - exports$1.isNull = isNull; - function isNullOrUndefined(arg) { - return arg == null; - } - exports$1.isNullOrUndefined = isNullOrUndefined; - function isNumber(arg) { - return typeof arg === "number"; - } - exports$1.isNumber = isNumber; - function isString2(arg) { - return typeof arg === "string"; - } - exports$1.isString = isString2; - function isSymbol(arg) { - return typeof arg === "symbol"; - } - exports$1.isSymbol = isSymbol; - function isUndefined(arg) { - return arg === void 0; - } - exports$1.isUndefined = isUndefined; - function isRegExp2(re2) { - return isObject2(re2) && objectToString(re2) === "[object RegExp]"; - } - exports$1.isRegExp = isRegExp2; - function isObject2(arg) { - return typeof arg === "object" && arg !== null; - } - exports$1.isObject = isObject2; - function isDate2(d) { - return isObject2(d) && objectToString(d) === "[object Date]"; - } - exports$1.isDate = isDate2; - function isError2(e) { - return isObject2(e) && (objectToString(e) === "[object Error]" || e instanceof Error); - } - exports$1.isError = isError2; - function isFunction(arg) { - return typeof arg === "function"; - } - exports$1.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$1.isPrimitive = isPrimitive; - exports$1.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$1.log = function() { - console.log("%s - %s", timestamp2(), exports$1.format.apply(exports$1, arguments)); - }; - exports$1.inherits = requireInherits_browser(); - exports$1._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$1) { - Object.defineProperty(exports$1, "__esModule", { value: true }); - exports$1.File = exports$1.Link = exports$1.Node = exports$1.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$1.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$1.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$1.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$1.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$1.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$1) { - 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$1); - exports$1.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$1) { - (function(root) { - var freeExports = exports$1 && !exports$1.nodeType && exports$1; - 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$1({ - __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$1) { - Object.defineProperty(exports$1, "__esModule", { value: true }); - exports$1.unixify = exports$1.bufferToEncoding = exports$1.getWriteSyncArgs = exports$1.getWriteArgs = exports$1.bufToUint8 = exports$1.dataToBuffer = exports$1.validateFd = exports$1.isFd = exports$1.flagsToNumber = exports$1.genRndStr6 = exports$1.createError = exports$1.pathToFilename = exports$1.nullCheck = exports$1.modeToNumber = exports$1.validateCallback = exports$1.promisify = exports$1.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$1.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$1.promisify = promisify2; - function validateCallback(callback) { - if (typeof callback !== "function") - throw TypeError(constants_1.ERRSTR.CB); - return callback; - } - exports$1.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$1.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$1.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$1.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$1.createError = createError; - function genRndStr6() { - const str = (Math.random() + 1).toString(36).substring(2, 8); - if (str.length === 6) - return str; - else - return genRndStr6(); - } - exports$1.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$1.flagsToNumber = flagsToNumber; - function isFd(path2) { - return path2 >>> 0 === path2; - } - exports$1.isFd = isFd; - function validateFd(fd) { - if (!isFd(fd)) - throw TypeError(constants_1.ERRSTR.FD); - } - exports$1.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$1.dataToBuffer = dataToBuffer; - const bufToUint8 = (buf) => new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); - exports$1.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$1.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$1.getWriteSyncArgs = getWriteSyncArgs; - function bufferToEncoding(buffer2, encoding2) { - if (!encoding2 || encoding2 === "buffer") - return buffer2; - else - return buffer2.toString(encoding2); - } - exports$1.bufferToEncoding = bufferToEncoding; - const isSeparator = (str, i) => { - let char = str[i]; - return i > 0 && (char === "/" || exports$1.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$1.isWin) { - filepath = normalizePath(filepath, stripTrailing); - return filepath.replace(/^([a-zA-Z]+:|\.\/)/, ""); - } - return filepath; - }; - exports$1.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$1) { - Object.defineProperty(exports$1, "__esModule", { value: true }); - exports$1.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$1.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$1.toTreeSync = toTreeSync; - })(print); - return print; -} -var options$1 = {}; -var hasRequiredOptions; -function requireOptions() { - if (hasRequiredOptions) return options$1; - hasRequiredOptions = 1; - (function(exports$1) { - Object.defineProperty(exports$1, "__esModule", { value: true }); - exports$1.getWriteFileOptions = exports$1.writeFileDefaults = exports$1.getRealpathOptsAndCb = exports$1.getRealpathOptions = exports$1.getStatOptsAndCb = exports$1.getStatOptions = exports$1.getAppendFileOptsAndCb = exports$1.getAppendFileOpts = exports$1.getReaddirOptsAndCb = exports$1.getReaddirOptions = exports$1.getReadFileOptions = exports$1.getRmOptsAndCb = exports$1.getRmdirOptions = exports$1.getDefaultOptsAndCb = exports$1.getDefaultOpts = exports$1.optsDefaults = exports$1.optsAndCbGenerator = exports$1.optsGenerator = exports$1.getOptions = exports$1.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$1.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$1.getOptions = getOptions2; - function optsGenerator(defaults) { - return (options2) => getOptions2(defaults, options2); - } - exports$1.optsGenerator = optsGenerator; - function optsAndCbGenerator(getOpts) { - return (options2, callback) => typeof options2 === "function" ? [getOpts(), options2] : [getOpts(options2), (0, util_1.validateCallback)(callback)]; - } - exports$1.optsAndCbGenerator = optsAndCbGenerator; - exports$1.optsDefaults = { - encoding: "utf8" - }; - exports$1.getDefaultOpts = optsGenerator(exports$1.optsDefaults); - exports$1.getDefaultOptsAndCb = optsAndCbGenerator(exports$1.getDefaultOpts); - const rmdirDefaults = { - recursive: false - }; - const getRmdirOptions = (options2) => { - return Object.assign({}, rmdirDefaults, options2); - }; - exports$1.getRmdirOptions = getRmdirOptions; - const getRmOpts = optsGenerator(exports$1.optsDefaults); - exports$1.getRmOptsAndCb = optsAndCbGenerator(getRmOpts); - const readFileOptsDefaults = { - flag: "r" - }; - exports$1.getReadFileOptions = optsGenerator(readFileOptsDefaults); - const readdirDefaults = { - encoding: "utf8", - recursive: false, - withFileTypes: false - }; - exports$1.getReaddirOptions = optsGenerator(readdirDefaults); - exports$1.getReaddirOptsAndCb = optsAndCbGenerator(exports$1.getReaddirOptions); - const appendFileDefaults = { - encoding: "utf8", - mode: 438, - flag: constants_1.FLAGS[constants_1.FLAGS.a] - }; - exports$1.getAppendFileOpts = optsGenerator(appendFileDefaults); - exports$1.getAppendFileOptsAndCb = optsAndCbGenerator(exports$1.getAppendFileOpts); - const statDefaults = { - bigint: false - }; - const getStatOptions = (options2 = {}) => Object.assign({}, statDefaults, options2); - exports$1.getStatOptions = getStatOptions; - const getStatOptsAndCb = (options2, callback) => typeof options2 === "function" ? [(0, exports$1.getStatOptions)(), options2] : [(0, exports$1.getStatOptions)(options2), (0, util_1.validateCallback)(callback)]; - exports$1.getStatOptsAndCb = getStatOptsAndCb; - const realpathDefaults = exports$1.optsDefaults; - exports$1.getRealpathOptions = optsGenerator(realpathDefaults); - exports$1.getRealpathOptsAndCb = optsAndCbGenerator(exports$1.getRealpathOptions); - exports$1.writeFileDefaults = { - encoding: "utf8", - mode: 438, - flag: constants_1.FLAGS[constants_1.FLAGS.w] - }; - exports$1.getWriteFileOptions = optsGenerator(exports$1.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$1) { - Object.defineProperty(exports$1, "__esModule", { value: true }); - exports$1.memfs = exports$1.fs = exports$1.createFsFromVolume = exports$1.vol = exports$1.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$1.Volume = volume_1.Volume; - exports$1.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$1.createFsFromVolume = createFsFromVolume; - exports$1.fs = createFsFromVolume(exports$1.vol); - const memfs = (json = {}, cwd = "/") => { - const vol = exports$1.Volume.fromNestedJSON(json, cwd); - const fs2 = createFsFromVolume(vol); - return { fs: fs2, vol }; - }; - exports$1.memfs = memfs; - module.exports = Object.assign(Object.assign({}, module.exports), exports$1.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$1) { - var RetryOperation = requireRetry_operation(); - exports$1.operation = function(options2) { - var timeouts = exports$1.timeouts(options2); - return new RetryOperation(timeouts, { - forever: options2 && options2.forever, - unref: options2 && options2.unref, - maxRetryTime: options2 && options2.maxRetryTime - }); - }; - exports$1.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$1.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$1.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$1.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$1) { - exports$1.formatArgs = formatArgs; - exports$1.save = save; - exports$1.load = load; - exports$1.useColors = useColors; - exports$1.storage = localstorage(); - exports$1.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$1.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$1.log = console.debug || console.log || (() => { - }); - function save(namespaces) { - try { - if (namespaces) { - exports$1.storage.setItem("debug", namespaces); - } else { - exports$1.storage.removeItem("debug"); - } - } catch (error2) { - } - } - function load() { - let r; - try { - r = exports$1.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$1); - 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$1) { - exports$1 = module.exports = require_stream_readable$2(); - exports$1.Stream = exports$1; - exports$1.Readable = exports$1; - exports$1.Writable = require_stream_writable$2(); - exports$1.Duplex = require_stream_duplex$2(); - exports$1.Transform = require_stream_transform$2(); - exports$1.PassThrough = require_stream_passthrough$2(); - exports$1.finished = requireEndOfStream$3(); - exports$1.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$1 = sha_js.exports = function SHA(algorithm) { - algorithm = algorithm.toLowerCase(); - var Algorithm = exports$1[algorithm]; - if (!Algorithm) throw new Error(algorithm + " is not supported (we accept pull requests)"); - return new Algorithm(); - }; - exports$1.sha = requireSha$1(); - exports$1.sha1 = requireSha1(); - exports$1.sha224 = requireSha224(); - exports$1.sha256 = requireSha256(); - exports$1.sha384 = requireSha384(); - exports$1.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$1) { - exports$1["des-ecb"] = { - key: 8, - iv: 0 - }; - exports$1["des-cbc"] = exports$1.des = { - key: 8, - iv: 8 - }; - exports$1["des-ede3-cbc"] = exports$1.des3 = { - key: 24, - iv: 8 - }; - exports$1["des-ede3"] = { - key: 24, - iv: 0 - }; - exports$1["des-ede-cbc"] = { - key: 16, - iv: 8 - }; - exports$1["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$1) { - 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$1.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$1) { - 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$1.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$1) { - exports$1 = module.exports = require_stream_readable$1(); - exports$1.Stream = exports$1; - exports$1.Readable = exports$1; - exports$1.Writable = require_stream_writable$1(); - exports$1.Duplex = require_stream_duplex$1(); - exports$1.Transform = require_stream_transform$1(); - exports$1.PassThrough = require_stream_passthrough$1(); - exports$1.finished = requireEndOfStream$2(); - exports$1.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$1) { - 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$1.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$1) { - 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$1.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$1) { - var utils2 = exports$1; - 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$1) { - var utils2 = exports$1; - 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$1) { - var curve2 = exports$1; - 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$1) { - var hash2 = exports$1; - 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$1) { - var curves2 = exports$1; - 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$1) { - var elliptic2 = exports$1; - 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$1) { - 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$1.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$1) { - 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$1.tagClass = { - 0: "universal", - 1: "application", - 2: "context", - 3: "private" - }; - exports$1.tagClassByName = reverse(exports$1.tagClass); - exports$1.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$1.tagByName = reverse(exports$1.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$1) { - const encoders2 = exports$1; - 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$1) { - const decoders2 = exports$1; - decoders2.der = requireDer(); - decoders2.pem = requirePem(); - })(decoders); - return decoders; -} -var hasRequiredApi; -function requireApi() { - if (hasRequiredApi) return api; - hasRequiredApi = 1; - (function(exports$1) { - const encoders2 = requireEncoders(); - const decoders2 = requireDecoders(); - const inherits = requireInherits_browser$1(); - const api2 = exports$1; - 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$1) { - const base2 = exports$1; - 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$1) { - const constants2 = exports$1; - 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$1) { - const asn12 = exports$1; - 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$1) { - 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$1.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$1) { - 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$1.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$1) { - exports$1.publicEncrypt = requirePublicEncrypt(); - exports$1.privateDecrypt = requirePrivateDecrypt(); - exports$1.privateEncrypt = function privateEncrypt(key2, buf) { - return exports$1.publicEncrypt(key2, buf, true); - }; - exports$1.publicDecrypt = function publicDecrypt(key2, buf) { - return exports$1.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$1) { - var TYPED_OK = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Int32Array !== "undefined"; - function _has(obj, key2) { - return Object.prototype.hasOwnProperty.call(obj, key2); - } - exports$1.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$1.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$1.setTyped = function(on) { - if (on) { - exports$1.Buf8 = Uint8Array; - exports$1.Buf16 = Uint16Array; - exports$1.Buf32 = Int32Array; - exports$1.assign(exports$1, fnTyped); - } else { - exports$1.Buf8 = Array; - exports$1.Buf16 = Array; - exports$1.Buf32 = Array; - exports$1.assign(exports$1, fnUntyped); - } - }; - exports$1.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$1) { - var assert2 = requireAssert(); - var Zstream = requireZstream(); - var zlib_deflate = requireDeflate(); - var zlib_inflate = requireInflate(); - var constants2 = requireConstants$4(); - for (var key2 in constants2) { - exports$1[key2] = constants2[key2]; - } - exports$1.NONE = 0; - exports$1.DEFLATE = 1; - exports$1.INFLATE = 2; - exports$1.GZIP = 3; - exports$1.GUNZIP = 4; - exports$1.DEFLATERAW = 5; - exports$1.INFLATERAW = 6; - exports$1.UNZIP = 7; - var GZIP_HEADER_ID1 = 31; - var GZIP_HEADER_ID2 = 139; - function Zlib(mode) { - if (typeof mode !== "number" || mode < exports$1.DEFLATE || mode > exports$1.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$1.UNZIP); - if (this.mode === exports$1.DEFLATE || this.mode === exports$1.GZIP || this.mode === exports$1.DEFLATERAW) { - zlib_deflate.deflateEnd(this.strm); - } else if (this.mode === exports$1.INFLATE || this.mode === exports$1.GUNZIP || this.mode === exports$1.INFLATERAW || this.mode === exports$1.UNZIP) { - zlib_inflate.inflateEnd(this.strm); - } - this.mode = exports$1.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$1.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$1.Z_NO_FLUSH && flush !== exports$1.Z_PARTIAL_FLUSH && flush !== exports$1.Z_SYNC_FLUSH && flush !== exports$1.Z_FULL_FLUSH && flush !== exports$1.Z_FINISH && flush !== exports$1.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$1.DEFLATE: - case exports$1.GZIP: - case exports$1.DEFLATERAW: - this.err = zlib_deflate.deflate(this.strm, this.flush); - break; - case exports$1.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$1.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$1.GUNZIP; - } else { - this.mode = exports$1.INFLATE; - } - break; - default: - throw new Error("invalid number of gzip magic number bytes read"); - } - // fallthrough - case exports$1.INFLATE: - case exports$1.GUNZIP: - case exports$1.INFLATERAW: - this.err = zlib_inflate.inflate( - this.strm, - this.flush - // If data was encoded with dictionary - ); - if (this.err === exports$1.Z_NEED_DICT && this.dictionary) { - this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary); - if (this.err === exports$1.Z_OK) { - this.err = zlib_inflate.inflate(this.strm, this.flush); - } else if (this.err === exports$1.Z_DATA_ERROR) { - this.err = exports$1.Z_NEED_DICT; - } - } - while (this.strm.avail_in > 0 && this.mode === exports$1.GUNZIP && this.err === exports$1.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$1.Z_OK: - case exports$1.Z_BUF_ERROR: - if (this.strm.avail_out !== 0 && this.flush === exports$1.Z_FINISH) { - this._error("unexpected end of file"); - return false; - } - break; - case exports$1.Z_STREAM_END: - break; - case exports$1.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$1.Z_FILTERED || strategy === exports$1.Z_HUFFMAN_ONLY || strategy === exports$1.Z_RLE || strategy === exports$1.Z_FIXED || strategy === exports$1.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$1.Z_NO_FLUSH; - this.err = exports$1.Z_OK; - if (this.mode === exports$1.GZIP || this.mode === exports$1.GUNZIP) { - this.windowBits += 16; - } - if (this.mode === exports$1.UNZIP) { - this.windowBits += 32; - } - if (this.mode === exports$1.DEFLATERAW || this.mode === exports$1.INFLATERAW) { - this.windowBits = -1 * this.windowBits; - } - this.strm = new Zstream(); - switch (this.mode) { - case exports$1.DEFLATE: - case exports$1.GZIP: - case exports$1.DEFLATERAW: - this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports$1.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy); - break; - case exports$1.INFLATE: - case exports$1.GUNZIP: - case exports$1.INFLATERAW: - case exports$1.UNZIP: - this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits); - break; - default: - throw new Error("Unknown mode " + this.mode); - } - if (this.err !== exports$1.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$1.Z_OK; - switch (this.mode) { - case exports$1.DEFLATE: - case exports$1.DEFLATERAW: - this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary); - break; - } - if (this.err !== exports$1.Z_OK) { - this._error("Failed to set dictionary"); - } - }; - Zlib.prototype._reset = function() { - this.err = exports$1.Z_OK; - switch (this.mode) { - case exports$1.DEFLATE: - case exports$1.DEFLATERAW: - case exports$1.GZIP: - this.err = zlib_deflate.deflateReset(this.strm); - break; - case exports$1.INFLATE: - case exports$1.INFLATERAW: - case exports$1.GUNZIP: - this.err = zlib_inflate.inflateReset(this.strm); - break; - } - if (this.err !== exports$1.Z_OK) { - this._error("Failed to reset stream"); - } - }; - exports$1.Zlib = Zlib; - })(binding); - return binding; -} -var hasRequiredLib; -function requireLib() { - if (hasRequiredLib) return lib; - hasRequiredLib = 1; - (function(exports$1) { - 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$1, 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$1, "codes", { - enumerable: true, - value: Object.freeze(codes), - writable: false - }); - exports$1.Deflate = Deflate; - exports$1.Inflate = Inflate; - exports$1.Gzip = Gzip; - exports$1.Gunzip = Gunzip; - exports$1.DeflateRaw = DeflateRaw; - exports$1.InflateRaw = InflateRaw; - exports$1.Unzip = Unzip; - exports$1.createDeflate = function(o) { - return new Deflate(o); - }; - exports$1.createInflate = function(o) { - return new Inflate(o); - }; - exports$1.createDeflateRaw = function(o) { - return new DeflateRaw(o); - }; - exports$1.createInflateRaw = function(o) { - return new InflateRaw(o); - }; - exports$1.createGzip = function(o) { - return new Gzip(o); - }; - exports$1.createGunzip = function(o) { - return new Gunzip(o); - }; - exports$1.createUnzip = function(o) { - return new Unzip(o); - }; - exports$1.deflate = function(buffer2, opts, callback) { - if (typeof opts === "function") { - callback = opts; - opts = {}; - } - return zlibBuffer(new Deflate(opts), buffer2, callback); - }; - exports$1.deflateSync = function(buffer2, opts) { - return zlibBufferSync(new Deflate(opts), buffer2); - }; - exports$1.gzip = function(buffer2, opts, callback) { - if (typeof opts === "function") { - callback = opts; - opts = {}; - } - return zlibBuffer(new Gzip(opts), buffer2, callback); - }; - exports$1.gzipSync = function(buffer2, opts) { - return zlibBufferSync(new Gzip(opts), buffer2); - }; - exports$1.deflateRaw = function(buffer2, opts, callback) { - if (typeof opts === "function") { - callback = opts; - opts = {}; - } - return zlibBuffer(new DeflateRaw(opts), buffer2, callback); - }; - exports$1.deflateRawSync = function(buffer2, opts) { - return zlibBufferSync(new DeflateRaw(opts), buffer2); - }; - exports$1.unzip = function(buffer2, opts, callback) { - if (typeof opts === "function") { - callback = opts; - opts = {}; - } - return zlibBuffer(new Unzip(opts), buffer2, callback); - }; - exports$1.unzipSync = function(buffer2, opts) { - return zlibBufferSync(new Unzip(opts), buffer2); - }; - exports$1.inflate = function(buffer2, opts, callback) { - if (typeof opts === "function") { - callback = opts; - opts = {}; - } - return zlibBuffer(new Inflate(opts), buffer2, callback); - }; - exports$1.inflateSync = function(buffer2, opts) { - return zlibBufferSync(new Inflate(opts), buffer2); - }; - exports$1.gunzip = function(buffer2, opts, callback) { - if (typeof opts === "function") { - callback = opts; - opts = {}; - } - return zlibBuffer(new Gunzip(opts), buffer2, callback); - }; - exports$1.gunzipSync = function(buffer2, opts) { - return zlibBufferSync(new Gunzip(opts), buffer2); - }; - exports$1.inflateRaw = function(buffer2, opts, callback) { - if (typeof opts === "function") { - callback = opts; - opts = {}; - } - return zlibBuffer(new InflateRaw(opts), buffer2, callback); - }; - exports$1.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$1.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$1.Z_MIN_CHUNK || opts.chunkSize > exports$1.Z_MAX_CHUNK) { - throw new Error("Invalid chunk size: " + opts.chunkSize); - } - } - if (opts.windowBits) { - if (opts.windowBits < exports$1.Z_MIN_WINDOWBITS || opts.windowBits > exports$1.Z_MAX_WINDOWBITS) { - throw new Error("Invalid windowBits: " + opts.windowBits); - } - } - if (opts.level) { - if (opts.level < exports$1.Z_MIN_LEVEL || opts.level > exports$1.Z_MAX_LEVEL) { - throw new Error("Invalid compression level: " + opts.level); - } - } - if (opts.memLevel) { - if (opts.memLevel < exports$1.Z_MIN_MEMLEVEL || opts.memLevel > exports$1.Z_MAX_MEMLEVEL) { - throw new Error("Invalid memLevel: " + opts.memLevel); - } - } - if (opts.strategy) { - if (opts.strategy != exports$1.Z_FILTERED && opts.strategy != exports$1.Z_HUFFMAN_ONLY && opts.strategy != exports$1.Z_RLE && opts.strategy != exports$1.Z_FIXED && opts.strategy != exports$1.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$1.codes[errno]; - self2.emit("error", error2); - }; - var level = exports$1.Z_DEFAULT_COMPRESSION; - if (typeof opts.level === "number") level = opts.level; - var strategy = exports$1.Z_DEFAULT_STRATEGY; - if (typeof opts.strategy === "number") strategy = opts.strategy; - this._handle.init(opts.windowBits || exports$1.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports$1.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$1.Z_MIN_LEVEL || level > exports$1.Z_MAX_LEVEL) { - throw new RangeError("Invalid compression level: " + level); - } - if (strategy != exports$1.Z_FILTERED && strategy != exports$1.Z_HUFFMAN_ONLY && strategy != exports$1.Z_RLE && strategy != exports$1.Z_FIXED && strategy != exports$1.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$1) { - 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$1 = inflateSync; - exports$1.Inflate = Inflate; - exports$1.createInflate = createInflate; - exports$1.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$1) { - const { Argument } = requireArgument(); - const { Command } = requireCommand(); - const { CommanderError, InvalidArgumentError } = requireError(); - const { Help } = requireHelp(); - const { Option } = requireOption(); - exports$1 = module.exports = new Command(); - exports$1.program = exports$1; - exports$1.Argument = Argument; - exports$1.Command = Command; - exports$1.CommanderError = CommanderError; - exports$1.Help = Help; - exports$1.InvalidArgumentError = InvalidArgumentError; - exports$1.InvalidOptionArgumentError = InvalidArgumentError; - exports$1.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$1) { - 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$1) { - (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$1) { - !(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$1["sprintf"] = sprintf2; - exports$1["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$1) { - 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$1, "__esModule", { value: true }); - exports$1.v6 = exports$1.AddressError = exports$1.Address6 = exports$1.Address4 = void 0; - const ipv4_1 = requireIpv4(); - Object.defineProperty(exports$1, "Address4", { enumerable: true, get: function() { - return ipv4_1.Address4; - } }); - const ipv6_1 = requireIpv6(); - Object.defineProperty(exports$1, "Address6", { enumerable: true, get: function() { - return ipv6_1.Address6; - } }); - const address_error_1 = requireAddressError(); - Object.defineProperty(exports$1, "AddressError", { enumerable: true, get: function() { - return address_error_1.AddressError; - } }); - const helpers2 = __importStar(requireHelpers$1()); - exports$1.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$1) { - 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$1, "__esModule", { value: true }); - exports$1.SocksClientError = exports$1.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$1, "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$1.SocksClient = SocksClient; - })(socksclient); - return socksclient; -} -var hasRequiredBuild; -function requireBuild() { - if (hasRequiredBuild) return build; - hasRequiredBuild = 1; - (function(exports$1) { - 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$1, "__esModule", { value: true }); - __exportStar(requireSocksclient(), exports$1); - })(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 = 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.log = (data2) => { - stream2.write(data2.replace(ansiRegex, "")); - stream2.write("\n"); - }; - } - } - log(name, message) { - let cachedDebugger = this._debuggers.get(name); - if (!cachedDebugger) { - cachedDebugger = debug(`pw:${name}`); - this._debuggers.set(name, cachedDebugger); - cachedDebugger.color = debugLoggerColorMap[name] || 0; - } - cachedDebugger(message); - } - isEnabled(name) { - return debug.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$1({ - __proto__: null, - default: index$2 -}, [yazlExports]); -var yauzlExports = requireYauzl(); -const index = /* @__PURE__ */ getDefaultExportFromCjs(yauzlExports); -const index$1 = /* @__PURE__ */ _mergeNamespaces$1({ - __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 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$1) { - exports$1.fetch = isFunction(commonjsGlobal.fetch) && isFunction(commonjsGlobal.ReadableStream); - exports$1.writableStream = isFunction(commonjsGlobal.WritableStream); - exports$1.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$1.arraybuffer = exports$1.fetch || checkTypeSupport("arraybuffer"); - exports$1.msstream = !exports$1.fetch && checkTypeSupport("ms-stream"); - exports$1.mozchunkedarraybuffer = !exports$1.fetch && checkTypeSupport("moz-chunked-arraybuffer"); - exports$1.overrideMimeType = exports$1.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$1) { - exports$1 = module.exports = require_stream_readable(); - exports$1.Stream = exports$1; - exports$1.Readable = exports$1; - exports$1.Writable = require_stream_writable(); - exports$1.Duplex = require_stream_duplex(); - exports$1.Transform = require_stream_transform(); - exports$1.PassThrough = require_stream_passthrough(); - exports$1.finished = requireEndOfStream(); - exports$1.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$1) { - var ClientRequest = requireRequest(); - var response2 = requireResponse(); - var extend2 = requireImmutable(); - var statusCodes = requireBrowser$1(); - var url2 = require$$1$5; - var http2 = exports$1; - 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("pw:android")("Stopping the old driver"); - await this.shell(`am force-stop com.microsoft.playwright.androiddriver`); - if (!this._options.omitDriverInstall) { - debug("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("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("pw:android")("Skipping the driver installation"); - } - debug("pw:android")("Starting the new driver"); - this.shell("am instrument -w com.microsoft.playwright.androiddriver.test/androidx.test.runner.AndroidJUnitRunner").catch((e) => debug("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("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("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("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("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("pw:android")(`exception while removing ${artifactsDir}: ${errors2[i]}`); - }; - gracefullyCloseSet.add(cleanupArtifactsDir); - socket.on("close", async () => { - gracefullyCloseSet.delete(cleanupArtifactsDir); - cleanupArtifactsDir().catch((e) => debug("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("pw:android")("Opening install socket"); - const installSocket = await this._backend.open(`shell:cmd package install ${args.join(" ")} ${content.length}`); - debug("pw:android")("Writing driver bytes: " + content.length); - await installSocket.write(content); - const success = await new Promise((f) => installSocket.on("data", f)); - debug("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("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("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("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("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("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 crxApp2 = from((await this._channel.start(options2 ?? {})).crxApplication); - crxApp2.on("close", onClose); - return crxApp2; - } - 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, "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) - return; - (_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; - } -} -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$1 = /* @__PURE__ */ Object.create(null); - if (!node2.body) { - node2.body = []; - } - while (this.type !== types$1.eof) { - var stmt = this.parseStatement(null, true, exports$1); - 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$1) { - 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$1); - // 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$1) { - if (this.options.ecmaVersion >= 11) { - if (this.eatContextual("as")) { - node2.exported = this.parseModuleExportName(); - this.checkExport(exports$1, 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$1) { - this.next(); - if (this.eat(types$1.star)) { - return this.parseExportAllDeclaration(node2, exports$1); - } - if (this.eat(types$1._default)) { - this.checkExport(exports$1, "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$1, node2.declaration.declarations); - } else { - this.checkExport(exports$1, node2.declaration.id, node2.declaration.id.start); - } - node2.specifiers = []; - node2.source = null; - } else { - node2.declaration = null; - node2.specifiers = this.parseExportSpecifiers(exports$1); - 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$1, name, pos) { - if (!exports$1) { - return; - } - if (typeof name !== "string") { - name = name.type === "Identifier" ? name.name : name.value; - } - if (hasOwn(exports$1, name)) { - this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); - } - exports$1[name] = true; -}; -pp$8.checkPatternExport = function(exports$1, pat) { - var type2 = pat.type; - if (type2 === "Identifier") { - this.checkExport(exports$1, 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$1, 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$1, elt); - } - } - } else if (type2 === "Property") { - this.checkPatternExport(exports$1, pat.value); - } else if (type2 === "AssignmentPattern") { - this.checkPatternExport(exports$1, pat.left); - } else if (type2 === "RestElement") { - this.checkPatternExport(exports$1, pat.argument); - } -}; -pp$8.checkVariableExport = function(exports$1, decls) { - if (!exports$1) { - return; - } - for (var i = 0, list = decls; i < list.length; i += 1) { - var decl = list[i]; - this.checkPatternExport(exports$1, 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$1) { - var node2 = this.startNode(); - node2.local = this.parseModuleExportName(); - node2.exported = this.eatContextual("as") ? this.parseModuleExportName() : node2.local; - this.checkExport( - exports$1, - node2.exported, - node2.exported.start - ); - return this.finishNode(node2, "ExportSpecifier"); -}; -pp$8.parseExportSpecifiers = function(exports$1) { - 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$1)); - } - 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": (snapshot2) => ["assertSnapshot", { snapshot: snapshot2 }] -}; -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 crxApp2 = await this._crx.get({ incognito }) ?? await this._crx.start({ incognito }, serverSideCallMetadata()); - await this._crx.player.run(crxApp2._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 crxApp2 = await this._crx.get({ incognito: false }); - const recorder = crxApp2 == null ? void 0 : crxApp2._recorder(); - if (recorder && crxApp2 && crxApp2._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 crxApp2 = 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 crxApp2._createRecorderApp(recorder); - else - return new EmptyRecorderApp(); - }; - }; - return crxApp2; - } - 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 crxApp2 = new CrxApplication2(this, context, transport); - await crxApp2.attach(incognitoTabId); - return crxApp2; - } - 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(); -browserExports$2.debug; -const INTERACTIVE_ROLES = /* @__PURE__ */ new Set([ - "button", - "link", - "textbox", - "checkbox", - "radio", - "combobox", - "menuitem", - "menuitemcheckbox", - "menuitemradio", - "option", - "slider", - "spinbutton", - "switch", - "tab", - "searchbox", - "treeitem" -]); -let refMap = /* @__PURE__ */ new Map(); -let refCounter = 0; -async function snapshot(page) { - const tree = await page.accessibility.snapshot(); - if (!tree) return "(empty page)"; - refMap.clear(); - refCounter = 0; - return formatNode(tree, 0); -} -function formatNode(node2, indent) { - const lines = []; - const pad = " ".repeat(indent); - const isInteractive = INTERACTIVE_ROLES.has(node2.role); - let ref2 = ""; - if (isInteractive) { - ref2 = `e${++refCounter}`; - refMap.set(ref2, { role: node2.role, name: node2.name }); - } - let desc = `${node2.role}`; - if (node2.name) desc += ` "${node2.name}"`; - if (ref2) desc += ` [ref=${ref2}]`; - const states = []; - if (node2.checked === true) states.push("checked"); - if (node2.checked === "mixed") states.push("mixed"); - if (node2.disabled) states.push("disabled"); - if (node2.expanded === true) states.push("expanded"); - if (node2.expanded === false) states.push("collapsed"); - if (node2.selected) states.push("selected"); - if (node2.pressed === true) states.push("pressed"); - if (node2.readonly) states.push("readonly"); - if (node2.required) states.push("required"); - if (states.length) desc += ` [${states.join(", ")}]`; - if (node2.value !== void 0) desc += `: "${node2.value}"`; - lines.push(`${pad}- ${desc}`); - if (node2.children) { - for (const child of node2.children) { - lines.push(formatNode(child, indent + 1)); - } - } - return lines.join("\n"); -} -function resolveRef(ref2) { - const entry = refMap.get(ref2); - if (!entry) throw new Error(`Unknown ref: ${ref2}. Run "snapshot" first.`); - return entry; -} -function getLocator(page, ref2) { - const entry = resolveRef(ref2); - return page.getByRole(entry.role, { name: entry.name, exact: true }); -} -async function execute(command2, page) { - const [keyword, ...args] = command2.trim().split(/\s+/); - try { - switch (keyword) { - case "snapshot": - return { text: await snapshot(page), isError: false }; - // goto, back, forward, reload are handled in background.ts via Chrome APIs - case "click": { - if (!args[0]) return { text: "Usage: click ", isError: true }; - await getLocator(page, args[0]).click(); - return { text: "Clicked", isError: false }; - } - case "fill": { - if (args.length < 2) return { text: "Usage: fill ", isError: true }; - await getLocator(page, args[0]).fill(args.slice(1).join(" ")); - return { text: "Filled", isError: false }; - } - case "type": { - if (args.length < 2) return { text: "Usage: type ", isError: true }; - await getLocator(page, args[0]).pressSequentially(args.slice(1).join(" ")); - return { text: "Typed", isError: false }; - } - case "press": { - if (args.length < 2) return { text: "Usage: press ", isError: true }; - await getLocator(page, args[0]).press(args.slice(1).join("+")); - return { text: "Pressed", isError: false }; - } - case "hover": { - if (!args[0]) return { text: "Usage: hover ", isError: true }; - await getLocator(page, args[0]).hover(); - return { text: "Hovered", isError: false }; - } - case "select": { - if (args.length < 2) return { text: "Usage: select ", isError: true }; - await getLocator(page, args[0]).selectOption(args.slice(1).join(" ")); - return { text: "Selected", isError: false }; - } - case "check": { - if (!args[0]) return { text: "Usage: check ", isError: true }; - await getLocator(page, args[0]).check(); - return { text: "Checked", isError: false }; - } - case "uncheck": { - if (!args[0]) return { text: "Usage: uncheck ", isError: true }; - await getLocator(page, args[0]).uncheck(); - return { text: "Unchecked", isError: false }; - } - case "screenshot": { - const buf = await page.screenshot(); - const base64 = buf.toString("base64"); - return { text: `data:image/png;base64,${base64}`, isError: false }; - } - case "wait": { - const ms2 = parseInt(args[0]) || 1e3; - await page.waitForTimeout(ms2); - return { text: `Waited ${ms2}ms`, isError: false }; - } - case "title": { - const title = await page.title(); - return { text: title, isError: false }; - } - case "url": - return { text: page.url(), isError: false }; - case "help": - return { - text: [ - "Commands:", - " snapshot — show accessibility tree with refs", - " goto — navigate to URL", - " click — click element", - " fill — fill input with text", - " type — type text character by character", - " press — press key (e.g. Enter, Tab)", - " hover — hover over element", - " select — select option by value", - " check — check checkbox", - " uncheck — uncheck checkbox", - " screenshot — capture screenshot", - " back / forward — navigate history", - " reload — reload page", - " wait [ms] — wait (default 1000ms)", - " title / url — show page title or URL" - ].join("\n"), - isError: false - }; - default: - return { text: `Unknown command: ${keyword}. Type "help" for commands.`, isError: true }; - } - } catch (e) { - return { text: String(e), isError: true }; - } -} -let crxApp = null; -let activePage = null; -let activeTabId = null; -chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }); -chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => { - if (msg.type === "attach") { - attachToTab(msg.tabId).then(sendResponse); - return true; - } - if (msg.type === "run") { - handleCommand(msg.command).then(sendResponse); - return true; - } -}); -function waitForTabLoad(tabId, timeout = 1e4) { - return new Promise((resolve) => { - let timer; - const listener = (id, info) => { - if (id === tabId && info.status === "complete") { - chrome.tabs.onUpdated.removeListener(listener); - clearTimeout(timer); - resolve(); - } - }; - chrome.tabs.onUpdated.addListener(listener); - timer = setTimeout(() => { - chrome.tabs.onUpdated.removeListener(listener); - resolve(); - }, timeout); - }); -} -async function getActiveTabId() { - if (activeTabId) return activeTabId; - const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true }); - return (tab == null ? void 0 : tab.id) ?? null; -} -async function navigateTab(url2) { - const tabId = await getActiveTabId(); - if (!tabId) return { text: "No active tab found.", isError: true }; - if (!activePage || activePage.isClosed()) { - await chrome.tabs.update(tabId, { url: "about:blank" }); - await waitForTabLoad(tabId, 2e3); - const result = await attachToTab(tabId); - if (!result.ok) { - return { text: `Cannot attach: ${result.error}`, isError: true }; - } - } - await chrome.tabs.update(tabId, { url: url2 }); - await waitForTabLoad(tabId); - return { text: `Navigated to ${url2}`, isError: false }; -} -async function goBackTab() { - const tabId = await getActiveTabId(); - if (!tabId) return { text: "No active tab found.", isError: true }; - await chrome.tabs.goBack(tabId); - await waitForTabLoad(tabId); - return { text: "Went back", isError: false }; -} -async function goForwardTab() { - const tabId = await getActiveTabId(); - if (!tabId) return { text: "No active tab found.", isError: true }; - await chrome.tabs.goForward(tabId); - await waitForTabLoad(tabId); - return { text: "Went forward", isError: false }; -} -async function reloadTab() { - const tabId = await getActiveTabId(); - if (!tabId) return { text: "No active tab found.", isError: true }; - await chrome.tabs.reload(tabId); - await waitForTabLoad(tabId); - return { text: "Reloaded", isError: false }; -} -async function attachToTab(tabId) { - var _a2; - try { - const tab = await chrome.tabs.get(tabId); - if ((_a2 = tab.url) == null ? void 0 : _a2.startsWith("chrome://")) { - return { ok: false, error: "Cannot attach to chrome:// pages. Navigate to a regular webpage first." }; - } - if (!crxApp) crxApp = await crx.start(); - if (activeTabId && activeTabId !== tabId) { - try { - await crxApp.detach(activeTabId); - } catch { - } - } - activePage = await crxApp.attach(tabId); - activeTabId = tabId; - return { ok: true, url: activePage.url() }; - } catch (e) { - activePage = null; - return { ok: false, error: String(e) }; - } -} -async function ensurePage() { - if (activePage && !activePage.isClosed()) return activePage; - const tabId = await getActiveTabId(); - if (tabId) { - const result = await attachToTab(tabId); - if (result.ok) return activePage; - } - return null; -} -async function handleCommand(command2) { - const [keyword, ...args] = command2.trim().split(/\s+/); - if (keyword === "goto") { - let url2 = args.join(" "); - if (!url2) return { text: "Usage: goto ", isError: true }; - if (!url2.startsWith("http")) url2 = `https://${url2}`; - return navigateTab(url2); - } - if (keyword === "back") return goBackTab(); - if (keyword === "forward") return goForwardTab(); - if (keyword === "reload") return reloadTab(); - const page = await ensurePage(); - if (!page) { - return { text: "Not attached to any tab. Click the connection indicator to reconnect.", isError: true }; - } - return await execute(command2, page); -} -//# sourceMappingURL=background.js.map diff --git a/packages/repl-ext/dist/background.js.map b/packages/repl-ext/dist/background.js.map deleted file mode 100644 index 552e239..0000000 --- a/packages/repl-ext/dist/background.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"background.js","sources":["../../../node_modules/playwright-crx/node_modules/process/browser.js","../../../node_modules/playwright-crx/src/shims/process.ts","../../../node_modules/playwright-crx/node_modules/setimmediate/setImmediate.js","../../../node_modules/playwright-crx/src/shims/setImmediate.ts","../../../node_modules/playwright-crx/node_modules/base64-js/index.js","../../../node_modules/playwright-crx/node_modules/ieee754/index.js","../../../node_modules/playwright-crx/node_modules/buffer/index.js","../../../node_modules/playwright-crx/src/shims/buffer.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/constants.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/Stats.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/internal/buffer.ts","../../../node_modules/playwright-crx/node_modules/has-symbols/shams.js","../../../node_modules/playwright-crx/node_modules/has-tostringtag/shams.js","../../../node_modules/playwright-crx/node_modules/es-object-atoms/index.js","../../../node_modules/playwright-crx/node_modules/es-errors/index.js","../../../node_modules/playwright-crx/node_modules/es-errors/eval.js","../../../node_modules/playwright-crx/node_modules/es-errors/range.js","../../../node_modules/playwright-crx/node_modules/es-errors/ref.js","../../../node_modules/playwright-crx/node_modules/es-errors/syntax.js","../../../node_modules/playwright-crx/node_modules/es-errors/type.js","../../../node_modules/playwright-crx/node_modules/es-errors/uri.js","../../../node_modules/playwright-crx/node_modules/math-intrinsics/abs.js","../../../node_modules/playwright-crx/node_modules/math-intrinsics/floor.js","../../../node_modules/playwright-crx/node_modules/math-intrinsics/max.js","../../../node_modules/playwright-crx/node_modules/math-intrinsics/min.js","../../../node_modules/playwright-crx/node_modules/math-intrinsics/pow.js","../../../node_modules/playwright-crx/node_modules/math-intrinsics/round.js","../../../node_modules/playwright-crx/node_modules/math-intrinsics/isNaN.js","../../../node_modules/playwright-crx/node_modules/math-intrinsics/sign.js","../../../node_modules/playwright-crx/node_modules/gopd/gOPD.js","../../../node_modules/playwright-crx/node_modules/gopd/index.js","../../../node_modules/playwright-crx/node_modules/es-define-property/index.js","../../../node_modules/playwright-crx/node_modules/has-symbols/index.js","../../../node_modules/playwright-crx/node_modules/get-proto/Reflect.getPrototypeOf.js","../../../node_modules/playwright-crx/node_modules/get-proto/Object.getPrototypeOf.js","../../../node_modules/playwright-crx/node_modules/function-bind/implementation.js","../../../node_modules/playwright-crx/node_modules/function-bind/index.js","../../../node_modules/playwright-crx/node_modules/call-bind-apply-helpers/functionCall.js","../../../node_modules/playwright-crx/node_modules/call-bind-apply-helpers/functionApply.js","../../../node_modules/playwright-crx/node_modules/call-bind-apply-helpers/reflectApply.js","../../../node_modules/playwright-crx/node_modules/call-bind-apply-helpers/actualApply.js","../../../node_modules/playwright-crx/node_modules/call-bind-apply-helpers/index.js","../../../node_modules/playwright-crx/node_modules/dunder-proto/get.js","../../../node_modules/playwright-crx/node_modules/get-proto/index.js","../../../node_modules/playwright-crx/node_modules/hasown/index.js","../../../node_modules/playwright-crx/node_modules/get-intrinsic/index.js","../../../node_modules/playwright-crx/node_modules/define-data-property/index.js","../../../node_modules/playwright-crx/node_modules/has-property-descriptors/index.js","../../../node_modules/playwright-crx/node_modules/set-function-length/index.js","../../../node_modules/playwright-crx/node_modules/call-bind-apply-helpers/applyBind.js","../../../node_modules/playwright-crx/node_modules/call-bind/index.js","../../../node_modules/playwright-crx/node_modules/call-bind/callBound.js","../../../node_modules/playwright-crx/node_modules/is-arguments/index.js","../../../node_modules/playwright-crx/node_modules/is-generator-function/index.js","../../../node_modules/playwright-crx/node_modules/is-callable/index.js","../../../node_modules/playwright-crx/node_modules/for-each/index.js","../../../node_modules/playwright-crx/node_modules/possible-typed-array-names/index.js","../../../node_modules/playwright-crx/node_modules/available-typed-arrays/index.js","../../../node_modules/playwright-crx/node_modules/call-bound/index.js","../../../node_modules/playwright-crx/node_modules/which-typed-array/index.js","../../../node_modules/playwright-crx/node_modules/is-typed-array/index.js","../../../node_modules/playwright-crx/node_modules/util/support/types.js","../../../node_modules/playwright-crx/node_modules/util/support/isBufferBrowser.js","../../../node_modules/playwright-crx/node_modules/inherits/inherits_browser.js","../../../node_modules/playwright-crx/node_modules/util/util.js","../../../node_modules/playwright-crx/node_modules/assert/build/internal/errors.js","../../../node_modules/playwright-crx/node_modules/assert/build/internal/assert/assertion_error.js","../../../node_modules/playwright-crx/node_modules/object-keys/isArguments.js","../../../node_modules/playwright-crx/node_modules/object-keys/implementation.js","../../../node_modules/playwright-crx/node_modules/object-keys/index.js","../../../node_modules/playwright-crx/node_modules/object.assign/implementation.js","../../../node_modules/playwright-crx/node_modules/object.assign/polyfill.js","../../../node_modules/playwright-crx/node_modules/object-is/implementation.js","../../../node_modules/playwright-crx/node_modules/object-is/polyfill.js","../../../node_modules/playwright-crx/node_modules/define-properties/index.js","../../../node_modules/playwright-crx/node_modules/object-is/shim.js","../../../node_modules/playwright-crx/node_modules/object-is/index.js","../../../node_modules/playwright-crx/node_modules/is-nan/implementation.js","../../../node_modules/playwright-crx/node_modules/is-nan/polyfill.js","../../../node_modules/playwright-crx/node_modules/is-nan/shim.js","../../../node_modules/playwright-crx/node_modules/is-nan/index.js","../../../node_modules/playwright-crx/node_modules/assert/build/internal/util/comparisons.js","../../../node_modules/playwright-crx/node_modules/assert/build/assert.js","../../../node_modules/playwright-crx/node_modules/memfs/src/internal/errors.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/encoding.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/Dirent.ts","../../../node_modules/playwright-crx/node_modules/path/node_modules/util/support/isBufferBrowser.js","../../../node_modules/playwright-crx/node_modules/path/node_modules/inherits/inherits_browser.js","../../../node_modules/playwright-crx/node_modules/path/node_modules/util/util.js","../../../node_modules/playwright-crx/node_modules/path/path.js","../../../node_modules/playwright-crx/node_modules/memfs/src/process.ts","../../../node_modules/playwright-crx/node_modules/events/events.js","../../../node_modules/playwright-crx/node_modules/memfs/src/node.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/setImmediate.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/queueMicrotask.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/setTimeoutUnref.ts","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/ours/primordials.js","../../../node_modules/playwright-crx/node_modules/abort-controller/browser.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/ours/util.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/ours/errors.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/validators.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/utils.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/end-of-stream.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/destroy.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/legacy.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/add-abort-signal.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/buffer_list.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/state.js","../../../node_modules/playwright-crx/node_modules/safe-buffer/index.js","../../../node_modules/playwright-crx/node_modules/string_decoder/lib/string_decoder.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/from.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/readable.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/writable.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/duplexify.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/duplex.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/transform.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/passthrough.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/pipeline.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/compose.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/internal/streams/operators.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/stream/promises.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/stream.js","../../../node_modules/playwright-crx/node_modules/readable-stream/lib/ours/browser.js","../../../node_modules/playwright-crx/node_modules/memfs/src/node/constants.ts","../../../node_modules/playwright-crx/node_modules/punycode/punycode.js","../../../node_modules/playwright-crx/__vite-browser-external","../../../node_modules/playwright-crx/node_modules/object-inspect/index.js","../../../node_modules/playwright-crx/node_modules/side-channel-list/index.js","../../../node_modules/playwright-crx/node_modules/side-channel-map/index.js","../../../node_modules/playwright-crx/node_modules/side-channel-weakmap/index.js","../../../node_modules/playwright-crx/node_modules/side-channel/index.js","../../../node_modules/playwright-crx/node_modules/qs/lib/formats.js","../../../node_modules/playwright-crx/node_modules/qs/lib/utils.js","../../../node_modules/playwright-crx/node_modules/qs/lib/stringify.js","../../../node_modules/playwright-crx/node_modules/qs/lib/parse.js","../../../node_modules/playwright-crx/node_modules/qs/lib/index.js","../../../node_modules/playwright-crx/node_modules/url/url.js","../../../node_modules/playwright-crx/src/shims/url.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/node/util.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/node/FileHandle.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/node/FsPromises.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/json-joy/util/print/printTree.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/node-to-fsa/util.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/print/index.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/node/options.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/volume.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/node/lists/fsSynchronousApiList.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/node/lists/fsCallbackApiList.ts","../../../node_modules/playwright-crx/node_modules/memfs/src/index.ts","../../../node_modules/playwright-crx/src/shims/fs.ts","../../../node_modules/playwright-crx/src/shims/global.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/protocol/validatorPrimitives.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/protocol/validator.ts","../../../node_modules/playwright-crx/src/protocol/validator.ts","../../../node_modules/playwright-crx/node_modules/os-browserify/browser.js","../../../node_modules/playwright-crx/src/shims/child_process.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/retry/lib/retry_operation.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/retry/lib/retry.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/retry/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/signal-exit/signals.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/signal-exit/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/src/third_party/lockfile.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/lib/styles.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/lib/system/has-flag.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/lib/system/supports-colors.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/lib/custom/trap.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/lib/custom/zalgo.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/lib/maps/america.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/lib/maps/zebra.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/lib/maps/rainbow.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/lib/maps/random.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/lib/colors.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/colors/safe.js","../../../node_modules/playwright-crx/node_modules/ms/index.js","../../../node_modules/playwright-crx/node_modules/debug/src/common.js","../../../node_modules/playwright-crx/node_modules/debug/src/browser.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/diff/lib/index.mjs","../../../node_modules/playwright-crx/node_modules/randombytes/browser.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/internal/streams/stream-browser.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/internal/streams/buffer_list.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/internal/streams/destroy.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/errors-browser.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/internal/streams/state.js","../../../node_modules/playwright-crx/node_modules/util-deprecate/browser.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/_stream_writable.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/_stream_duplex.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/internal/streams/end-of-stream.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/internal/streams/async_iterator.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/internal/streams/from-browser.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/_stream_readable.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/_stream_transform.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/_stream_passthrough.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/lib/internal/streams/pipeline.js","../../../node_modules/playwright-crx/node_modules/hash-base/node_modules/readable-stream/readable-browser.js","../../../node_modules/playwright-crx/node_modules/hash-base/index.js","../../../node_modules/playwright-crx/node_modules/md5.js/index.js","../../../node_modules/playwright-crx/node_modules/ripemd160/index.js","../../../node_modules/playwright-crx/node_modules/sha.js/hash.js","../../../node_modules/playwright-crx/node_modules/sha.js/sha.js","../../../node_modules/playwright-crx/node_modules/sha.js/sha1.js","../../../node_modules/playwright-crx/node_modules/sha.js/sha256.js","../../../node_modules/playwright-crx/node_modules/sha.js/sha224.js","../../../node_modules/playwright-crx/node_modules/sha.js/sha512.js","../../../node_modules/playwright-crx/node_modules/sha.js/sha384.js","../../../node_modules/playwright-crx/node_modules/sha.js/index.js","../../../node_modules/playwright-crx/node_modules/cipher-base/index.js","../../../node_modules/playwright-crx/node_modules/create-hash/browser.js","../../../node_modules/playwright-crx/node_modules/create-hmac/legacy.js","../../../node_modules/playwright-crx/node_modules/create-hash/md5.js","../../../node_modules/playwright-crx/node_modules/create-hmac/browser.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/algos.js","../../../node_modules/playwright-crx/node_modules/pbkdf2/lib/precondition.js","../../../node_modules/playwright-crx/node_modules/pbkdf2/lib/default-encoding.js","../../../node_modules/playwright-crx/node_modules/pbkdf2/lib/to-buffer.js","../../../node_modules/playwright-crx/node_modules/pbkdf2/lib/sync-browser.js","../../../node_modules/playwright-crx/node_modules/pbkdf2/lib/async.js","../../../node_modules/playwright-crx/node_modules/pbkdf2/browser.js","../../../node_modules/playwright-crx/node_modules/des.js/lib/des/utils.js","../../../node_modules/playwright-crx/node_modules/minimalistic-assert/index.js","../../../node_modules/playwright-crx/node_modules/des.js/lib/des/cipher.js","../../../node_modules/playwright-crx/node_modules/des.js/lib/des/des.js","../../../node_modules/playwright-crx/node_modules/des.js/lib/des/cbc.js","../../../node_modules/playwright-crx/node_modules/des.js/lib/des/ede.js","../../../node_modules/playwright-crx/node_modules/des.js/lib/des.js","../../../node_modules/playwright-crx/node_modules/browserify-des/index.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/modes/ecb.js","../../../node_modules/playwright-crx/node_modules/buffer-xor/index.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/modes/cbc.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/modes/cfb.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/modes/cfb8.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/modes/cfb1.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/modes/ofb.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/incr32.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/modes/ctr.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/modes/index.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/aes.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/ghash.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/authCipher.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/streamCipher.js","../../../node_modules/playwright-crx/node_modules/evp_bytestokey/index.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/encrypter.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/decrypter.js","../../../node_modules/playwright-crx/node_modules/browserify-aes/browser.js","../../../node_modules/playwright-crx/node_modules/browserify-des/modes.js","../../../node_modules/playwright-crx/node_modules/browserify-cipher/browser.js","../../../node_modules/playwright-crx/node_modules/diffie-hellman/node_modules/bn.js/lib/bn.js","../../../node_modules/playwright-crx/node_modules/miller-rabin/node_modules/bn.js/lib/bn.js","../../../node_modules/playwright-crx/node_modules/brorand/index.js","../../../node_modules/playwright-crx/node_modules/miller-rabin/lib/mr.js","../../../node_modules/playwright-crx/node_modules/diffie-hellman/lib/generatePrime.js","../../../node_modules/playwright-crx/node_modules/diffie-hellman/lib/dh.js","../../../node_modules/playwright-crx/node_modules/diffie-hellman/browser.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/stream-browser.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/buffer_list.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/destroy.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/errors-browser.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/state.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_writable.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_duplex.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/end-of-stream.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/async_iterator.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/from-browser.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_readable.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_transform.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_passthrough.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/pipeline.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/node_modules/readable-stream/readable-browser.js","../../../node_modules/playwright-crx/node_modules/bn.js/lib/bn.js","../../../node_modules/playwright-crx/node_modules/browserify-rsa/index.js","../../../node_modules/playwright-crx/node_modules/elliptic/node_modules/bn.js/lib/bn.js","../../../node_modules/playwright-crx/node_modules/minimalistic-crypto-utils/lib/utils.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/utils.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/curve/base.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/curve/short.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/curve/mont.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/curve/edwards.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/curve/index.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/utils.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/common.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/sha/common.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/sha/1.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/sha/256.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/sha/224.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/sha/512.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/sha/384.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/sha.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/ripemd.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash/hmac.js","../../../node_modules/playwright-crx/node_modules/hash.js/lib/hash.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/curves.js","../../../node_modules/playwright-crx/node_modules/hmac-drbg/lib/hmac-drbg.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/ec/key.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/ec/signature.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/ec/index.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/eddsa/key.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/eddsa/signature.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic/eddsa/index.js","../../../node_modules/playwright-crx/node_modules/elliptic/lib/elliptic.js","../../../node_modules/playwright-crx/node_modules/asn1.js/node_modules/bn.js/lib/bn.js","../../../node_modules/playwright-crx/node_modules/safer-buffer/safer.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/base/reporter.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/base/buffer.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/base/node.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/constants/der.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/encoders/der.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/encoders/pem.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/encoders/index.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/decoders/der.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/decoders/pem.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/decoders/index.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/api.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/base/index.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1/constants/index.js","../../../node_modules/playwright-crx/node_modules/asn1.js/lib/asn1.js","../../../node_modules/playwright-crx/node_modules/parse-asn1/certificate.js","../../../node_modules/playwright-crx/node_modules/parse-asn1/asn1.js","../../../node_modules/playwright-crx/node_modules/parse-asn1/fixProc.js","../../../node_modules/playwright-crx/node_modules/parse-asn1/index.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/browser/sign.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/browser/verify.js","../../../node_modules/playwright-crx/node_modules/browserify-sign/browser/index.js","../../../node_modules/playwright-crx/node_modules/create-ecdh/node_modules/bn.js/lib/bn.js","../../../node_modules/playwright-crx/node_modules/create-ecdh/browser.js","../../../node_modules/playwright-crx/node_modules/public-encrypt/mgf.js","../../../node_modules/playwright-crx/node_modules/public-encrypt/xor.js","../../../node_modules/playwright-crx/node_modules/public-encrypt/node_modules/bn.js/lib/bn.js","../../../node_modules/playwright-crx/node_modules/public-encrypt/withPublic.js","../../../node_modules/playwright-crx/node_modules/public-encrypt/publicEncrypt.js","../../../node_modules/playwright-crx/node_modules/public-encrypt/privateDecrypt.js","../../../node_modules/playwright-crx/node_modules/public-encrypt/browser.js","../../../node_modules/playwright-crx/node_modules/randomfill/browser.js","../../../node_modules/playwright-crx/node_modules/crypto-browserify/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/dotenv/lib/main.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/proxy-from-env/index.js","../../../node_modules/playwright-crx/src/shims/net.ts","../../../node_modules/playwright-crx/src/shims/tls.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/agent-base/src/promisify.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/agent-base/src/index.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/https-proxy-agent/src/parse-proxy-response.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/https-proxy-agent/src/agent.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/https-proxy-agent/src/index.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/jpeg-js/lib/encoder.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/jpeg-js/lib/decoder.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/jpeg-js/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/mime/Mime.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/mime/types/standard.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/mime/types/other.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/mime/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/concat-map/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/balanced-match/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/brace-expansion/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/minimatch/minimatch.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/is-docker/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/is-wsl/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/define-lazy-prop/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/open/index.js","../../../node_modules/playwright-crx/node_modules/pako/lib/zlib/zstream.js","../../../node_modules/playwright-crx/node_modules/pako/lib/utils/common.js","../../../node_modules/playwright-crx/node_modules/pako/lib/zlib/trees.js","../../../node_modules/playwright-crx/node_modules/pako/lib/zlib/adler32.js","../../../node_modules/playwright-crx/node_modules/pako/lib/zlib/crc32.js","../../../node_modules/playwright-crx/node_modules/pako/lib/zlib/messages.js","../../../node_modules/playwright-crx/node_modules/pako/lib/zlib/deflate.js","../../../node_modules/playwright-crx/node_modules/pako/lib/zlib/inffast.js","../../../node_modules/playwright-crx/node_modules/pako/lib/zlib/inftrees.js","../../../node_modules/playwright-crx/node_modules/pako/lib/zlib/inflate.js","../../../node_modules/playwright-crx/node_modules/pako/lib/zlib/constants.js","../../../node_modules/playwright-crx/node_modules/browserify-zlib/lib/binding.js","../../../node_modules/playwright-crx/node_modules/browserify-zlib/lib/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/chunkstream.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/interlace.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/paeth-predictor.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/filter-parse.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/filter-parse-async.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/constants.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/crc.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/parser.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/bitmapper.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/format-normaliser.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/parser-async.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/bitpacker.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/filter-pack.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/packer.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/packer-async.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/sync-inflate.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/sync-reader.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/filter-parse-sync.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/parser-sync.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/packer-sync.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/png-sync.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/pngjs/lib/png.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/commander/lib/error.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/commander/lib/argument.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/commander/lib/help.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/commander/lib/option.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/commander/lib/suggestSimilar.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/commander/lib/command.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/commander/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/progress/lib/node-progress.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/progress/index.js","../../../node_modules/playwright-crx/src/shims/dns.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/smart-buffer/src/utils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/smart-buffer/src/smartbuffer.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/socks/src/common/constants.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/socks/src/common/util.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/ip-address/src/common.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/ip-address/src/v4/constants.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/ip-address/src/address-error.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/jsbn/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/sprintf-js/src/sprintf.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/ip-address/src/ipv4.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/ip-address/src/v6/constants.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/ip-address/src/v6/helpers.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/ip-address/src/v6/regular-expressions.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/ip-address/src/ipv6.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/ip-address/src/ip-address.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/socks/src/common/helpers.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/socks/src/common/receivebuffer.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/socks/src/client/socksclient.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/socks/src/index.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/socks-proxy-agent/src/agent.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/socks-proxy-agent/src/index.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/nodes/identity.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/visit.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/doc/directives.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/doc/anchors.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/doc/applyReviver.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/nodes/toJS.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/nodes/Node.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/nodes/Alias.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/nodes/Scalar.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/doc/createNode.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/nodes/Collection.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/stringify/stringifyComment.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/stringify/foldFlowLines.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/stringify/stringifyString.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/stringify/stringify.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/stringify/stringifyPair.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/log.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/nodes/addPairToJSMap.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/nodes/Pair.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/stringify/stringifyCollection.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/nodes/YAMLMap.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/common/map.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/nodes/YAMLSeq.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/common/seq.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/common/string.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/common/null.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/core/bool.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/stringify/stringifyNumber.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/core/float.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/core/int.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/core/schema.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/json/schema.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/yaml-1.1/float.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/yaml-1.1/int.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/yaml-1.1/set.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/tags.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/schema/Schema.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/stringify/stringifyDocument.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/doc/Document.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/errors.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/resolve-props.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/util-contains-newline.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/util-flow-indent-check.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/util-map-includes.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/resolve-block-map.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/resolve-block-seq.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/resolve-end.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/resolve-flow-collection.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/compose-collection.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/resolve-block-scalar.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/compose-scalar.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/compose-node.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/compose-doc.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/compose/composer.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/parse/cst-scalar.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/parse/cst-stringify.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/parse/cst-visit.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/parse/cst.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/parse/lexer.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/parse/line-counter.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/parse/parser.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/yaml/browser/dist/public-api.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/node_modules/ws/browser.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/utils/src/utilsBundleImpl.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utilsBundle.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/debugLogger.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/stackTrace.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/manualPromise.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/linuxUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/userAgent.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/wrappy/wrappy.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/once/once.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/end-of-stream/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/pump/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/get-stream/buffer-stream.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/get-stream/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/pend/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/yauzl/fd-slicer.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/buffer-crc32/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/yauzl/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/src/third_party/extract-zip.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/node_modules/yazl/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/bundles/zip/src/zipBundleImpl.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/zipBundle.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/fileUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/registry/browserFetcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/registry/nativeDeps.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/ascii.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/hostPlatform.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/spawnAsync.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/registry/dependencies.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/assert.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/headers.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/cssTokenizer.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/cssParser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/selectorParser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/stringUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/locatorGenerators.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/mimeType.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/multimap.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/protocolMetainfo.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/protocolFormatter.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/rtti.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/time.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/timeoutRunner.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/urlMatch.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/image_tools/colorUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/image_tools/imageChannel.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/image_tools/stats.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/image_tools/compare.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/third_party/pixelmatch.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/comparators.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/crypto.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/env.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/debug.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/eventsHelper.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/expectUtils.ts","../../../node_modules/playwright-crx/node_modules/stream-http/lib/capability.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/stream-browser.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/buffer_list.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/destroy.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/errors-browser.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/state.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/_stream_writable.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/_stream_duplex.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/end-of-stream.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/async_iterator.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/from-browser.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/_stream_readable.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/_stream_transform.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/_stream_passthrough.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/pipeline.js","../../../node_modules/playwright-crx/node_modules/stream-http/node_modules/readable-stream/readable-browser.js","../../../node_modules/playwright-crx/node_modules/stream-http/lib/response.js","../../../node_modules/playwright-crx/node_modules/stream-http/lib/request.js","../../../node_modules/playwright-crx/node_modules/xtend/immutable.js","../../../node_modules/playwright-crx/node_modules/builtin-status-codes/browser.js","../../../node_modules/playwright-crx/node_modules/stream-http/index.js","../../../node_modules/playwright-crx/node_modules/https-browserify/index.js","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/happyEyeballs.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/network.ts","../../../node_modules/playwright-crx/node_modules/inspector/node_modules/ws/lib/browser.js","../../../node_modules/playwright-crx/node_modules/endpoint/endpoint.js","../../../node_modules/playwright-crx/node_modules/inspector/inspector.js","../../../node_modules/playwright-crx/src/shims/async_hooks.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/zones.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/nodePlatform.ts","../../../node_modules/playwright-crx/src/shims/readline.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/processLauncher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/profiler.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/socksProxy.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/task.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/zipFile.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/registry/index.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/protocol/serializers.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/errors.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/instrumentation.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/protocolError.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/callLog.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/dispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/generated/clockSource.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/clock.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/debugger.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dialog.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/artifact.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/generated/utilityScriptSource.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/utilityScriptSerializers.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/javascript.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/progress.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/fileUploadUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/generated/injectedScriptSource.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dom.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/frameSelectors.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/helper.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/network.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/accessibility.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/console.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/fileChooser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/usKeyboardLayout.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/input.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/screenshotter.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/generated/bindingsControllerSource.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/page.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/types.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/frames.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/har/harTracer.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/har/harRecorder.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/codegen/language.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/recorder/recorderUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/recorder/recorderRunner.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/recorder/recorderCollection.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/generated/pollingRecorderSource.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/deviceDescriptors.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/codegen/csharp.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/codegen/javascript.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/codegen/java.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/codegen/jsonl.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/codegen/python.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/codegen/languages.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/recorder/throttledFile.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/recorder/contextRecorder.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/locatorParser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/recorder.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/launchApp.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/recorder/recorderApp.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/selectors.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/trace/recorder/snapshotterInjected.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/trace/recorder/snapshotter.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/trace/recorder/tracing.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/generated/storageScriptSource.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/browserContext.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/cookieStore.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/formData.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/socksClientCertificatesInterceptor.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/fetch.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/streamDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/artifactDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crConnection.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/cdpSessionDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/jsHandleDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/tracingDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/networkDispatchers.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/ariaSnapshot.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/frameDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/elementHandlerDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/generated/webSocketMockSource.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/webSocketRouteDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/pageDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/dialogDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/download.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/browser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crAccessibility.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crCoverage.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crProtocolHelper.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crDragDrop.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crExecutionContext.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/macEditingCommands.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crInput.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crNetworkManager.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crPdf.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/defaultFontFamilies.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/videoRecorder.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crPage.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crServiceWorker.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crBrowser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/writableStreamDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/utils/pipeTransport.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/chromiumSwitches.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/android/android.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/androidDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/browserDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/browserTypeDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/transport.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/electron/electron.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/electronDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/harBackend.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/traceUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/localUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/jsonPipeDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/socksInterceptor.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/dispatchers/localUtilsDispatcher.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/android/backendAdb.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/pipeTransport.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/browserType.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/bidiConnection.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/third_party/bidiProtocolCore.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/third_party/bidiProtocolPermissions.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/bidiNetworkManager.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/third_party/bidiDeserializer.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/third_party/bidiSerializer.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/bidiExecutionContext.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/third_party/bidiKeyboard.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/bidiInput.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/bidiPdf.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/bidiPage.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/bidiBrowser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/bidiChromium.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/third_party/firefoxPrefs.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/bidi/bidiFirefox.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/crDevTools.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/chromium/chromium.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/debugController.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/firefox/ffConnection.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/firefox/ffAccessibility.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/firefox/ffExecutionContext.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/firefox/ffInput.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/firefox/ffNetworkManager.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/firefox/ffPage.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/firefox/ffBrowser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/firefox/firefox.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/webkit/wkConnection.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/webkit/wkAccessibility.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/webkit/wkExecutionContext.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/webkit/wkInput.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/webkit/wkInterceptableRequest.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/webkit/wkProvisionalPage.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/webkit/wkWorkers.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/webkit/wkPage.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/webkit/wkBrowser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/webkit/webkit.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/server/playwright.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/eventEmitter.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/clientStackTrace.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/channelOwner.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/stream.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/fileUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/artifact.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/cdpSession.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/clientHelper.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/clock.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/errors.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/jsHandle.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/accessibility.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/coverage.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/download.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/events.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/utils/isomorphic/locatorUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/locator.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/tracing.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/timeoutSettings.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/fetch.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/waiter.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/worker.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/network.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/types.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/frame.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/writableStream.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/elementHandle.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/fileChooser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/harRouter.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/input.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/video.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/page.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/consoleMessage.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/dialog.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/webError.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/browserContext.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/webSocket.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/android.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/browser.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/browserType.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/clientInstrumentation.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/electron.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/jsonPipe.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/localUtils.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/selectors.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/playwright.ts","../../../node_modules/playwright-crx/playwright/packages/playwright-core/src/client/connection.ts","../../../node_modules/playwright-crx/src/client/crx.ts","../../../node_modules/playwright-crx/src/client/crxPlaywright.ts","../../../node_modules/playwright-crx/src/client/crxConnection.ts","../../../node_modules/playwright-crx/src/server/recorder/popupRecorderWindow.ts","../../../node_modules/playwright-crx/src/server/recorder/sidepanelRecorderWindow.ts","../../../node_modules/playwright-crx/node_modules/acorn/dist/acorn.mjs","../../../node_modules/playwright-crx/node_modules/acorn-walk/dist/walk.mjs","../../../node_modules/playwright-crx/src/server/recorder/parser.ts","../../../node_modules/playwright-crx/src/server/recorder/crxRecorderApp.ts","../../../node_modules/playwright-crx/src/server/utils.ts","../../../node_modules/playwright-crx/src/server/transport/crxTransport.ts","../../../node_modules/playwright-crx/src/server/recorder/recorderUtils.ts","../../../node_modules/playwright-crx/src/server/recorder/crxPlayer.ts","../../../node_modules/playwright-crx/src/server/crx.ts","../../../node_modules/playwright-crx/src/server/crxPlaywright.ts","../../../node_modules/playwright-crx/src/server/dispatchers/crxDispatcher.ts","../../../node_modules/playwright-crx/src/server/dispatchers/crxPlaywrightDispatcher.ts","../../../node_modules/playwright-crx/src/client/crxZone.ts","../../../node_modules/playwright-crx/src/index.ts","../src/snapshot.ts","../src/commands.ts","../src/background.ts"],"sourcesContent":["// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","/**\n * Copyright (c) Rui Figueira.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// @ts-ignore\nimport process from 'process/browser';\n\n// https://github.com/cabinjs/browser-hrtime/blob/cb6b7c336e93726a302e04a5ac4755e7e353edaf/src/index.ts#L22\nprocess.hrtime = (previousTimestamp?: [number, number]): [number, number] => {\n const baseNow = Math.floor((Date.now() - performance.now()) * 1e-3);\n const clocktime = performance.now() * 1e-3;\n let seconds = Math.floor(clocktime) + baseNow;\n let nanoseconds = Math.floor((clocktime % 1) * 1e9);\n\n if (previousTimestamp) {\n seconds = seconds - previousTimestamp[0];\n nanoseconds = nanoseconds - previousTimestamp[1];\n if (nanoseconds < 0) {\n seconds--;\n nanoseconds += 1e9;\n }\n }\n return [seconds, nanoseconds];\n};\nprocess.platform = 'linux';\nprocess.versions.node = '18.16';\nprocess.stdout = { isTTY: 'false' };\nprocess.geteuid = () => '';\n\nprocess.env['PLAYWRIGHT_BROWSERS_PATH'] = '.';\n\nself.process = process;\n","(function (global, undefined) {\n \"use strict\";\n\n if (global.setImmediate) {\n return;\n }\n\n var nextHandle = 1; // Spec says greater than zero\n var tasksByHandle = {};\n var currentlyRunningATask = false;\n var doc = global.document;\n var registerImmediate;\n\n function setImmediate(callback) {\n // Callback can either be a function or a string\n if (typeof callback !== \"function\") {\n callback = new Function(\"\" + callback);\n }\n // Copy function arguments\n var args = new Array(arguments.length - 1);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i + 1];\n }\n // Store and register the task\n var task = { callback: callback, args: args };\n tasksByHandle[nextHandle] = task;\n registerImmediate(nextHandle);\n return nextHandle++;\n }\n\n function clearImmediate(handle) {\n delete tasksByHandle[handle];\n }\n\n function run(task) {\n var callback = task.callback;\n var args = task.args;\n switch (args.length) {\n case 0:\n callback();\n break;\n case 1:\n callback(args[0]);\n break;\n case 2:\n callback(args[0], args[1]);\n break;\n case 3:\n callback(args[0], args[1], args[2]);\n break;\n default:\n callback.apply(undefined, args);\n break;\n }\n }\n\n function runIfPresent(handle) {\n // From the spec: \"Wait until any invocations of this algorithm started before this one have completed.\"\n // So if we're currently running a task, we'll need to delay this invocation.\n if (currentlyRunningATask) {\n // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a\n // \"too much recursion\" error.\n setTimeout(runIfPresent, 0, handle);\n } else {\n var task = tasksByHandle[handle];\n if (task) {\n currentlyRunningATask = true;\n try {\n run(task);\n } finally {\n clearImmediate(handle);\n currentlyRunningATask = false;\n }\n }\n }\n }\n\n function installNextTickImplementation() {\n registerImmediate = function(handle) {\n process.nextTick(function () { runIfPresent(handle); });\n };\n }\n\n function canUsePostMessage() {\n // The test against `importScripts` prevents this implementation from being installed inside a web worker,\n // where `global.postMessage` means something completely different and can't be used for this purpose.\n if (global.postMessage && !global.importScripts) {\n var postMessageIsAsynchronous = true;\n var oldOnMessage = global.onmessage;\n global.onmessage = function() {\n postMessageIsAsynchronous = false;\n };\n global.postMessage(\"\", \"*\");\n global.onmessage = oldOnMessage;\n return postMessageIsAsynchronous;\n }\n }\n\n function installPostMessageImplementation() {\n // Installs an event handler on `global` for the `message` event: see\n // * https://developer.mozilla.org/en/DOM/window.postMessage\n // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages\n\n var messagePrefix = \"setImmediate$\" + Math.random() + \"$\";\n var onGlobalMessage = function(event) {\n if (event.source === global &&\n typeof event.data === \"string\" &&\n event.data.indexOf(messagePrefix) === 0) {\n runIfPresent(+event.data.slice(messagePrefix.length));\n }\n };\n\n if (global.addEventListener) {\n global.addEventListener(\"message\", onGlobalMessage, false);\n } else {\n global.attachEvent(\"onmessage\", onGlobalMessage);\n }\n\n registerImmediate = function(handle) {\n global.postMessage(messagePrefix + handle, \"*\");\n };\n }\n\n function installMessageChannelImplementation() {\n var channel = new MessageChannel();\n channel.port1.onmessage = function(event) {\n var handle = event.data;\n runIfPresent(handle);\n };\n\n registerImmediate = function(handle) {\n channel.port2.postMessage(handle);\n };\n }\n\n function installReadyStateChangeImplementation() {\n var html = doc.documentElement;\n registerImmediate = function(handle) {\n // Create a - -``` - -### 4. Convert `src/lib/converter.ts` (simplest, no Chrome APIs) - -- Add param/return types: `tokenize(raw: string): string[]`, `pwToPlaywright(cmd: string): string | null` -- No other changes needed (pure functions, already ESM exports) - -### 5. Convert `src/content/recorder.ts` (IIFE, no imports/exports) - -- Must remain a script (no import/export) — the IIFE is preserved in Rollup output -- Add type annotations to function params (`el: Element`, `e: MouseEvent`, etc.) -- Type narrow DOM elements: `el as HTMLInputElement`, `el as HTMLSelectElement`, etc. -- Type state variables: `fillTimer: ReturnType | null`, etc. -- `window.__pwRecorderCleanup` uses the `Window` extension from `types.d.ts` -- `chrome` global comes from `@types/chrome` - -### 6. Convert `src/background.ts` - -- Replace CJS export guard with ESM named exports: `export async function startRecording(...)`, etc. -- Type state variables: `recordingTabId: number | null`, listener types, etc. -- Type function params and return types -- `navCommittedListener` callback typed per `chrome.webNavigation.onCommitted` listener signature - -### 7. Convert `src/panel/panel.ts` - -- All `document.getElementById()` calls need non-null assertions and specific casts: - ```ts - const output = document.getElementById("output") as HTMLDivElement; - const input = document.getElementById("command-input") as HTMLInputElement; - const editor = document.getElementById("editor") as HTMLTextAreaElement; - ``` -- Define `RunResult` interface: `{ text: string; isError: boolean; image?: string }` -- Type `filterResponse`, `responseHistory`, and all function params -- Update import: `import { pwToPlaywright } from "../lib/converter.js"` (keep `.js` — Vite resolves `.js` → `.ts`) - -### 8. Update `public/manifest.json` - -- Add `"type": "module"` to background config (background.ts compiles to ESM): - ```json - "background": { - "service_worker": "background.js", - "type": "module" - } - ``` -- File path references stay the same (background.js, panel/panel.html, content/recorder.js) since Vite outputs match this structure - -### 9. Convert unit tests (.js → .ts) - -- Move from `test/*.js` → `test/*.ts` -- Update import paths to reference `src/`: - - `from "../lib/converter.js"` → `from "../src/lib/converter.js"` - - `await import("../background.js")` → `await import("../src/background.js")` - - `await import("../content/recorder.js")` → `await import("../src/content/recorder.js")` - - `await import("../panel/panel.js")` → `await import("../src/panel/panel.js")` -- Add type annotations, `as any` casts on chrome mock setup -- Type `sendMessageSpy`, DOM element casts, mock fetch objects - -### 10. Update config files - -**`vitest.config.ts`** (rename from .js): -- Update `setupFiles: "./test/setup.ts"` -- Update coverage includes: `["src/**/*.ts"]` -- Add `dist/**` to excludes - -**`playwright.config.ts`** (rename from .js): -- Minimal changes, just rename - -### 11. Convert e2e tests (.mjs → .ts) - -**`e2e/panel/fixtures.ts`** and **`e2e/recording/fixtures.ts`**: -- `EXTENSION_PATH` → `path.resolve(__dirname, '../../dist')` -- Type the custom fixture interfaces -- Import from `./fixtures.js` in test files - -**`e2e/commands/fixtures.ts`**: -- Core imports use `declare module` stubs from `types.d.ts` -- Type the `run` fixture - -**All e2e test files** (`.mjs` → `.ts`): -- Update imports: `from './fixtures.js'` -- Type helper functions (`findRef`, `countTabs`, `startRecordingOn`, etc.) - -### 12. Update .gitignore - -- Add `dist/` under the extension package - -### 13. Delete old files - -- Remove original `background.js`, `panel/`, `content/`, `lib/`, `icons/`, `manifest.json` from package root (now in `src/` and `public/`) - -## Files Summary - -| Action | File | -|--------|------| -| Create | `vite.config.ts` | -| Create | `tsconfig.json` | -| Create | `types.d.ts` | -| Create | `public/manifest.json` (moved from root) | -| Create | `public/icons/` (moved from root) | -| Move+Edit | `background.js` → `src/background.ts` | -| Move+Edit | `panel/panel.js` → `src/panel/panel.ts` | -| Move+Edit | `panel/panel.html` → `src/panel/panel.html` | -| Move | `panel/panel.css` → `src/panel/panel.css` | -| Move+Edit | `content/recorder.js` → `src/content/recorder.ts` | -| Move+Edit | `lib/converter.js` → `src/lib/converter.ts` | -| Rename+Edit | `test/setup.js` → `test/setup.ts` | -| Rename+Edit | `test/converter.test.js` → `test/converter.test.ts` | -| Rename+Edit | `test/background.test.js` → `test/background.test.ts` | -| Rename+Edit | `test/recorder.test.js` → `test/recorder.test.ts` | -| Rename+Edit | `test/panel.test.js` → `test/panel.test.ts` | -| Rename+Edit | `vitest.config.js` → `vitest.config.ts` | -| Rename+Edit | `playwright.config.js` → `playwright.config.ts` | -| Rename+Edit | `e2e/panel/fixtures.mjs` → `e2e/panel/fixtures.ts` | -| Rename+Edit | `e2e/panel/panel.test.mjs` → `e2e/panel/panel.test.ts` | -| Rename+Edit | `e2e/recording/fixtures.mjs` → `e2e/recording/fixtures.ts` | -| Rename+Edit | `e2e/recording/recording.test.mjs` → `e2e/recording/recording.test.ts` | -| Rename+Edit | `e2e/commands/fixtures.mjs` → `e2e/commands/fixtures.ts` | -| Rename+Edit | `e2e/commands/commands.test.mjs` → `e2e/commands/commands.test.ts` | -| Edit | `package.json` | -| Delete | Old root-level `background.js`, `panel/`, `content/`, `lib/`, `icons/`, `manifest.json` | - -## Verification - -1. `npm install` — installs vite, typescript, @types/chrome -2. `npx tsc` — type checking passes with no errors -3. `npm run build` — Vite builds to dist/ with correct structure -4. Verify `dist/` contains: `manifest.json`, `icons/`, `background.js`, `panel/panel.html`, `panel/panel.js`, `panel/panel.css`, `content/recorder.js` -5. `npm test` — all vitest unit tests pass -6. Manually load `dist/` as unpacked Chrome extension to verify it works -7. `npm run test:e2e` — e2e tests pass (if server infrastructure available) diff --git a/packages/extension/package.json b/packages/extension/package.json index 3cd0ddb..33cba3e 100644 --- a/packages/extension/package.json +++ b/packages/extension/package.json @@ -1,6 +1,6 @@ { "name": "@playwright-repl/extension", - "version": "1.0.0", + "version": "1.1.0", "private": true, "description": "Chrome DevTools panel extension for Playwright REPL", "type": "module", diff --git a/sidepanel-mockup.png b/sidepanel-mockup.png deleted file mode 100644 index 7b79b0d57f243f42459c72a052189de6bd21d523..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 35674 zcmbrmWmsF$wk}K!iWOSCSX&CTXmN)YEyaox+=5GSC$vB*?oix{y99@{P~0^@fE0Ik zN%94H_WADFXYc2pd+)E6tjsyrlp*hU$5;ves3?Pv^AraI0|Q_7y`%~T#{CKmjJwSb z@1pN~QXZMcz#znsm3*h>p1M7U?X7mwf%lOBaS z^BU|ojp>&+t7`WUq2*2$I1*X&9!mPXIfRJ$1d43E98*0Nwo8nnPekg910$v!}e2 z?17)}@)GN{^g~dF>jlY8^ZPXS#gi~7wVO9}?)!ay2Kv2BdqGFKyhXAO+a0^Q6hXK7 zL+S=viG$=%^2B0(ewXPxyc|g><&ORVkK65DRtY|DEe?ji1hT$|R`6zKcrWYj8absD z*c+!84~N!G-H`BDZ9;XwhiNrB)ZS(cT5p0GY2?s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