diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..6a2dbed --- /dev/null +++ b/.dockerignore @@ -0,0 +1,13 @@ +node_modules +npm-debug.log +Dockerfile +docker-compose.yml +.dockerignore +.git +.gitignore +.editorconfig +README.md +tests/ +.editor/ +*.log +output/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..af7e023 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +# syntax=docker/dockerfile:1 +FROM node:20-alpine + +WORKDIR /app + +# Install dependencies +COPY package*.json ./ +RUN npm ci --only=production + +# Copy application code +COPY server ./server +COPY web ./web +COPY testcases ./testcases +COPY testplans ./testplans + +# Create output directory (for generated reports/plans) +RUN mkdir -p output/testplans output/reports + +EXPOSE 4321 + +ENV NODE_ENV=production +ENV PORT=4321 + +CMD ["node", "server/index.js"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..09e8654 --- /dev/null +++ b/README.md @@ -0,0 +1,62 @@ +# Autotest + +Sistema de gestión de planes y casos de prueba basado en YAML, con interfaz web para edición y exportación. + +## Requisitos + +- Docker y Docker Compose (recomendado) +- Node.js 20+ (solo si quieres ejecutarlo sin Docker) + +## Ejecución recomendada (Docker) + +```bash +# Levantar el editor +docker compose up -d --build + +# Ver logs +docker compose logs -f autotest + +# Parar +docker compose down +``` + +Accede a la interfaz en: **http://localhost:4321** + +Los ficheros YAML de `testcases/` y `testplans/` están montados como volúmenes, por lo que cualquier cambio que hagas desde la interfaz se refleja directamente en tu sistema de archivos (ideal para git y backups). + +## Estructura del proyecto + +``` +autotest/ +├── server/ # Backend Express +├── web/ # Frontend estático +├── testcases/ # Casos de prueba (fuente de verdad) +├── testplans/ # Planes de prueba compuestos +├── tests/ # Tests de Playwright +├── legacy/ # Datos antiguos (JSON legacy para algunos exports) +├── docker-compose.yml +└── Dockerfile +``` + +## Datos + +- Los **testcases** y **testplans** están en formato YAML bajo `testcases/` y `testplans/`. +- Estos son los ficheros versionables con Git. +- El editor web permite editarlos de forma cómoda y exportar planes (manual + automatizado). + +## Scripts útiles (opcional) + +```bash +npm install # Instala dependencias del backend +npm run web # Ejecutar localmente sin Docker (node server/index.js) +npm test # Ejecutar tests de Playwright +``` + +## Notas + +- El sistema está en transición. Algunos scripts de exportación todavía usan el JSON legacy en `legacy/data/`. +- La forma principal de uso es mediante **Docker Compose**. + +--- + +Desarrollado siguiendo principios de simplicidad y mantenibilidad. diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..6b4dbad --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,26 @@ +# Autotest - Editor Web + Backend +# Run with: docker compose up -d --build +# +# Access at: http://localhost:4321 +# YAML files are mounted via bind mounts (testcases/ and testplans/) + +services: + autotest: + build: + context: . + dockerfile: Dockerfile + container_name: autotest + restart: unless-stopped + ports: + - "4321:4321" + volumes: + # Bind mounts so YAML files are persisted and visible from host (good for git + backups) + - ./testcases:/app/testcases + - ./testplans:/app/testplans + # Optional: also persist generated outputs if you want them outside the container + - ./output:/app/output + environment: + - NODE_ENV=production + - PORT=4321 + # Uncomment the next line if you want to see live logs during development + # tty: true diff --git a/docs/project-status.html b/docs/project-status.html new file mode 100644 index 0000000..f625b4d --- /dev/null +++ b/docs/project-status.html @@ -0,0 +1,202 @@ + + + + + + Autotest • Seguimiento del Proyecto + + + + + +
+ + +
+
+
+ +
+
+

Autotest

+

Seguimiento del proyecto

+
+
+
+
Última actualización
+
25 de mayo de 2026
+
+
+ + +
+
+
+
Estado actual
+
Fase 3 completada
+
+
+
58%
+
del proyecto reestructurado
+
+
+ +
+
+
+ +
+
Reestructuración + Base técnica
+
Funcionalidad completa (Test Plans + Export)
+
+
+ +
+ + +
+
+ +
Completado
+
+ +
+
+
+
+
Reestructuración del proyecto
+
Estructura limpia: server/ + web/
+
+
Fase 1
+
+
+ +
+
+
+
Docker Compose listo
+
Despliegue con un solo comando + bind mounts para YAMLs
+
+
Fase 2
+
+
+ +
+
+
+
Limpieza final
+
Carpeta antigua editor/ eliminada
+
+
Fase 3
+
+
+ +
+
+
+
YAML como fuente de verdad
+
Lectura y escritura de testcases en YAML
+
+
+
+ +
+
+
+
Edición por paso
+
Cada paso puede marcarse como automatizable o no
+
+
+
+ +
+
+
+
Mejora del navbar
+
Botones más compactos con icono + palabra corta
+
+
+
+
+
+ + +
+
+ +
Pendiente
+
+ +
+
+
+
Fase C – Gestión de Test Plans
+ Alta +
+
+ Crear, editar y componer planes de prueba desde la interfaz.
+ Seleccionar testcases por ID y definir dependencias. +
+
+ +
+
+
Fase D – Exportación de planes
+ Alta +
+
+ Exportar un testplan compuesto generando:
+ • HTML para pruebas manuales
+ • Fichero .spec.ts para Playwright + MCP +
+
+ +
+
Mejoras en Docker
+
Healthcheck, variables de entorno, logging mejorado, multi-stage más optimizado.
+
+ +
+
Limpieza legacy
+
Eliminar referencias al JSON antiguo y los scripts que todavía lo usan.
+
+
+
+
+ + +
+
Cómo ejecutar el proyecto
+ +
+
+
RECOMENDADO
+
+ docker compose up -d --build +
+
Accede en http://localhost:4321
+
+
+
LOCAL (sin Docker)
+
+ npm run web +
+
+
+
+ +
+ Proyecto en buen estado. Base técnica sólida.
+ Próximo foco recomendado: Fase C (Test Plans) +
+ +
+ + diff --git a/editor/README.md b/editor/README.md deleted file mode 100644 index f58ec8f..0000000 --- a/editor/README.md +++ /dev/null @@ -1,55 +0,0 @@ -# Test Plan Editor - -Graphical web editor for the PBX / Core QA Automation Test Cases. - -## How to run - -```bash -cd editor - -# Install dependencies (only first time) -npm install - -# Start the server -npm start -``` - -Then open **http://localhost:4321** - -## Features - -- Beautiful dark UI consistent with the project -- Filter by module, group, status and free-text search -- Click any test case to open a rich editor: - - Edit description - - Change status (Automated / Partial / Manual) - - Manage ordered list of **Test Steps** - - Manage **Automatable** items (green) - - Manage **Not Automatable Yet** items (red) - - Add / edit / remove **Dependencies** (label + value) -- Save button per test (applies to in-memory copy) -- Global **"Save All Changes"** button → persists everything to `data/testcases.json` -- Keyboard shortcut: `Cmd/Ctrl + S` to save everything - -## Data - -All data lives in `editor/data/testcases.json`. - -You can re-generate the initial data from the old static report anytime by running: - -```bash -node editor/bootstrap-from-report.js -``` - -## Future ideas (if you want to expand) - -- Export an updated `report/test-plan.html` with the new data embedded -- Connect the main report to load from this JSON instead of the hardcoded array -- Visual drag & drop reordering of steps -- Bulk status change -- Integration with the actual .spec.ts files (parse + write real test code) - -## Notes - -- This editor is meant for the **planning / metadata** layer (steps, what is automatable, dependencies, manual reasons, etc.). -- The actual Playwright test code in `tests/` remains the source of truth for execution. diff --git a/editor/bootstrap-from-report.js b/editor/bootstrap-from-report.js deleted file mode 100644 index ba567e8..0000000 --- a/editor/bootstrap-from-report.js +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env node -/** - * Bootstrap script: extracts test cases from the existing report/test-plan.html - * and generates editor/data/testcases.json with the enriched structure. - * - * Run once: node editor/bootstrap-from-report.js - */ - -const fs = require('fs'); -const path = require('path'); -const { enrichTestCase } = require('./lib/enrich'); - -const REPORTS_DIR = path.join(__dirname, 'output', 'reports'); -const OUTPUT_FILE = path.join(__dirname, 'data', 'testcases.json'); - -console.log('Looking for latest automation report in output/reports/...'); - -// Find the latest *_qa_automation.html file -const files = fs.readdirSync(REPORTS_DIR) - .filter(f => f.endsWith('_qa_automation.html')) - .map(f => ({ - name: f, - time: fs.statSync(path.join(REPORTS_DIR, f)).mtime.getTime() - })) - .sort((a, b) => b.time - a.time); - -if (files.length === 0) { - console.error('ERROR: No qa_automation.html reports found in editor/output/reports/'); - console.error('Please run the editor and use Export → Full Report at least once.'); - process.exit(1); -} - -const latestReport = path.join(REPORTS_DIR, files[0].name); -console.log(`Using latest report: ${latestReport}`); - -const html = fs.readFileSync(latestReport, 'utf8'); - -// Extract the TESTS = [...] array using regex (simple but effective for this case) -const match = html.match(/const TESTS = (\[[\s\S]*?\]);/); - -if (!match) { - console.error('ERROR: Could not find TESTS array in the report file.'); - process.exit(1); -} - -let tests; -try { - // eslint-disable-next-line no-eval - tests = eval('(' + match[1] + ')'); -} catch (e) { - console.error('Failed to parse TESTS array:', e.message); - process.exit(1); -} - -console.log(`Found ${tests.length} test cases.`); - -// Convert + enrich with smart defaults (same logic used in the report modal) -const enriched = tests.map(t => { - const base = { - id: t.id, - group: t.group, - module: t.module, - action: t.action, - description: t.description, - status: t.status, - file: t.file, - manualReason: t.manualReason || undefined, - partialNotes: t.partialNotes || undefined - }; - - const rich = enrichTestCase(base); - return { - ...base, - steps: rich.steps, - automatable: rich.automatable, - notYet: rich.notYet, - dependencies: rich.dependencies - }; -}); - -fs.writeFileSync(OUTPUT_FILE, JSON.stringify(enriched, null, 2)); - -console.log(`✅ Generated ${OUTPUT_FILE} with ${enriched.length} fully enriched test cases.`); -console.log(' All automatable / not-automatable / steps / dependencies are pre-loaded.'); -console.log('You can now start the editor: cd editor && npm start'); diff --git a/editor/node_modules/es-object-atoms/CHANGELOG.md b/editor/node_modules/es-object-atoms/CHANGELOG.md deleted file mode 100644 index fdd2abe..0000000 --- a/editor/node_modules/es-object-atoms/CHANGELOG.md +++ /dev/null @@ -1,37 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [v1.1.1](https://github.com/ljharb/es-object-atoms/compare/v1.1.0...v1.1.1) - 2025-01-14 - -### Commits - -- [types] `ToObject`: improve types [`cfe8c8a`](https://github.com/ljharb/es-object-atoms/commit/cfe8c8a105c44820cb22e26f62d12ef0ad9715c8) - -## [v1.1.0](https://github.com/ljharb/es-object-atoms/compare/v1.0.1...v1.1.0) - 2025-01-14 - -### Commits - -- [New] add `isObject` [`51e4042`](https://github.com/ljharb/es-object-atoms/commit/51e4042df722eb3165f40dc5f4bf33d0197ecb07) - -## [v1.0.1](https://github.com/ljharb/es-object-atoms/compare/v1.0.0...v1.0.1) - 2025-01-13 - -### Commits - -- [Dev Deps] update `@ljharb/eslint-config`, `@ljharb/tsconfig`, `@types/tape`, `auto-changelog`, `tape` [`38ab9eb`](https://github.com/ljharb/es-object-atoms/commit/38ab9eb00b62c2f4668644f5e513d9b414ebd595) -- [types] improve types [`7d1beb8`](https://github.com/ljharb/es-object-atoms/commit/7d1beb887958b78b6a728a210a1c8370ab7e2aa1) -- [Tests] replace `aud` with `npm audit` [`25863ba`](https://github.com/ljharb/es-object-atoms/commit/25863baf99178f1d1ad33d1120498db28631907e) -- [Dev Deps] add missing peer dep [`c012309`](https://github.com/ljharb/es-object-atoms/commit/c0123091287e6132d6f4240496340c427433df28) - -## v1.0.0 - 2024-03-16 - -### Commits - -- Initial implementation, tests, readme, types [`f1499db`](https://github.com/ljharb/es-object-atoms/commit/f1499db7d3e1741e64979c61d645ab3137705e82) -- Initial commit [`99eedc7`](https://github.com/ljharb/es-object-atoms/commit/99eedc7b5fde38a50a28d3c8b724706e3e4c5f6a) -- [meta] rename repo [`fc851fa`](https://github.com/ljharb/es-object-atoms/commit/fc851fa70616d2d182aaf0bd02c2ed7084dea8fa) -- npm init [`b909377`](https://github.com/ljharb/es-object-atoms/commit/b909377c50049bd0ec575562d20b0f9ebae8947f) -- Only apps should have lockfiles [`7249edd`](https://github.com/ljharb/es-object-atoms/commit/7249edd2178c1b9ddfc66ffcc6d07fdf0d28efc1) diff --git a/editor/node_modules/es-object-atoms/isObject.d.ts b/editor/node_modules/es-object-atoms/isObject.d.ts deleted file mode 100644 index 43bee3b..0000000 --- a/editor/node_modules/es-object-atoms/isObject.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -declare function isObject(x: unknown): x is object; - -export = isObject; diff --git a/editor/output/reports/2026-05-22_10-49-21_qa_automation.html b/editor/output/reports/2026-05-22_10-49-21_qa_automation.html deleted file mode 100644 index 9287660..0000000 --- a/editor/output/reports/2026-05-22_10-49-21_qa_automation.html +++ /dev/null @@ -1,936 +0,0 @@ - - - - - - QA Automation Test Plan Report - - - - - -
-
-
-

QA Automation Test Plan Report

-

Generated from Test Case Editor • 2026-05-22

-
-
- 86 test cases • 39.5% automated -
-
- - -
-
-
TOTAL TESTS
-
86
-
-
-
AUTOMATED
-
34
-
39.5%
-
-
-
PARTIAL
-
16
-
18.6%
-
-
-
MANUAL
-
36
-
41.9%
-
-
- -
TEST CASES
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#IDGroupStatusDescription
1core-repository-check-presence_of_release_notes_and_changelogcore-repository - automated - Verify Release Notes and Changelog are present in the software repository
2core-repository-check-presence_of_trouble_shooting_guidecore-repository - automated - Verify Troubleshooting Guide is present in the repository
3core-repository-check-presence_of_all_mandatory_core-documentation_filescore-repository - automated - Verify all mandatory core documentation files are listed in the repository
4core-repository-check-presence_of_main_software_version_all_hypervisorscore-repository - automated - Verify main software version packages are available for all supported hypervisors
5core-repository-check-presence_of_patch_version_and_its_compatibilitycore-repository - automated - Verify patch version packages and compatibility matrices are present
6core-repository-check-presence_of_companion_tools_and_supporting_scriptscore-repository - automated - Verify companion tools and supporting scripts are available in the repository
7core-documentation-write-release_notes_feature_changes_and_known_issuescore-documentation - automated - Extract and record Release Notes, feature changes, and known issues
8core-documentation-check-accuracy_installation_and_configuration_guidecore-documentation - manual - Verify accuracy of the Installation and Configuration Guide against actual system behaviour
9core-documentation-check-accuracy_trouble_shooting_guidecore-documentation - manual - Verify the Troubleshooting Guide procedures are accurate and complete
10core-documentation-write-changed_cli_configuration_commandscore-documentation - automated - Extract and record changed CLI configuration commands for this release
11core-features-write-summary_of_each_new_feature_per_releasecore-features - automated - Extract and record a summary of each new feature included in this release
12core-features-check-integration_of_new_features_with_existing_call_processing_and_modulescore-features - partial - Verify new features integrate correctly with existing call processing and system modules
13core-features-check-backward_compatibility_of_new_featurescore-features - partial - Verify new features are backward-compatible with existing configurations and older endpoint firmware
14core-features-check-performance_and_resource_impact_assessment_of_new_featurescore-features - manual - Assess CPU/memory/network resource impact of new features under representative call load
15core-features-write-analysis_of_new_security_riskscore-features - manual - Identify, analyse, and document new security risks introduced by features in this release
16core-features-write-ui_ux_and_admin_portal_changes_validationcore-features - automated - Capture and record all UI/UX changes in the admin portal for this release
17core-features-check-provisioning_changes_for_new_featurescore-features - automated - Verify provisioning settings for new features are accessible in the admin portal
18core-virtualization-write-supported_hypervisors_deploymentcore-virtualization - automated - Record the list of supported hypervisors and deployment methods from the download portal
19core-virtualization-write-guest_agent_integrationcore-virtualization - manual - Record guest agent integration status for each supported hypervisor
20core-virtualization-write-resource_allocation_vcpu_vram_vdiskcore-virtualization - manual - Record vCPU, vRAM, and vDisk resource allocation for deployment templates
21core-virtualization-write-virtual_networking_configurationcore-virtualization - manual - Record virtual networking configuration: virtual switches, VLANs, NIC assignments
22core-virtualization-check-live_migration_and_active_call_preservationcore-virtualization - manual - Verify VM live migration preserves active calls without interruption
23core-virtualization-check-snapshot_backup_restore_and_consistencycore-virtualization - partial - Verify VM snapshot and restore operations maintain full system consistency
24core-virtualization-check-hypervisor_level_high_availabilitycore-virtualization - manual - Verify hypervisor-level HA restarts the PBX VM after a host failure
25core-virtualization-write-storage_thin_vs_thick_provisioningcore-virtualization - manual - Record storage provisioning type and performance implications for each hypervisor
26core-security-write-strong_password_policycore-security - automated - Navigate to security settings and record the current password policy configuration
27core-security-check-sip_tls_and_srtp_encryption_enabled_by_defaultcore-security - automated - Verify SIP TLS and SRTP media encryption are enabled by default
28core-security-check-ip_access_control_listscore-security - automated - Verify IP Access Control Lists are properly configured and enforced
29core-security-check-unnecessary_services_and_ports_are_disabledcore-security - partial - Verify unnecessary services and network ports are disabled
30core-security-check-security_event_logging_and_audit_trail_is_activecore-security - automated - Verify security event logging and audit trail are active and recording events
31core-security-check-auto_enrollment_certificate_management_processcore-security - automated - Verify auto-enrollment certificate management (ACME/Let's Encrypt) is configured and functional
32core-security-check-known_vulnerable_dependencies_in_release_artifactscore-security - partial - Verify release artifacts do not contain known vulnerable dependencies (CVE scan)
33core-security-check-previous_security_findings_have_been_remediated_before_releasecore-security - manual - Verify all previously identified security findings are remediated before release
34core-security-check-obtain_formal_security_team_sign_off_for_the_new_versioncore-security - manual - Obtain formal written sign-off from the Security team approving the release
35core-security-check-verify_role_based_access_control_and_least_privilege_principlecore-security - automated - Verify RBAC roles are correctly defined and least-privilege principle is enforced
36core-security-check-encryption_of_sensitive_data_at_rest_and_in_transitcore-security - partial - Verify sensitive data is encrypted at rest (DB) and in transit (HTTPS/TLS)
37core-installation-check-fresh_installationcore-installation - manual - Verify complete fresh installation from scratch succeeds on each supported hypervisor
38core-installation-check-post_install_service_status_and_port_verificationcore-installation - partial - Verify all required services are running and expected ports are open after installation
39core-installation-check-initial_configurationcore-installation - automated - Verify the initial configuration wizard completes successfully
40core-installation-check-license_activationcore-installation - automated - Verify license activation completes successfully and licensed features are unlocked
41core-upgrade-check-in_place_upgrade_from_previous_major_versioncore-upgrade - manual - Verify in-place upgrade from the previous major version completes successfully without data loss
42core-upgrade-check-configuration_and_database_migration_validationcore-upgrade - partial - Verify configuration objects and database content migrate correctly after upgrade
43core-upgrade-check-schema_upgrade_and_data_integrity_checkcore-upgrade - manual - Verify database schema is correctly upgraded and all data maintains integrity
44core-upgrade-check-rollback_procedure_execution_and_verificationcore-upgrade - manual - Verify the rollback procedure successfully reverts the system to the previous version
45core-upgrade-check-post_upgrade_regression_of_core_featurescore-upgrade - automated - Run automated regression checks on core portal features after upgrade
46core-upgrade-check-zero_downtime_upgrade_where_supportedcore-upgrade - manual - Verify zero-downtime upgrade keeps the service available throughout the upgrade process
47core-interoperability-check-addmcore-interoperability - automated - Verify ADDM integration is configured and reporting discovery data correctly
48core-interoperability-check-siemcore-interoperability - automated - Verify SIEM integration is configured and forwarding security events
49pbx-configuration-check-initial_system_setup_and_network_settingspbx-configuration - automated - Verify initial PBX system setup and network settings are correctly configured
50pbx-configuration-check-dialplan_route_and_outbound_rule_creationpbx-configuration - automated - Verify creation and validation of dial plan rules and outbound routes
51pbx-configuration-check-backup_restore_full_system_configurationpbx-configuration - automated - Verify full system configuration backup and restore operations work correctly
52pbx-configuration-check-bulk_csv_import_export_of_settingspbx-configuration - automated - Verify bulk CSV import and export of settings
53pbx-extensions-check-create_modify_delete_sip_extensionspbx-extensions - automated - Verify full CRUD lifecycle for SIP extensions in the admin portal
54pbx-extensions-check-extension_registration_with_deskphones_softphonespbx-extensions - manual - Verify SIP extension registers successfully from a desk phone and a softphone client
55pbx-extensions-check-device_provisioningpbx-extensions - partial - Verify automatic device provisioning: profile generation and server URL accessible
56pbx-calls-check-internal_extension_to_extension_audio_callpbx-calls - manual - Verify internal extension-to-extension audio call connects with bi-directional audio
57pbx-calls-check-inbound_call_from_sip_trunk_pstnpbx-calls - manual - Verify inbound call from a SIP trunk/PSTN routes correctly to the configured destination
58pbx-calls-check-outbound_call_to_sip_trunk_pstn_with_caller_idpbx-calls - manual - Verify outbound call via SIP trunk presents the correct Caller ID on the receiving end
59pbx-calls-check-caller_id_presentation_restriction_and_paipbx-calls - manual - Verify Caller ID presentation, Anonymous restriction (CLIR), and P-Asserted-Identity header
60pbx-calls-check-call_hold_resume_and_music_on_holdpbx-calls - manual - Verify call hold, resume, and Music on Hold playback work correctly
61pbx-calls-check-call_waiting_notification_and_switchingpbx-calls - manual - Verify call waiting notification and switching between active and waiting calls
62pbx-calls-check-three_way_conference_and_multi_party_bridgepbx-calls - manual - Verify three-way conference calling and multi-party conference bridge functionality
63pbx-codecs-check-codec_negotiation_g711_g729_opus_g722pbx-codecs - manual - Verify successful codec negotiation for G.711, G.729, Opus, and G.722
64pbx-codecs-check-dtmf_transmission_rfc2833_inband_sip_infopbx-codecs - manual - Verify DTMF digit transmission via RFC2833, in-band audio, and SIP INFO methods
65pbx-codecs-check-t38_fax_passthrough_and_error_correctionpbx-codecs - manual - Verify T.38 fax passthrough and error correction (ECM) work correctly
66pbx-calls-security-check-srtp_sdes_or_dtls_media_encryptionpbx-calls-security - partial - Verify SRTP with SDES or DTLS-SRTP is enabled for media encryption on calls
67pbx-calls-security-check-acl_ip_whitelisting_and_rate_limitingpbx-calls-security - partial - Verify ACL IP whitelisting rules and SIP rate limiting are configured and enforced
68pbx-calls-security-check-toll_fraud_prevention_rules_and_alertingpbx-calls-security - automated - Verify toll fraud prevention rules and alert notifications are configured
69pbx-performance-check-cpu_memory_disk_io_utilization_under_sustained_loadpbx-performance - manual - Verify CPU, memory, and disk I/O remain within limits under sustained call load
70pbx-performance-check-long_duration_stability_72h_testpbx-performance - manual - Verify system stability under continuous call load over a 72-hour period
71pbx-performance-check-memory_leak_and_resource_cleanup_detectionpbx-performance - manual - Detect memory leaks and verify proper resource cleanup over extended operation
72pbx-availability-check-active_passive_or_active_active_failoverpbx-availability - manual - Verify Active-Passive or Active-Active failover transitions correctly on node failure
73pbx-availability-check-database_replication_and_sync_integritypbx-availability - manual - Verify database replication between HA nodes maintains consistency and acceptable lag
74pbx-availability-check-automatic_failover_and_call_preservationpbx-availability - manual - Verify automatic failover preserves active calls (no drops, no audio interruption > 200ms)
75pbx-availability-check-geographic_redundancy_and_geo_distributionpbx-availability - manual - Verify geo-distributed deployment handles site failover without service interruption
76pbx-management-check-cli_managementpbx-management - partial - Verify CLI management interface is accessible and key management commands execute correctly
77pbx-management-check-gui_managementpbx-management - automated - Verify all main admin portal sections load correctly and management actions are functional
78pbx-logs-check-cdr_generation_accuracy_completeness_and_exportpbx-logs - automated - Verify CDR records contain all required fields and can be exported to CSV/PDF
79pbx-logs-check-real_time_active_call_and_registration_monitoringpbx-logs - automated - Verify real-time monitoring dashboard shows active calls and SIP registrations
80pbx-logs-check-detailed_logging_levels_rotation_and_searchpbx-logs - automated - Verify logging levels, log rotation, and log search/filter functionality
81pbx-logs-check-threshold_alarms_cpu_channels_disk_memorypbx-logs - automated - Verify threshold-based alarms for CPU, active channels, disk, and memory usage
82pbx-logs-check-call_quality_metrics_mos_jitter_loss_per_callpbx-logs - partial - Verify per-call quality metrics (MOS score, jitter, packet loss) are collected and displayed
83pbx-regression-check-core_call_features_after_any_code_changepbx-regression - partial - Run regression checks on core features after any code change to detect regressions
84pbx-regression-check-previously_fixed_bugs_and_edge_cases_reverificationpbx-regression - partial - Verify all previously fixed bugs and known edge cases have not regressed
85pbx-regression-check-performance_baselines_comparison_against_previous_versionpbx-regression - manual - Compare key performance metrics against baselines from the previous version
86pbx-regression-check-security_hardening_and_vulnerability_scan_baselinepbx-regression - partial - Verify security hardening settings and compare vulnerability scan baseline against previous version
-
- -
- Generated by Test Case Editor • Data source: editor/data/testcases.json -
-
- - \ No newline at end of file diff --git a/editor/output/reports/2026-05-22_10-51-18_qa_automation.html b/editor/output/reports/2026-05-22_10-51-18_qa_automation.html deleted file mode 100644 index 9287660..0000000 --- a/editor/output/reports/2026-05-22_10-51-18_qa_automation.html +++ /dev/null @@ -1,936 +0,0 @@ - - - - - - QA Automation Test Plan Report - - - - - -
-
-
-

QA Automation Test Plan Report

-

Generated from Test Case Editor • 2026-05-22

-
-
- 86 test cases • 39.5% automated -
-
- - -
-
-
TOTAL TESTS
-
86
-
-
-
AUTOMATED
-
34
-
39.5%
-
-
-
PARTIAL
-
16
-
18.6%
-
-
-
MANUAL
-
36
-
41.9%
-
-
- -
TEST CASES
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#IDGroupStatusDescription
1core-repository-check-presence_of_release_notes_and_changelogcore-repository - automated - Verify Release Notes and Changelog are present in the software repository
2core-repository-check-presence_of_trouble_shooting_guidecore-repository - automated - Verify Troubleshooting Guide is present in the repository
3core-repository-check-presence_of_all_mandatory_core-documentation_filescore-repository - automated - Verify all mandatory core documentation files are listed in the repository
4core-repository-check-presence_of_main_software_version_all_hypervisorscore-repository - automated - Verify main software version packages are available for all supported hypervisors
5core-repository-check-presence_of_patch_version_and_its_compatibilitycore-repository - automated - Verify patch version packages and compatibility matrices are present
6core-repository-check-presence_of_companion_tools_and_supporting_scriptscore-repository - automated - Verify companion tools and supporting scripts are available in the repository
7core-documentation-write-release_notes_feature_changes_and_known_issuescore-documentation - automated - Extract and record Release Notes, feature changes, and known issues
8core-documentation-check-accuracy_installation_and_configuration_guidecore-documentation - manual - Verify accuracy of the Installation and Configuration Guide against actual system behaviour
9core-documentation-check-accuracy_trouble_shooting_guidecore-documentation - manual - Verify the Troubleshooting Guide procedures are accurate and complete
10core-documentation-write-changed_cli_configuration_commandscore-documentation - automated - Extract and record changed CLI configuration commands for this release
11core-features-write-summary_of_each_new_feature_per_releasecore-features - automated - Extract and record a summary of each new feature included in this release
12core-features-check-integration_of_new_features_with_existing_call_processing_and_modulescore-features - partial - Verify new features integrate correctly with existing call processing and system modules
13core-features-check-backward_compatibility_of_new_featurescore-features - partial - Verify new features are backward-compatible with existing configurations and older endpoint firmware
14core-features-check-performance_and_resource_impact_assessment_of_new_featurescore-features - manual - Assess CPU/memory/network resource impact of new features under representative call load
15core-features-write-analysis_of_new_security_riskscore-features - manual - Identify, analyse, and document new security risks introduced by features in this release
16core-features-write-ui_ux_and_admin_portal_changes_validationcore-features - automated - Capture and record all UI/UX changes in the admin portal for this release
17core-features-check-provisioning_changes_for_new_featurescore-features - automated - Verify provisioning settings for new features are accessible in the admin portal
18core-virtualization-write-supported_hypervisors_deploymentcore-virtualization - automated - Record the list of supported hypervisors and deployment methods from the download portal
19core-virtualization-write-guest_agent_integrationcore-virtualization - manual - Record guest agent integration status for each supported hypervisor
20core-virtualization-write-resource_allocation_vcpu_vram_vdiskcore-virtualization - manual - Record vCPU, vRAM, and vDisk resource allocation for deployment templates
21core-virtualization-write-virtual_networking_configurationcore-virtualization - manual - Record virtual networking configuration: virtual switches, VLANs, NIC assignments
22core-virtualization-check-live_migration_and_active_call_preservationcore-virtualization - manual - Verify VM live migration preserves active calls without interruption
23core-virtualization-check-snapshot_backup_restore_and_consistencycore-virtualization - partial - Verify VM snapshot and restore operations maintain full system consistency
24core-virtualization-check-hypervisor_level_high_availabilitycore-virtualization - manual - Verify hypervisor-level HA restarts the PBX VM after a host failure
25core-virtualization-write-storage_thin_vs_thick_provisioningcore-virtualization - manual - Record storage provisioning type and performance implications for each hypervisor
26core-security-write-strong_password_policycore-security - automated - Navigate to security settings and record the current password policy configuration
27core-security-check-sip_tls_and_srtp_encryption_enabled_by_defaultcore-security - automated - Verify SIP TLS and SRTP media encryption are enabled by default
28core-security-check-ip_access_control_listscore-security - automated - Verify IP Access Control Lists are properly configured and enforced
29core-security-check-unnecessary_services_and_ports_are_disabledcore-security - partial - Verify unnecessary services and network ports are disabled
30core-security-check-security_event_logging_and_audit_trail_is_activecore-security - automated - Verify security event logging and audit trail are active and recording events
31core-security-check-auto_enrollment_certificate_management_processcore-security - automated - Verify auto-enrollment certificate management (ACME/Let's Encrypt) is configured and functional
32core-security-check-known_vulnerable_dependencies_in_release_artifactscore-security - partial - Verify release artifacts do not contain known vulnerable dependencies (CVE scan)
33core-security-check-previous_security_findings_have_been_remediated_before_releasecore-security - manual - Verify all previously identified security findings are remediated before release
34core-security-check-obtain_formal_security_team_sign_off_for_the_new_versioncore-security - manual - Obtain formal written sign-off from the Security team approving the release
35core-security-check-verify_role_based_access_control_and_least_privilege_principlecore-security - automated - Verify RBAC roles are correctly defined and least-privilege principle is enforced
36core-security-check-encryption_of_sensitive_data_at_rest_and_in_transitcore-security - partial - Verify sensitive data is encrypted at rest (DB) and in transit (HTTPS/TLS)
37core-installation-check-fresh_installationcore-installation - manual - Verify complete fresh installation from scratch succeeds on each supported hypervisor
38core-installation-check-post_install_service_status_and_port_verificationcore-installation - partial - Verify all required services are running and expected ports are open after installation
39core-installation-check-initial_configurationcore-installation - automated - Verify the initial configuration wizard completes successfully
40core-installation-check-license_activationcore-installation - automated - Verify license activation completes successfully and licensed features are unlocked
41core-upgrade-check-in_place_upgrade_from_previous_major_versioncore-upgrade - manual - Verify in-place upgrade from the previous major version completes successfully without data loss
42core-upgrade-check-configuration_and_database_migration_validationcore-upgrade - partial - Verify configuration objects and database content migrate correctly after upgrade
43core-upgrade-check-schema_upgrade_and_data_integrity_checkcore-upgrade - manual - Verify database schema is correctly upgraded and all data maintains integrity
44core-upgrade-check-rollback_procedure_execution_and_verificationcore-upgrade - manual - Verify the rollback procedure successfully reverts the system to the previous version
45core-upgrade-check-post_upgrade_regression_of_core_featurescore-upgrade - automated - Run automated regression checks on core portal features after upgrade
46core-upgrade-check-zero_downtime_upgrade_where_supportedcore-upgrade - manual - Verify zero-downtime upgrade keeps the service available throughout the upgrade process
47core-interoperability-check-addmcore-interoperability - automated - Verify ADDM integration is configured and reporting discovery data correctly
48core-interoperability-check-siemcore-interoperability - automated - Verify SIEM integration is configured and forwarding security events
49pbx-configuration-check-initial_system_setup_and_network_settingspbx-configuration - automated - Verify initial PBX system setup and network settings are correctly configured
50pbx-configuration-check-dialplan_route_and_outbound_rule_creationpbx-configuration - automated - Verify creation and validation of dial plan rules and outbound routes
51pbx-configuration-check-backup_restore_full_system_configurationpbx-configuration - automated - Verify full system configuration backup and restore operations work correctly
52pbx-configuration-check-bulk_csv_import_export_of_settingspbx-configuration - automated - Verify bulk CSV import and export of settings
53pbx-extensions-check-create_modify_delete_sip_extensionspbx-extensions - automated - Verify full CRUD lifecycle for SIP extensions in the admin portal
54pbx-extensions-check-extension_registration_with_deskphones_softphonespbx-extensions - manual - Verify SIP extension registers successfully from a desk phone and a softphone client
55pbx-extensions-check-device_provisioningpbx-extensions - partial - Verify automatic device provisioning: profile generation and server URL accessible
56pbx-calls-check-internal_extension_to_extension_audio_callpbx-calls - manual - Verify internal extension-to-extension audio call connects with bi-directional audio
57pbx-calls-check-inbound_call_from_sip_trunk_pstnpbx-calls - manual - Verify inbound call from a SIP trunk/PSTN routes correctly to the configured destination
58pbx-calls-check-outbound_call_to_sip_trunk_pstn_with_caller_idpbx-calls - manual - Verify outbound call via SIP trunk presents the correct Caller ID on the receiving end
59pbx-calls-check-caller_id_presentation_restriction_and_paipbx-calls - manual - Verify Caller ID presentation, Anonymous restriction (CLIR), and P-Asserted-Identity header
60pbx-calls-check-call_hold_resume_and_music_on_holdpbx-calls - manual - Verify call hold, resume, and Music on Hold playback work correctly
61pbx-calls-check-call_waiting_notification_and_switchingpbx-calls - manual - Verify call waiting notification and switching between active and waiting calls
62pbx-calls-check-three_way_conference_and_multi_party_bridgepbx-calls - manual - Verify three-way conference calling and multi-party conference bridge functionality
63pbx-codecs-check-codec_negotiation_g711_g729_opus_g722pbx-codecs - manual - Verify successful codec negotiation for G.711, G.729, Opus, and G.722
64pbx-codecs-check-dtmf_transmission_rfc2833_inband_sip_infopbx-codecs - manual - Verify DTMF digit transmission via RFC2833, in-band audio, and SIP INFO methods
65pbx-codecs-check-t38_fax_passthrough_and_error_correctionpbx-codecs - manual - Verify T.38 fax passthrough and error correction (ECM) work correctly
66pbx-calls-security-check-srtp_sdes_or_dtls_media_encryptionpbx-calls-security - partial - Verify SRTP with SDES or DTLS-SRTP is enabled for media encryption on calls
67pbx-calls-security-check-acl_ip_whitelisting_and_rate_limitingpbx-calls-security - partial - Verify ACL IP whitelisting rules and SIP rate limiting are configured and enforced
68pbx-calls-security-check-toll_fraud_prevention_rules_and_alertingpbx-calls-security - automated - Verify toll fraud prevention rules and alert notifications are configured
69pbx-performance-check-cpu_memory_disk_io_utilization_under_sustained_loadpbx-performance - manual - Verify CPU, memory, and disk I/O remain within limits under sustained call load
70pbx-performance-check-long_duration_stability_72h_testpbx-performance - manual - Verify system stability under continuous call load over a 72-hour period
71pbx-performance-check-memory_leak_and_resource_cleanup_detectionpbx-performance - manual - Detect memory leaks and verify proper resource cleanup over extended operation
72pbx-availability-check-active_passive_or_active_active_failoverpbx-availability - manual - Verify Active-Passive or Active-Active failover transitions correctly on node failure
73pbx-availability-check-database_replication_and_sync_integritypbx-availability - manual - Verify database replication between HA nodes maintains consistency and acceptable lag
74pbx-availability-check-automatic_failover_and_call_preservationpbx-availability - manual - Verify automatic failover preserves active calls (no drops, no audio interruption > 200ms)
75pbx-availability-check-geographic_redundancy_and_geo_distributionpbx-availability - manual - Verify geo-distributed deployment handles site failover without service interruption
76pbx-management-check-cli_managementpbx-management - partial - Verify CLI management interface is accessible and key management commands execute correctly
77pbx-management-check-gui_managementpbx-management - automated - Verify all main admin portal sections load correctly and management actions are functional
78pbx-logs-check-cdr_generation_accuracy_completeness_and_exportpbx-logs - automated - Verify CDR records contain all required fields and can be exported to CSV/PDF
79pbx-logs-check-real_time_active_call_and_registration_monitoringpbx-logs - automated - Verify real-time monitoring dashboard shows active calls and SIP registrations
80pbx-logs-check-detailed_logging_levels_rotation_and_searchpbx-logs - automated - Verify logging levels, log rotation, and log search/filter functionality
81pbx-logs-check-threshold_alarms_cpu_channels_disk_memorypbx-logs - automated - Verify threshold-based alarms for CPU, active channels, disk, and memory usage
82pbx-logs-check-call_quality_metrics_mos_jitter_loss_per_callpbx-logs - partial - Verify per-call quality metrics (MOS score, jitter, packet loss) are collected and displayed
83pbx-regression-check-core_call_features_after_any_code_changepbx-regression - partial - Run regression checks on core features after any code change to detect regressions
84pbx-regression-check-previously_fixed_bugs_and_edge_cases_reverificationpbx-regression - partial - Verify all previously fixed bugs and known edge cases have not regressed
85pbx-regression-check-performance_baselines_comparison_against_previous_versionpbx-regression - manual - Compare key performance metrics against baselines from the previous version
86pbx-regression-check-security_hardening_and_vulnerability_scan_baselinepbx-regression - partial - Verify security hardening settings and compare vulnerability scan baseline against previous version
-
- -
- Generated by Test Case Editor • Data source: editor/data/testcases.json -
-
- - \ No newline at end of file diff --git a/editor/output/testplans/2026-05-22_10-52-32_Manual-Test-Plan.html b/editor/output/testplans/2026-05-22_10-52-32_Manual-Test-Plan.html deleted file mode 100644 index 98ad643..0000000 --- a/editor/output/testplans/2026-05-22_10-52-32_Manual-Test-Plan.html +++ /dev/null @@ -1,154 +0,0 @@ - - - - -Manual Test Plan - Manual-Test-Plan - - - - -
-
-

Manual Test Plan

-
Manual-Test-Plan — Generated on 5/22/2026, 12:52:32 PM
-
-
Total cases: 3
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Test IDDescription & Expected ResultStepsSeverityResult / Comments
core-repository
core-repository-check-presence_of_release_notes_and_changelog - Verify Release Notes and Changelog are present in the software repository -
Expected Result
- -
-
  1. Open admin portal or repository URL in browser context
  2. Navigate to the download / documentation portal
  3. Search or locate the relevant file/link by filename pattern
  4. Assert presence and visibility of the expected document
-
Dependencies
Admin Portal: https://pbx.local:4443 (configure via $BASE_URL)
Repository URL: ${BASE_URL}/downloads or $REPO_URL
Protocol: HTTPS (admin portal) + optional SSH/CLI
Credentials: Admin user with sufficient privileges (portal + SSH where needed)
Test Data: Clean test tenant or lab PBX instance (recommended isolated environment)
-
- - -
Status
- -
Actual Result / Comments
- -
pbx-regression
pbx-regression-check-previously_fixed_bugs_and_edge_cases_reverification - Verify all previously fixed bugs and known edge cases have not regressed -
Expected Result
- -
-
  1. Open admin portal or repository URL in browser context
  2. Execute the main verification or configuration action described in the test
  3. Capture evidence (screenshot, log, API response)
  4. Assert expected outcome
-
Dependencies
Admin Portal: https://pbx.local:4443 (configure via $BASE_URL)
Repository URL: ${BASE_URL}/downloads or $REPO_URL
Protocol: HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP
Credentials: Admin user with sufficient privileges (portal + SSH where needed)
Test Data: Clean test tenant or lab PBX instance (recommended isolated environment)
-
- - -
Status
- -
Actual Result / Comments
- -
pbx-regression-check-security_hardening_and_vulnerability_scan_baseline - Verify security hardening settings and compare vulnerability scan baseline against previous version -
Expected Result
- -
-
  1. Open admin portal or repository URL in browser context
  2. Execute the main verification or configuration action described in the test
  3. Capture evidence (screenshot, log, API response)
  4. Assert expected outcome
-
Dependencies
Admin Portal: https://pbx.local:4443 (configure via $BASE_URL)
Repository URL: ${BASE_URL}/downloads or $REPO_URL
Protocol: HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP
Credentials: Admin user with sufficient privileges (portal + SSH where needed)
Test Data: Clean test tenant or lab PBX instance (recommended isolated environment)
-
- - -
Status
- -
Actual Result / Comments
- -
- -

- Generated by QA Automation Test Plan Editor • All results and comments should be filled by the tester. -

- - - \ No newline at end of file diff --git a/editor/output/testplans/2026-05-22_10-52-44_Manual-Test-Plan.html b/editor/output/testplans/2026-05-22_10-52-44_Manual-Test-Plan.html deleted file mode 100644 index 9299efa..0000000 --- a/editor/output/testplans/2026-05-22_10-52-44_Manual-Test-Plan.html +++ /dev/null @@ -1,154 +0,0 @@ - - - - -Manual Test Plan - Manual-Test-Plan - - - - -
-
-

Manual Test Plan

-
Manual-Test-Plan — Generated on 5/22/2026, 12:52:44 PM
-
-
Total cases: 3
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Test IDDescription & Expected ResultStepsSeverityResult / Comments
core-repository
core-repository-check-presence_of_release_notes_and_changelog - Verify Release Notes and Changelog are present in the software repository -
Expected Result
- -
-
  1. Open admin portal or repository URL in browser context
  2. Navigate to the download / documentation portal
  3. Search or locate the relevant file/link by filename pattern
  4. Assert presence and visibility of the expected document
-
Dependencies
Admin Portal: https://pbx.local:4443 (configure via $BASE_URL)
Repository URL: ${BASE_URL}/downloads or $REPO_URL
Protocol: HTTPS (admin portal) + optional SSH/CLI
Credentials: Admin user with sufficient privileges (portal + SSH where needed)
Test Data: Clean test tenant or lab PBX instance (recommended isolated environment)
-
- - -
Status
- -
Actual Result / Comments
- -
pbx-regression
pbx-regression-check-previously_fixed_bugs_and_edge_cases_reverification - Verify all previously fixed bugs and known edge cases have not regressed -
Expected Result
- -
-
  1. Open admin portal or repository URL in browser context
  2. Execute the main verification or configuration action described in the test
  3. Capture evidence (screenshot, log, API response)
  4. Assert expected outcome
-
Dependencies
Admin Portal: https://pbx.local:4443 (configure via $BASE_URL)
Repository URL: ${BASE_URL}/downloads or $REPO_URL
Protocol: HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP
Credentials: Admin user with sufficient privileges (portal + SSH where needed)
Test Data: Clean test tenant or lab PBX instance (recommended isolated environment)
-
- - -
Status
- -
Actual Result / Comments
- -
pbx-regression-check-security_hardening_and_vulnerability_scan_baseline - Verify security hardening settings and compare vulnerability scan baseline against previous version -
Expected Result
- -
-
  1. Open admin portal or repository URL in browser context
  2. Execute the main verification or configuration action described in the test
  3. Capture evidence (screenshot, log, API response)
  4. Assert expected outcome
-
Dependencies
Admin Portal: https://pbx.local:4443 (configure via $BASE_URL)
Repository URL: ${BASE_URL}/downloads or $REPO_URL
Protocol: HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP
Credentials: Admin user with sufficient privileges (portal + SSH where needed)
Test Data: Clean test tenant or lab PBX instance (recommended isolated environment)
-
- - -
Status
- -
Actual Result / Comments
- -
- -

- Generated by QA Automation Test Plan Editor • All results and comments should be filled by the tester. -

- - - \ No newline at end of file diff --git a/editor/output/testplans/plans/mpgtjmur_mwevcb.json b/editor/output/testplans/plans/mpgtjmur_mwevcb.json deleted file mode 100644 index bc620ec..0000000 --- a/editor/output/testplans/plans/mpgtjmur_mwevcb.json +++ /dev/null @@ -1,397 +0,0 @@ -{ - "id": "mpgtjmur_mwevcb", - "name": "Manual Test Plan", - "createdAt": "2026-05-22T11:10:52.275Z", - "updatedAt": "2026-05-22T11:11:14.189Z", - "tests": [ - { - "id": "core-documentation-write-release_notes_feature_changes_and_known_issues", - "group": "core-documentation", - "module": "core", - "action": "write", - "description": "Extract and record Release Notes, feature changes, and known issues", - "status": "automated", - "file": "tests/core/documentation.spec.ts", - "steps": [ - "Open admin portal or repository URL in browser context", - "Navigate to the download / documentation portal", - "Search or locate the relevant file/link by filename pattern", - "Assert presence and visibility of the expected document" - ], - "automatable": [ - "Full end-to-end execution via Playwright against the admin portal UI", - "Navigation, form interaction, and assertions are scriptable" - ], - "notYet": [], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ], - "severity": "High", - "expectedResult": "Extract and record Release Notes, feature changes, and known issues", - "actualResult": "ererer", - "testerStatus": "N/A", - "comments": "" - }, - { - "id": "core-documentation-check-accuracy_installation_and_configuration_guide", - "group": "core-documentation", - "module": "core", - "action": "check", - "description": "Verify accuracy of the Installation and Configuration Guide against actual system behaviour", - "status": "manual", - "file": "tests/core/documentation.spec.ts", - "manualReason": "Requires expert human review: QA engineer must follow the guide step-by-step on a clean system", - "steps": [ - "Open admin portal or repository URL in browser context", - "Navigate to the download / documentation portal", - "Search or locate the relevant file/link by filename pattern", - "Assert presence and visibility of the expected document" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires expert human review: QA engineer must follow the guide step-by-step on a clean system", - "Requires external SIP endpoints or physical phones for media/audio validation" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ], - "severity": "High", - "expectedResult": "Verify accuracy of the Installation and Configuration Guide against actual system behaviour", - "actualResult": "", - "testerStatus": "N/A", - "comments": "" - }, - { - "id": "core-documentation-check-accuracy_trouble_shooting_guide", - "group": "core-documentation", - "module": "core", - "action": "check", - "description": "Verify the Troubleshooting Guide procedures are accurate and complete", - "status": "manual", - "file": "tests/core/documentation.spec.ts", - "manualReason": "Requires expert human review to validate each troubleshooting scenario on a real system", - "steps": [ - "Open admin portal or repository URL in browser context", - "Navigate to the download / documentation portal", - "Search or locate the relevant file/link by filename pattern", - "Assert presence and visibility of the expected document" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires expert human review to validate each troubleshooting scenario on a real system", - "Requires external SIP endpoints or physical phones for media/audio validation" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ], - "severity": "High", - "expectedResult": "Verify the Troubleshooting Guide procedures are accurate and complete", - "actualResult": "", - "testerStatus": "N/A", - "comments": "" - }, - { - "id": "core-documentation-write-changed_cli_configuration_commands", - "group": "core-documentation", - "module": "core", - "action": "write", - "description": "Extract and record changed CLI configuration commands for this release", - "status": "automated", - "file": "tests/core/documentation.spec.ts", - "steps": [ - "Open admin portal or repository URL in browser context", - "Navigate to the download / documentation portal", - "Search or locate the relevant file/link by filename pattern", - "Assert presence and visibility of the expected document" - ], - "automatable": [ - "Full end-to-end execution via Playwright against the admin portal UI", - "Navigation, form interaction, and assertions are scriptable" - ], - "notYet": [], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ], - "severity": "High", - "expectedResult": "Extract and record changed CLI configuration commands for this release", - "actualResult": "", - "testerStatus": "N/A", - "comments": "" - }, - { - "id": "core-installation-check-fresh_installation", - "group": "core-installation", - "module": "core", - "action": "check", - "description": "Verify complete fresh installation from scratch succeeds on each supported hypervisor", - "status": "manual", - "file": "tests/core/installation.spec.ts", - "manualReason": "Requires provisioning a clean VM, mounting ISO/OVA, and running the installation wizard", - "steps": [ - "Open admin portal or repository URL in browser context", - "Prepare clean or previous-version VM/image", - "Perform installation or upgrade procedure", - "Post-install verification via portal + external tools" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires provisioning a clean VM, mounting ISO/OVA, and running the installation wizard", - "Requires external SIP endpoints or physical phones for media/audio validation" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ], - "severity": "High", - "expectedResult": "Verify complete fresh installation from scratch succeeds on each supported hypervisor", - "actualResult": "", - "testerStatus": "N/A", - "comments": "" - }, - { - "id": "core-installation-check-post_install_service_status_and_port_verification", - "group": "core-installation", - "module": "core", - "action": "check", - "description": "Verify all required services are running and expected ports are open after installation", - "status": "partial", - "file": "tests/core/installation.spec.ts", - "partialNotes": "Service status via admin portal automated; TCP port verification requires nmap from external host", - "steps": [ - "Open admin portal or repository URL in browser context", - "Prepare clean or previous-version VM/image", - "Perform installation or upgrade procedure", - "Post-install verification via portal + external tools" - ], - "automatable": [ - "Portal UI configuration and verification steps (already partially automated)", - "Data extraction and reporting of current settings" - ], - "notYet": [ - "Service status via admin portal automated; TCP port verification requires nmap from external host", - "Requires external SIP endpoints or physical phones for media/audio validation" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ], - "severity": "High", - "expectedResult": "Verify all required services are running and expected ports are open after installation", - "actualResult": "", - "testerStatus": "N/A", - "comments": "" - }, - { - "id": "core-installation-check-initial_configuration", - "group": "core-installation", - "module": "core", - "action": "check", - "description": "Verify the initial configuration wizard completes successfully", - "status": "automated", - "file": "tests/core/installation.spec.ts", - "steps": [ - "Open admin portal or repository URL in browser context", - "Prepare clean or previous-version VM/image", - "Perform installation or upgrade procedure", - "Post-install verification via portal + external tools" - ], - "automatable": [ - "Full end-to-end execution via Playwright against the admin portal UI", - "Navigation, form interaction, and assertions are scriptable" - ], - "notYet": [], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ], - "severity": "High", - "expectedResult": "Verify the initial configuration wizard completes successfully", - "actualResult": "", - "testerStatus": "N/A", - "comments": "" - }, - { - "id": "core-installation-check-license_activation", - "group": "core-installation", - "module": "core", - "action": "check", - "description": "Verify license activation completes successfully and licensed features are unlocked", - "status": "automated", - "file": "tests/core/installation.spec.ts", - "steps": [ - "Open admin portal or repository URL in browser context", - "Prepare clean or previous-version VM/image", - "Perform installation or upgrade procedure", - "Post-install verification via portal + external tools" - ], - "automatable": [ - "Full end-to-end execution via Playwright against the admin portal UI", - "Navigation, form interaction, and assertions are scriptable" - ], - "notYet": [], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ], - "severity": "High", - "expectedResult": "Verify license activation completes successfully and licensed features are unlocked", - "actualResult": "", - "testerStatus": "N/A", - "comments": "" - } - ] -} \ No newline at end of file diff --git a/editor/package.json b/editor/package.json deleted file mode 100644 index eba55e8..0000000 --- a/editor/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "test-plan-editor", - "version": "0.1.0", - "description": "Graphical editor for PBX/Core QA Automation Test Cases", - "main": "server.js", - "scripts": { - "start": "node server.js", - "dev": "node server.js" - }, - "dependencies": { - "cors": "^2.8.5", - "express": "^4.19.2" - } -} diff --git a/editor/scripts/types/automated-generation.ts b/editor/scripts/types/automated-generation.ts deleted file mode 100644 index 2d7725b..0000000 --- a/editor/scripts/types/automated-generation.ts +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Types related to automated test code generation from the editor data. - * These extend the base test model stored in data/testcases.json. - */ - -// ────────────────────────────────────────────────────────────── -// Core Generation Types -// ────────────────────────────────────────────────────────────── - -export interface CodeStep { - /** Human-readable step name that will become the title of `test.step()` */ - stepName: string; - - /** Key that maps to an entry in the Action Catalog (e.g. "navigate_to_downloads_portal") */ - actionKey: string; - - /** Optional parameters to be substituted into the template */ - params?: Record; -} - -export interface VerifiedSnippet { - /** The step name this snippet corresponds to */ - stepName: string; - - /** Raw Playwright / MCP code that was manually validated */ - code: string; -} - -export interface AutomatedTestExtension { - /** - * When true, this test is considered ready for full automated code generation. - * This is stricter than `status === "automated"`. - */ - fullyAutomated?: boolean; - - /** - * Ordered list of executable steps. - * Each step will be turned into a `await test.step(...)` block. - */ - codeSteps?: CodeStep[]; - - /** Free-form notes for the developer or LLM when generating code */ - implementationNotes?: string; - - /** - * Manually verified code snippets. - * These take precedence over the Action Catalog when present. - */ - verifiedSnippets?: VerifiedSnippet[]; -} - -// ────────────────────────────────────────────────────────────── -// Combined Type used by the Generator -// ────────────────────────────────────────────────────────────── - -export interface EnrichedTestForGeneration { - // Base fields (from testcases.json) - id: string; - group: string; - module: 'core' | 'pbx'; - action: 'check' | 'write'; - description: string; - status: 'automated' | 'partial' | 'manual'; - file: string; - - // Existing rich metadata - steps?: string[]; - automatable?: string[]; - notYet?: string[]; - dependencies?: Array<{ label: string; value: string }>; - - // New fields for code generation - fullyAutomated?: boolean; - codeSteps?: CodeStep[]; - implementationNotes?: string; - verifiedSnippets?: VerifiedSnippet[]; -} - -/** - * Type used when the generator receives data (after merging). - */ -export type TestForCodeGeneration = EnrichedTestForGeneration; diff --git a/editor/tasks/automated-code-generation.md b/editor/tasks/automated-code-generation.md deleted file mode 100644 index cc29026..0000000 --- a/editor/tasks/automated-code-generation.md +++ /dev/null @@ -1,240 +0,0 @@ -# Automated Test Code Generation - Progress Tracker - -**Project Goal**: Turn the Autotest Web Editor into the central "director" that can generate real, executable Playwright + MCP test files for all tests marked as fully automated. - -**Current Decisions (Locked)**: -- Output folder: `tests/generated/{core,pbx}/` -- File naming: Same names as existing tests (e.g. `documentation.spec.ts`) -- Generation style: Template-based + LLM under the hood -- Granularity: One spec file per group -- First target group: `core-documentation` -- Human must always review & commit -- LLM context: Full group + focus on current test -- Update `testInfo.annotations` in generated files - -**Status**: Active development — generator functional, first real code being produced (2026-05-22) - ---- - -## Phases & Tasks - -### Phase 0: Setup & Foundations - -- [x] Create `editor/tasks/automated-code-generation.md` (this file) -- [x] Create folder `tests/generated/core/` and `tests/generated/pbx/` -- [ ] Decide on generator script location (`editor/scripts/generate-playwright-tests.ts`) -- [ ] Add `ts-node` or proper TypeScript execution if needed for scripts -- [x] Create basic `ActionCatalog` types in `editor/scripts/types/automated-generation.ts` -- [x] Create initial Action Catalog structure (`editor/scripts/action-catalog/`) - -**Status**: Mostly done (script runner decision pending) - ---- - -### Phase 1: Data Model Extensions - -- [ ] Add new fields to the internal test model: - - `fullyAutomated?: boolean` - - `codeSteps?: Array<{ stepName: string, actionKey: string, params?: any }>` - - `implementationNotes?: string` - - `verifiedSnippets?: Array<{ stepName: string, code: string }>` -- [ ] Update `editor/data/testcases.json` schema (or handle missing fields gracefully) -- [x] Add UI section in the test modal for editing these new fields (basic codeSteps + params supported) -- [x] Add a filter "Only Fully Automated" in the main table / selection toolbar (selection works, visual row filter pending) - -**Owner**: Frontend + Data -**Priority**: High - ---- - -### Phase 2: Action Catalog - -- [x] Design `action-catalog.json` structure -- [x] Create folder `editor/scripts/action-catalog/` -- [x] Implement TypeScript loader (`loadActionCatalog()`) -- [x] Add first batch of entries for `core-documentation` group -- [x] Support parameter substitution (e.g. `{{pattern}}`) - -**Owner**: Backend / Scripts -**Priority**: High -**Status**: Foundation done, content population in progress - ---- - -### Phase 3: Core Code Generator - -- [x] Create generator script (now `.js`) -- [x] Support filtering by `status === "automated"` + `fullyAutomated` -- [x] Group tests by their `group` field -- [x] Generate one `.spec.ts` file per group in `tests/generated/` -- [x] Render `test.step()` blocks using the Action Catalog -- [x] Emit standard header + `testInfo.annotations` -- [x] Add basic CLI interface (`--group`, `--dry-run`) - -**Priority**: High - ---- - -### Phase 4: First Real Generation (core-documentation) - -- [x] Populate enough catalog entries to generate `documentation.spec.ts` (2/4 tests done) -- [x] Run generator against `core-documentation` tests (dry-run verified, real write via UI works) -- [ ] Manually review the output -- [ ] Iterate on templates until the generated file is acceptable -- [ ] Commit first generated file (after review) - -**Milestone**: First generated spec file - ---- - -### Phase 5: Editor Integration - -- [x] Add new button: **"Export Automated Playwright Tests"** -- [x] Add backend endpoint `POST /api/export/automated-tests` -- [x] Support real generation (writes files when called from UI) -- [ ] Add confirmation modal showing which groups will be generated -- [ ] Show link to the generated files after success - -**Priority**: Medium - ---- - -### Phase 6: LLM / MCP Assistance (Under the Hood) - -- [ ] Create helper to build rich context (full group + current test + catalog + examples) -- [ ] Integrate LLM call (via MCP or direct client) -- [ ] Add fallback: when no catalog match → ask LLM -- [ ] Store accepted LLM suggestions back into `verifiedSnippets` or catalog (optional learning loop) - -**Priority**: Medium - ---- - -### Phase 7: Regeneration & Safety - -- [ ] Define regeneration markers in generated files -- [ ] Implement update logic (preserve manual code above marker) -- [ ] Add `--force` and `--update-only` flags to the generator -- [ ] Document the regeneration contract - ---- - -### Phase 8: Polish & Documentation - -- [ ] Improve error messages and validation in generator -- [ ] Add tests for the generator (at least for `core-documentation`) -- [ ] Write `editor/docs/automated-code-generation.md` -- [ ] Update main `README.md` with new workflow -- [ ] Add "Fully Automated" badge/filter in the web editor - ---- - -## Current Status - -| Phase | Status | Notes | -|-------|--------------|------------------------------------| -| 0 | In Progress | Tracking file created | -| 1 | Not Started | Data model changes needed | -| 2 | Not Started | Action Catalog design pending | -| 3 | Not Started | Core generator not written yet | -| 4 | Not Started | First real generation | -| 5 | Not Started | Editor button not implemented | -| 6 | Not Started | LLM integration later | -| 7 | Not Started | Regeneration strategy | -| 8 | Not Started | Documentation | - -**Next Immediate Task**: Continue Phase 4 — enrich remaining core-documentation tests and improve catalog actions. - ---- - -## Notes & Decisions Log - -- 2026-05-22: Confirmed output goes to `tests/generated/` -- 2026-05-22: First target group = `core-documentation` -- 2026-05-22: Template-based + LLM under the hood -- 2026-05-22: Human review & commit required - ---- - -**Current Status (Updated 2026-05-22 evening)** - -| Phase | Status | Notes | -|-------|-----------------|-----------------------------------------------------------------------| -| 0 | Done | Tracking file + folders + basic types + JS generator created | -| 1 | In Progress | `fullyAutomated`, `implementationNotes`, `codeSteps` + params editor added. Two tests enriched. | -| 2 | In Progress | Catalog + loader done. Good entries for core-documentation + substitution working. | -| 3 | In Progress | Generator fully working in JS, supports group + real file writing via UI. | -| 4 | In Progress | 2 out of 4 core-documentation tests now generate real code. | -| 5 | Done | Export button + backend fully wired and functional. | -| 6 | Not Started | LLM/MCP fallback layer | -| 7 | Not Started | Regeneration safety markers | -| 8 | Not Started | Documentation & polish | - -**Next Immediate Recommended Task**: Enrich remaining core-documentation tests and expand Action Catalog for a complete group generation. - ---- - -**Last Updated**: 2026-05-22 (evening session) - ---- - -## Session Summary (2026-05-22) - -**Work completed in this session:** -- Added `fullyAutomated` checkbox + `implementationNotes` + basic `codeSteps` editor in the modal (Phase 1) -- Added "Only Fully Automated" bulk selection button (B) -- Created Action Catalog foundation + first entries for `core-documentation` (C) -- Created `generate-playwright-tests.ts` script (Phase 3 start) -- Added "Export Automated Tests" button in the UI + backend endpoint -- Updated progress tracker - -**Current blockers / next work:** -- Generator currently only does dry-run. Needs to actually write files. -- Need to test generation for `core-documentation` group. -- `codeSteps` editor is still basic (can be improved). -**Current Focus**: Setting up the task tracker and preparing Phase 1 - ---- - -## Session Summary (2026-05-22 - Evening continuation) - -**Work completed in this session:** -- Converted generator to plain JavaScript (`generate-playwright-tests.js`) + catalog loader for reliable execution without ts-node. -- Fixed `require` paths and made the generator fully functional. -- Improved `codeSteps` editor in the modal to support `params` (JSON input). -- Wired the "Export Automated Tests" button + backend to actually call the generator with `--group`. -- Enriched the first two `core-documentation` tests with real `fullyAutomated: true`, `implementationNotes`, and detailed `codeSteps` + params. -- Verified via `--dry-run` that the generator now produces clean, executable Playwright code with proper parameter substitution (e.g. `release-notes`, `cli-configuration`). -- Two tests in `core-documentation` now generate real steps instead of placeholders. - -**Updated Status Table** (see below) - -**Current blockers / open items:** -- Remaining two `core-documentation` tests still lack `codeSteps`. -- Action Catalog entries are still basic (many actions just do visibility checks). -- No regeneration marker / preserve-manual-sections logic yet. -- No visual row filter for "Only Fully Automated" (selection works, but table rows still show everything). - -**Recommended next steps for tomorrow:** -1. Enrich the other two `core-documentation` tests (`check-accuracy_installation...` and `check-accuracy_trouble_shooting...`) with proper `codeSteps`. -2. Expand the Action Catalog with more realistic actions (file extraction, text parsing, writing outputs, etc.). -3. Test a real (non-dry-run) generation via the UI button and review the file in `tests/generated/core/documentation.spec.ts`. -4. (Optional) Add a proper "Only Fully Automated" visual filter to hide non-automated rows in the table. - ---- - -## Current Status (Updated 2026-05-22 evening) - -| Phase | Status | Notes | -|-------|-----------------|-----------------------------------------------------------------------| -| 0 | Done | Tracking file + folders + basic types + JS generator created | -| 1 | In Progress | `fullyAutomated`, `implementationNotes`, `codeSteps` + params editor added. Two tests enriched. Filter button exists. | -| 2 | In Progress | Catalog + loader done. Initial useful entries for core-documentation added. Substitution works. | -| 3 | In Progress | Generator fully working (JS), supports `--group` + `--dry-run`, writes real files when called from UI. | -| 4 | In Progress | First real generation for `core-documentation` partially done (2/4 tests enriched and generating cleanly). | -| 5 | Done | "Export Automated Tests" button + backend endpoint implemented and tested. | -| 6 | Not Started | LLM/MCP fallback layer | -| 7 | Not Started | Regeneration safety markers + preserve manual code | -| 8 | Not Started | Documentation & polish | - -**Next Immediate Recommended Task (for tomorrow)**: Finish enriching all 4 tests in `core-documentation` and expand the Action Catalog so a complete, high-quality group can be generated. diff --git a/karpathy.md b/karpathy.md new file mode 100644 index 0000000..05ddc06 --- /dev/null +++ b/karpathy.md @@ -0,0 +1,59 @@ +Behavioral guidelines to reduce common LLM coding mistakes. Merge with project-specific instructions as needed. + +**Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment. + +## 1. Think Before Coding + +**Don't assume. Don't hide confusion. Surface tradeoffs.** + +Before implementing: +- State your assumptions explicitly. If uncertain, ask. +- If multiple interpretations exist, present them - don't pick silently. +- If a simpler approach exists, say so. Push back when warranted. +- If something is unclear, stop. Name what's confusing. Ask. + +## 2. Simplicity First + +**Minimum code that solves the problem. Nothing speculative.** + +- No features beyond what was asked. +- No abstractions for single-use code. +- No "flexibility" or "configurability" that wasn't requested. +- No error handling for impossible scenarios. +- If you write 200 lines and it could be 50, rewrite it. + +Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify. + +## 3. Surgical Changes + +**Touch only what you must. Clean up only your own mess.** + +When editing existing code: +- Don't "improve" adjacent code, comments, or formatting. +- Don't refactor things that aren't broken. +- Match existing style, even if you'd do it differently. +- If you notice unrelated dead code, mention it - don't delete it. + +When your changes create orphans: +- Remove imports/variables/functions that YOUR changes made unused. +- Don't remove pre-existing dead code unless asked. + +The test: Every changed line should trace directly to the user's request. + +## 4. Goal-Driven Execution + +**Define success criteria. Loop until verified.** + +Transform tasks into verifiable goals: +- "Add validation" → "Write tests for invalid inputs, then make them pass" +- "Fix the bug" → "Write a test that reproduces it, then make it pass" +- "Refactor X" → "Ensure tests pass before and after" + +For multi-step tasks, state a brief plan: +``` +1. [Step] → verify: [check] +2. [Step] → verify: [check] +3. [Step] → verify: [check] +``` + +Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification. diff --git a/editor/data/testcases.json b/legacy/data/testcases.json similarity index 97% rename from editor/data/testcases.json rename to legacy/data/testcases.json index 6d81558..475279e 100644 --- a/editor/data/testcases.json +++ b/legacy/data/testcases.json @@ -1,12 +1,102 @@ [ { - "id": "core-repository-check-presence_of_release_notes_and_changelog", - "group": "core-repository", + "id": "core-documentation-check-accuracy_installation_and_configuration_guide", + "group": "core-documentation", "module": "core", "action": "check", - "description": "Verify Release Notes and Changelog are present in the software repository", + "description": "Verify accuracy of the Installation and Configuration Guide against actual system behaviour", + "status": "manual", + "file": "tests/core/documentation.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Navigate to the download / documentation portal", + "Search or locate the relevant file/link by filename pattern", + "Assert presence and visibility of the expected document" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires expert human review: QA engineer must follow the guide step-by-step on a clean system", + "Requires external SIP endpoints or physical phones for media/audio validation" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires expert human review: QA engineer must follow the guide step-by-step on a clean system" + }, + { + "id": "core-documentation-check-accuracy_trouble_shooting_guide", + "group": "core-documentation", + "module": "core", + "action": "check", + "description": "Verify the Troubleshooting Guide procedures are accurate and complete", + "status": "manual", + "file": "tests/core/documentation.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Navigate to the download / documentation portal", + "Search or locate the relevant file/link by filename pattern", + "Assert presence and visibility of the expected document" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires expert human review to validate each troubleshooting scenario on a real system", + "Requires external SIP endpoints or physical phones for media/audio validation" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires expert human review to validate each troubleshooting scenario on a real system" + }, + { + "id": "core-documentation-write-changed_cli_configuration_commands", + "group": "core-documentation", + "module": "core", + "action": "write", + "description": "Extract and record changed CLI configuration commands for this release", "status": "automated", - "file": "tests/core/repository.spec.ts", + "file": "tests/core/documentation.spec.ts", "steps": [ "Open admin portal or repository URL in browser context", "Navigate to the download / documentation portal", @@ -42,13 +132,13 @@ ] }, { - "id": "core-repository-check-presence_of_trouble_shooting_guide", - "group": "core-repository", + "id": "core-documentation-write-release_notes_feature_changes_and_known_issues", + "group": "core-documentation", "module": "core", - "action": "check", - "description": "Verify Troubleshooting Guide is present in the repository", + "action": "write", + "description": "Extract and record Release Notes, feature changes, and known issues", "status": "automated", - "file": "tests/core/repository.spec.ts", + "file": "tests/core/documentation.spec.ts", "steps": [ "Open admin portal or repository URL in browser context", "Navigate to the download / documentation portal", @@ -83,6 +173,581 @@ } ] }, + { + "id": "core-features-check-backward_compatibility_of_new_features", + "group": "core-features", + "module": "core", + "action": "check", + "description": "Verify new features are backward-compatible with existing configurations and older endpoint firmware", + "status": "partial", + "file": "tests/core/features.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Portal UI configuration and verification steps (already partially automated)", + "Data extraction and reporting of current settings" + ], + "notYet": [ + "Configuration import checks automated; functional compatibility with older endpoints requires manual testing", + "Requires external SIP endpoints or physical phones for media/audio validation" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "partialNotes": "Configuration import checks automated; functional compatibility with older endpoints requires manual testing" + }, + { + "id": "core-features-check-integration_of_new_features_with_existing_call_processing_and_modules", + "group": "core-features", + "module": "core", + "action": "check", + "description": "Verify new features integrate correctly with existing call processing and system modules", + "status": "partial", + "file": "tests/core/features.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Portal UI configuration and verification steps (already partially automated)", + "Data extraction and reporting of current settings" + ], + "notYet": [ + "UI config checks automated; actual call-flow integration requires active telephony endpoints", + "Requires external SIP endpoints or physical phones for media/audio validation" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "partialNotes": "UI config checks automated; actual call-flow integration requires active telephony endpoints" + }, + { + "id": "core-features-check-performance_and_resource_impact_assessment_of_new_features", + "group": "core-features", + "module": "core", + "action": "check", + "description": "Assess CPU/memory/network resource impact of new features under representative call load", + "status": "manual", + "file": "tests/core/features.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires SIPp load generator, performance monitoring infrastructure, and sustained load testing", + "Requires external SIP endpoints or physical phones for media/audio validation" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires SIPp load generator, performance monitoring infrastructure, and sustained load testing" + }, + { + "id": "core-features-check-provisioning_changes_for_new_features", + "group": "core-features", + "module": "core", + "action": "check", + "description": "Verify provisioning settings for new features are accessible in the admin portal", + "status": "automated", + "file": "tests/core/features.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Full end-to-end execution via Playwright against the admin portal UI", + "Navigation, form interaction, and assertions are scriptable" + ], + "notYet": [], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ] + }, + { + "id": "core-features-write-analysis_of_new_security_risks", + "group": "core-features", + "module": "core", + "action": "write", + "description": "Identify, analyse, and document new security risks introduced by features in this release", + "status": "manual", + "file": "tests/core/features.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Security risk analysis requires expert threat modelling, source code review, and human judgment", + "Requires external SIP endpoints or physical phones for media/audio validation" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Security risk analysis requires expert threat modelling, source code review, and human judgment" + }, + { + "id": "core-features-write-summary_of_each_new_feature_per_release", + "group": "core-features", + "module": "core", + "action": "write", + "description": "Extract and record a summary of each new feature included in this release", + "status": "automated", + "file": "tests/core/features.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Full end-to-end execution via Playwright against the admin portal UI", + "Navigation, form interaction, and assertions are scriptable" + ], + "notYet": [], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ] + }, + { + "id": "core-features-write-ui_ux_and_admin_portal_changes_validation", + "group": "core-features", + "module": "core", + "action": "write", + "description": "Capture and record all UI/UX changes in the admin portal for this release", + "status": "automated", + "file": "tests/core/features.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Full end-to-end execution via Playwright against the admin portal UI", + "Navigation, form interaction, and assertions are scriptable" + ], + "notYet": [], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ] + }, + { + "id": "core-installation-check-fresh_installation", + "group": "core-installation", + "module": "core", + "action": "check", + "description": "Verify complete fresh installation from scratch succeeds on each supported hypervisor", + "status": "manual", + "file": "tests/core/installation.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Prepare clean or previous-version VM/image", + "Perform installation or upgrade procedure", + "Post-install verification via portal + external tools" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires provisioning a clean VM, mounting ISO/OVA, and running the installation wizard", + "Requires external SIP endpoints or physical phones for media/audio validation" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires provisioning a clean VM, mounting ISO/OVA, and running the installation wizard" + }, + { + "id": "core-installation-check-initial_configuration", + "group": "core-installation", + "module": "core", + "action": "check", + "description": "Verify the initial configuration wizard completes successfully", + "status": "automated", + "file": "tests/core/installation.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Prepare clean or previous-version VM/image", + "Perform installation or upgrade procedure", + "Post-install verification via portal + external tools" + ], + "automatable": [ + "Full end-to-end execution via Playwright against the admin portal UI", + "Navigation, form interaction, and assertions are scriptable" + ], + "notYet": [], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ] + }, + { + "id": "core-installation-check-license_activation", + "group": "core-installation", + "module": "core", + "action": "check", + "description": "Verify license activation completes successfully and licensed features are unlocked", + "status": "automated", + "file": "tests/core/installation.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Prepare clean or previous-version VM/image", + "Perform installation or upgrade procedure", + "Post-install verification via portal + external tools" + ], + "automatable": [ + "Full end-to-end execution via Playwright against the admin portal UI", + "Navigation, form interaction, and assertions are scriptable" + ], + "notYet": [], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ] + }, + { + "id": "core-installation-check-post_install_service_status_and_port_verification", + "group": "core-installation", + "module": "core", + "action": "check", + "description": "Verify all required services are running and expected ports are open after installation", + "status": "partial", + "file": "tests/core/installation.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Prepare clean or previous-version VM/image", + "Perform installation or upgrade procedure", + "Post-install verification via portal + external tools" + ], + "automatable": [ + "Portal UI configuration and verification steps (already partially automated)", + "Data extraction and reporting of current settings" + ], + "notYet": [ + "Service status via admin portal automated; TCP port verification requires nmap from external host", + "Requires external SIP endpoints or physical phones for media/audio validation" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "partialNotes": "Service status via admin portal automated; TCP port verification requires nmap from external host" + }, + { + "id": "core-interoperability-check-addm", + "group": "core-interoperability", + "module": "core", + "action": "check", + "description": "Verify ADDM integration is configured and reporting discovery data correctly", + "status": "automated", + "file": "tests/core/interoperability.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Full end-to-end execution via Playwright against the admin portal UI", + "Navigation, form interaction, and assertions are scriptable" + ], + "notYet": [], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "External Systems", + "value": "SIEM server (Splunk, ELK, QRadar) and/or ADDM/ADDM collector" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ] + }, + { + "id": "core-interoperability-check-siem", + "group": "core-interoperability", + "module": "core", + "action": "check", + "description": "Verify SIEM integration is configured and forwarding security events", + "status": "automated", + "file": "tests/core/interoperability.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Full end-to-end execution via Playwright against the admin portal UI", + "Navigation, form interaction, and assertions are scriptable" + ], + "notYet": [], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "External Systems", + "value": "SIEM server (Splunk, ELK, QRadar) and/or ADDM/ADDM collector" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ] + }, { "id": "core-repository-check-presence_of_all_mandatory_core-documentation_files", "group": "core-repository", @@ -125,6 +790,48 @@ } ] }, + { + "id": "core-repository-check-presence_of_companion_tools_and_supporting_scripts", + "group": "core-repository", + "module": "core", + "action": "check", + "description": "Verify companion tools and supporting scripts are available in the repository", + "status": "automated", + "file": "tests/core/repository.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Navigate to the download / documentation portal", + "Search or locate the relevant file/link by filename pattern", + "Assert presence and visibility of the expected document" + ], + "automatable": [ + "Full end-to-end execution via Playwright against the admin portal UI", + "Navigation, form interaction, and assertions are scriptable" + ], + "notYet": [], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ] + }, { "id": "core-repository-check-presence_of_main_software_version_all_hypervisors", "group": "core-repository", @@ -210,11 +917,11 @@ ] }, { - "id": "core-repository-check-presence_of_companion_tools_and_supporting_scripts", + "id": "core-repository-check-presence_of_release_notes_and_changelog", "group": "core-repository", "module": "core", "action": "check", - "description": "Verify companion tools and supporting scripts are available in the repository", + "description": "FASE1-TEST-1779730773816", "status": "automated", "file": "tests/core/repository.spec.ts", "steps": [ @@ -252,13 +959,13 @@ ] }, { - "id": "core-documentation-write-release_notes_feature_changes_and_known_issues", - "group": "core-documentation", + "id": "core-repository-check-presence_of_trouble_shooting_guide", + "group": "core-repository", "module": "core", - "action": "write", - "description": "Extract and record Release Notes, feature changes, and known issues", + "action": "check", + "description": "Verify Troubleshooting Guide is present in the repository", "status": "automated", - "file": "tests/core/documentation.spec.ts", + "file": "tests/core/repository.spec.ts", "steps": [ "Open admin portal or repository URL in browser context", "Navigate to the download / documentation portal", @@ -291,909 +998,281 @@ "label": "Test Data", "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" } - ], - "fullyAutomated": true, - "implementationNotes": "Use Playwright to navigate the admin portal downloads section and locate release notes documents. Extract text and write to a local file.", - "codeSteps": [ - { - "stepName": "Open admin portal or repository URL in browser context", - "actionKey": "open_admin_portal", - "params": {} - }, - { - "stepName": "Navigate to the download / documentation portal", - "actionKey": "navigate_to_downloads_portal", - "params": {} - }, - { - "stepName": "Search or locate the relevant file/link by filename pattern", - "actionKey": "search_for_document", - "params": { "pattern": "release-notes" } - }, - { - "stepName": "Assert presence and visibility of the expected document", - "actionKey": "assert_document_visible", - "params": { "pattern": "release-notes" } - } ] }, { - "id": "core-documentation-check-accuracy_installation_and_configuration_guide", - "group": "core-documentation", - "module": "core", - "action": "check", - "description": "Verify accuracy of the Installation and Configuration Guide against actual system behaviour", - "status": "manual", - "file": "tests/core/documentation.spec.ts", - "manualReason": "Requires expert human review: QA engineer must follow the guide step-by-step on a clean system", - "steps": [ - "Open admin portal or repository URL in browser context", - "Navigate to the download / documentation portal", - "Search or locate the relevant file/link by filename pattern", - "Assert presence and visibility of the expected document" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires expert human review: QA engineer must follow the guide step-by-step on a clean system", - "Requires external SIP endpoints or physical phones for media/audio validation" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-documentation-check-accuracy_trouble_shooting_guide", - "group": "core-documentation", - "module": "core", - "action": "check", - "description": "Verify the Troubleshooting Guide procedures are accurate and complete", - "status": "manual", - "file": "tests/core/documentation.spec.ts", - "manualReason": "Requires expert human review to validate each troubleshooting scenario on a real system", - "steps": [ - "Open admin portal or repository URL in browser context", - "Navigate to the download / documentation portal", - "Search or locate the relevant file/link by filename pattern", - "Assert presence and visibility of the expected document" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires expert human review to validate each troubleshooting scenario on a real system", - "Requires external SIP endpoints or physical phones for media/audio validation" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-documentation-write-changed_cli_configuration_commands", - "group": "core-documentation", - "module": "core", - "action": "write", - "description": "Extract and record changed CLI configuration commands for this release", - "status": "automated", - "file": "tests/core/documentation.spec.ts", - "steps": [ - "Open admin portal or repository URL in browser context", - "Navigate to the download / documentation portal", - "Search or locate the relevant file/link by filename pattern", - "Assert presence and visibility of the expected document" - ], - "automatable": [ - "Full end-to-end execution via Playwright against the admin portal UI", - "Navigation, form interaction, and assertions are scriptable" - ], - "notYet": [], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ], - "fullyAutomated": true, - "implementationNotes": "Similar to release notes extraction but targets CLI command changes in the documentation.", - "codeSteps": [ - { - "stepName": "Open admin portal or repository URL in browser context", - "actionKey": "open_admin_portal", - "params": {} - }, - { - "stepName": "Navigate to the download / documentation portal", - "actionKey": "navigate_to_downloads_portal", - "params": {} - }, - { - "stepName": "Search or locate the relevant file/link by filename pattern", - "actionKey": "search_for_document", - "params": { "pattern": "cli-configuration" } - }, - { - "stepName": "Assert presence and visibility of the expected document", - "actionKey": "assert_document_visible", - "params": { "pattern": "cli-configuration" } - } - ] - }, - { - "id": "core-features-write-summary_of_each_new_feature_per_release", - "group": "core-features", - "module": "core", - "action": "write", - "description": "Extract and record a summary of each new feature included in this release", - "status": "automated", - "file": "tests/core/features.spec.ts", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Full end-to-end execution via Playwright against the admin portal UI", - "Navigation, form interaction, and assertions are scriptable" - ], - "notYet": [], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-features-check-integration_of_new_features_with_existing_call_processing_and_modules", - "group": "core-features", - "module": "core", - "action": "check", - "description": "Verify new features integrate correctly with existing call processing and system modules", - "status": "partial", - "file": "tests/core/features.spec.ts", - "partialNotes": "UI config checks automated; actual call-flow integration requires active telephony endpoints", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Portal UI configuration and verification steps (already partially automated)", - "Data extraction and reporting of current settings" - ], - "notYet": [ - "UI config checks automated; actual call-flow integration requires active telephony endpoints", - "Requires external SIP endpoints or physical phones for media/audio validation" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-features-check-backward_compatibility_of_new_features", - "group": "core-features", - "module": "core", - "action": "check", - "description": "Verify new features are backward-compatible with existing configurations and older endpoint firmware", - "status": "partial", - "file": "tests/core/features.spec.ts", - "partialNotes": "Configuration import checks automated; functional compatibility with older endpoints requires manual testing", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Portal UI configuration and verification steps (already partially automated)", - "Data extraction and reporting of current settings" - ], - "notYet": [ - "Configuration import checks automated; functional compatibility with older endpoints requires manual testing", - "Requires external SIP endpoints or physical phones for media/audio validation" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-features-check-performance_and_resource_impact_assessment_of_new_features", - "group": "core-features", - "module": "core", - "action": "check", - "description": "Assess CPU/memory/network resource impact of new features under representative call load", - "status": "manual", - "file": "tests/core/features.spec.ts", - "manualReason": "Requires SIPp load generator, performance monitoring infrastructure, and sustained load testing", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires SIPp load generator, performance monitoring infrastructure, and sustained load testing", - "Requires external SIP endpoints or physical phones for media/audio validation" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-features-write-analysis_of_new_security_risks", - "group": "core-features", - "module": "core", - "action": "write", - "description": "Identify, analyse, and document new security risks introduced by features in this release", - "status": "manual", - "file": "tests/core/features.spec.ts", - "manualReason": "Security risk analysis requires expert threat modelling, source code review, and human judgment", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Security risk analysis requires expert threat modelling, source code review, and human judgment", - "Requires external SIP endpoints or physical phones for media/audio validation" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-features-write-ui_ux_and_admin_portal_changes_validation", - "group": "core-features", - "module": "core", - "action": "write", - "description": "Capture and record all UI/UX changes in the admin portal for this release", - "status": "automated", - "file": "tests/core/features.spec.ts", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Full end-to-end execution via Playwright against the admin portal UI", - "Navigation, form interaction, and assertions are scriptable" - ], - "notYet": [], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-features-check-provisioning_changes_for_new_features", - "group": "core-features", - "module": "core", - "action": "check", - "description": "Verify provisioning settings for new features are accessible in the admin portal", - "status": "automated", - "file": "tests/core/features.spec.ts", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Full end-to-end execution via Playwright against the admin portal UI", - "Navigation, form interaction, and assertions are scriptable" - ], - "notYet": [], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-virtualization-write-supported_hypervisors_deployment", - "group": "core-virtualization", - "module": "core", - "action": "write", - "description": "Record the list of supported hypervisors and deployment methods from the download portal", - "status": "automated", - "file": "tests/core/virtualization.spec.ts", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Full end-to-end execution via Playwright against the admin portal UI", - "Navigation, form interaction, and assertions are scriptable" - ], - "notYet": [ - "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", - "Long-running load or HA failover scenarios need dedicated lab infrastructure" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Hypervisor Access", - "value": "vCenter, Hyper-V Manager, Proxmox, or virsh (SSH/API)" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-virtualization-write-guest_agent_integration", - "group": "core-virtualization", - "module": "core", - "action": "write", - "description": "Record guest agent integration status for each supported hypervisor", - "status": "manual", - "file": "tests/core/virtualization.spec.ts", - "manualReason": "Requires direct access to hypervisor console (vCenter, Hyper-V Manager, virsh)", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires direct access to hypervisor console (vCenter, Hyper-V Manager, virsh)", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", - "Long-running load or HA failover scenarios need dedicated lab infrastructure" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Hypervisor Access", - "value": "vCenter, Hyper-V Manager, Proxmox, or virsh (SSH/API)" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-virtualization-write-resource_allocation_vcpu_vram_vdisk", - "group": "core-virtualization", - "module": "core", - "action": "write", - "description": "Record vCPU, vRAM, and vDisk resource allocation for deployment templates", - "status": "manual", - "file": "tests/core/virtualization.spec.ts", - "manualReason": "Hypervisor management plane access required; not exposed in PBX admin portal", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Hypervisor management plane access required; not exposed in PBX admin portal", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", - "Long-running load or HA failover scenarios need dedicated lab infrastructure" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Hypervisor Access", - "value": "vCenter, Hyper-V Manager, Proxmox, or virsh (SSH/API)" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-virtualization-write-virtual_networking_configuration", - "group": "core-virtualization", - "module": "core", - "action": "write", - "description": "Record virtual networking configuration: virtual switches, VLANs, NIC assignments", - "status": "manual", - "file": "tests/core/virtualization.spec.ts", - "manualReason": "Requires access to hypervisor networking configuration and virtual switch management", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires access to hypervisor networking configuration and virtual switch management", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", - "Long-running load or HA failover scenarios need dedicated lab infrastructure" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Hypervisor Access", - "value": "vCenter, Hyper-V Manager, Proxmox, or virsh (SSH/API)" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-virtualization-check-live_migration_and_active_call_preservation", - "group": "core-virtualization", - "module": "core", - "action": "check", - "description": "Verify VM live migration preserves active calls without interruption", - "status": "manual", - "file": "tests/core/virtualization.spec.ts", - "manualReason": "Requires HA infrastructure with 2+ hypervisor hosts and active SIP call sessions during migration", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires HA infrastructure with 2+ hypervisor hosts and active SIP call sessions during migration", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", - "Long-running load or HA failover scenarios need dedicated lab infrastructure" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Hypervisor Access", - "value": "vCenter, Hyper-V Manager, Proxmox, or virsh (SSH/API)" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-virtualization-check-snapshot_backup_restore_and_consistency", - "group": "core-virtualization", - "module": "core", - "action": "check", - "description": "Verify VM snapshot and restore operations maintain full system consistency", - "status": "partial", - "file": "tests/core/virtualization.spec.ts", - "partialNotes": "Post-restore consistency checks via admin portal automated; snapshot/restore operation needs hypervisor access", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Portal UI configuration and verification steps (already partially automated)", - "Data extraction and reporting of current settings" - ], - "notYet": [ - "Post-restore consistency checks via admin portal automated; snapshot/restore operation needs hypervisor access", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", - "Long-running load or HA failover scenarios need dedicated lab infrastructure" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Hypervisor Access", - "value": "vCenter, Hyper-V Manager, Proxmox, or virsh (SSH/API)" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-virtualization-check-hypervisor_level_high_availability", - "group": "core-virtualization", - "module": "core", - "action": "check", - "description": "Verify hypervisor-level HA restarts the PBX VM after a host failure", - "status": "manual", - "file": "tests/core/virtualization.spec.ts", - "manualReason": "Requires physical HA cluster with multiple hypervisor hosts; host failure must be simulated", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires physical HA cluster with multiple hypervisor hosts; host failure must be simulated", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", - "Long-running load or HA failover scenarios need dedicated lab infrastructure" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Hypervisor Access", - "value": "vCenter, Hyper-V Manager, Proxmox, or virsh (SSH/API)" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-virtualization-write-storage_thin_vs_thick_provisioning", - "group": "core-virtualization", - "module": "core", - "action": "write", - "description": "Record storage provisioning type and performance implications for each hypervisor", - "status": "manual", - "file": "tests/core/virtualization.spec.ts", - "manualReason": "Storage details only visible in hypervisor storage management interface", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Storage details only visible in hypervisor storage management interface", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", - "Long-running load or HA failover scenarios need dedicated lab infrastructure" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Hypervisor Access", - "value": "vCenter, Hyper-V Manager, Proxmox, or virsh (SSH/API)" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-security-write-strong_password_policy", + "id": "core-security-check-auto_enrollment_certificate_management_process", "group": "core-security", "module": "core", - "action": "write", - "description": "Navigate to security settings and record the current password policy configuration", + "action": "check", + "description": "Verify auto-enrollment certificate management (ACME/Let's Encrypt) is configured and functional", + "status": "automated", + "file": "tests/core/security.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Log in to the admin portal (if required)", + "Navigate to the relevant settings section", + "Read current configuration values via UI or API" + ], + "automatable": [ + "Full end-to-end execution via Playwright against the admin portal UI", + "Navigation, form interaction, and assertions are scriptable" + ], + "notYet": [], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ] + }, + { + "id": "core-security-check-encryption_of_sensitive_data_at_rest_and_in_transit", + "group": "core-security", + "module": "core", + "action": "check", + "description": "Verify sensitive data is encrypted at rest (DB) and in transit (HTTPS/TLS)", + "status": "partial", + "file": "tests/core/security.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Log in to the admin portal (if required)", + "Navigate to the relevant settings section", + "Read current configuration values via UI or API" + ], + "automatable": [ + "Portal UI configuration and verification steps (already partially automated)", + "Data extraction and reporting of current settings" + ], + "notYet": [ + "HTTPS/TLS configuration verified via portal; DB-level at-rest encryption requires SSH/CLI access", + "Requires external SIP endpoints or physical phones for media/audio validation" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "partialNotes": "HTTPS/TLS configuration verified via portal; DB-level at-rest encryption requires SSH/CLI access" + }, + { + "id": "core-security-check-ip_access_control_lists", + "group": "core-security", + "module": "core", + "action": "check", + "description": "Verify IP Access Control Lists are properly configured and enforced", + "status": "automated", + "file": "tests/core/security.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Log in to the admin portal (if required)", + "Navigate to the relevant settings section", + "Read current configuration values via UI or API" + ], + "automatable": [ + "Full end-to-end execution via Playwright against the admin portal UI", + "Navigation, form interaction, and assertions are scriptable" + ], + "notYet": [], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ] + }, + { + "id": "core-security-check-known_vulnerable_dependencies_in_release_artifacts", + "group": "core-security", + "module": "core", + "action": "check", + "description": "Verify release artifacts do not contain known vulnerable dependencies (CVE scan)", + "status": "partial", + "file": "tests/core/security.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Log in to the admin portal (if required)", + "Navigate to the relevant settings section", + "Read current configuration values via UI or API" + ], + "automatable": [ + "Portal UI configuration and verification steps (already partially automated)", + "Data extraction and reporting of current settings" + ], + "notYet": [ + "Vulnerability report page in portal automated; actual CVE scanning requires Trivy/OWASP-DC in CI", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Full CVE / dependency scanning (Trivy, Grype, OWASP Dependency-Check) in CI pipeline" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "partialNotes": "Vulnerability report page in portal automated; actual CVE scanning requires Trivy/OWASP-DC in CI" + }, + { + "id": "core-security-check-obtain_formal_security_team_sign_off_for_the_new_version", + "group": "core-security", + "module": "core", + "action": "check", + "description": "Obtain formal written sign-off from the Security team approving the release", + "status": "manual", + "file": "tests/core/security.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Log in to the admin portal (if required)", + "Navigate to the relevant settings section", + "Read current configuration values via UI or API" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Governance gate requiring human decision and formal sign-off document; cannot be automated", + "Requires external SIP endpoints or physical phones for media/audio validation" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Governance gate requiring human decision and formal sign-off document; cannot be automated" + }, + { + "id": "core-security-check-previous_security_findings_have_been_remediated_before_release", + "group": "core-security", + "module": "core", + "action": "check", + "description": "Verify all previously identified security findings are remediated before release", + "status": "manual", + "file": "tests/core/security.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Log in to the admin portal (if required)", + "Navigate to the relevant settings section", + "Read current configuration values via UI or API" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires access to security issue tracker and cross-referencing CVEs with the release changelog", + "Requires external SIP endpoints or physical phones for media/audio validation" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires access to security issue tracker and cross-referencing CVEs with the release changelog" + }, + { + "id": "core-security-check-security_event_logging_and_audit_trail_is_active", + "group": "core-security", + "module": "core", + "action": "check", + "description": "Verify security event logging and audit trail are active and recording events", "status": "automated", "file": "tests/core/security.spec.ts", "steps": [ @@ -1272,48 +1351,6 @@ } ] }, - { - "id": "core-security-check-ip_access_control_lists", - "group": "core-security", - "module": "core", - "action": "check", - "description": "Verify IP Access Control Lists are properly configured and enforced", - "status": "automated", - "file": "tests/core/security.spec.ts", - "steps": [ - "Open admin portal or repository URL in browser context", - "Log in to the admin portal (if required)", - "Navigate to the relevant settings section", - "Read current configuration values via UI or API" - ], - "automatable": [ - "Full end-to-end execution via Playwright against the admin portal UI", - "Navigation, form interaction, and assertions are scriptable" - ], - "notYet": [], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, { "id": "core-security-check-unnecessary_services_and_ports_are_disabled", "group": "core-security", @@ -1322,7 +1359,6 @@ "description": "Verify unnecessary services and network ports are disabled", "status": "partial", "file": "tests/core/security.spec.ts", - "partialNotes": "Service status via admin portal automated; port scanning requires nmap from external host", "steps": [ "Open admin portal or repository URL in browser context", "Log in to the admin portal (if required)", @@ -1358,228 +1394,8 @@ "label": "Test Data", "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" } - ] - }, - { - "id": "core-security-check-security_event_logging_and_audit_trail_is_active", - "group": "core-security", - "module": "core", - "action": "check", - "description": "Verify security event logging and audit trail are active and recording events", - "status": "automated", - "file": "tests/core/security.spec.ts", - "steps": [ - "Open admin portal or repository URL in browser context", - "Log in to the admin portal (if required)", - "Navigate to the relevant settings section", - "Read current configuration values via UI or API" ], - "automatable": [ - "Full end-to-end execution via Playwright against the admin portal UI", - "Navigation, form interaction, and assertions are scriptable" - ], - "notYet": [], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-security-check-auto_enrollment_certificate_management_process", - "group": "core-security", - "module": "core", - "action": "check", - "description": "Verify auto-enrollment certificate management (ACME/Let's Encrypt) is configured and functional", - "status": "automated", - "file": "tests/core/security.spec.ts", - "steps": [ - "Open admin portal or repository URL in browser context", - "Log in to the admin portal (if required)", - "Navigate to the relevant settings section", - "Read current configuration values via UI or API" - ], - "automatable": [ - "Full end-to-end execution via Playwright against the admin portal UI", - "Navigation, form interaction, and assertions are scriptable" - ], - "notYet": [], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-security-check-known_vulnerable_dependencies_in_release_artifacts", - "group": "core-security", - "module": "core", - "action": "check", - "description": "Verify release artifacts do not contain known vulnerable dependencies (CVE scan)", - "status": "partial", - "file": "tests/core/security.spec.ts", - "partialNotes": "Vulnerability report page in portal automated; actual CVE scanning requires Trivy/OWASP-DC in CI", - "steps": [ - "Open admin portal or repository URL in browser context", - "Log in to the admin portal (if required)", - "Navigate to the relevant settings section", - "Read current configuration values via UI or API" - ], - "automatable": [ - "Portal UI configuration and verification steps (already partially automated)", - "Data extraction and reporting of current settings" - ], - "notYet": [ - "Vulnerability report page in portal automated; actual CVE scanning requires Trivy/OWASP-DC in CI", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Full CVE / dependency scanning (Trivy, Grype, OWASP Dependency-Check) in CI pipeline" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-security-check-previous_security_findings_have_been_remediated_before_release", - "group": "core-security", - "module": "core", - "action": "check", - "description": "Verify all previously identified security findings are remediated before release", - "status": "manual", - "file": "tests/core/security.spec.ts", - "manualReason": "Requires access to security issue tracker and cross-referencing CVEs with the release changelog", - "steps": [ - "Open admin portal or repository URL in browser context", - "Log in to the admin portal (if required)", - "Navigate to the relevant settings section", - "Read current configuration values via UI or API" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires access to security issue tracker and cross-referencing CVEs with the release changelog", - "Requires external SIP endpoints or physical phones for media/audio validation" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-security-check-obtain_formal_security_team_sign_off_for_the_new_version", - "group": "core-security", - "module": "core", - "action": "check", - "description": "Obtain formal written sign-off from the Security team approving the release", - "status": "manual", - "file": "tests/core/security.spec.ts", - "manualReason": "Governance gate requiring human decision and formal sign-off document; cannot be automated", - "steps": [ - "Open admin portal or repository URL in browser context", - "Log in to the admin portal (if required)", - "Navigate to the relevant settings section", - "Read current configuration values via UI or API" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Governance gate requiring human decision and formal sign-off document; cannot be automated", - "Requires external SIP endpoints or physical phones for media/audio validation" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] + "partialNotes": "Service status via admin portal automated; port scanning requires nmap from external host" }, { "id": "core-security-check-verify_role_based_access_control_and_least_privilege_principle", @@ -1624,156 +1440,19 @@ ] }, { - "id": "core-security-check-encryption_of_sensitive_data_at_rest_and_in_transit", + "id": "core-security-write-strong_password_policy", "group": "core-security", "module": "core", - "action": "check", - "description": "Verify sensitive data is encrypted at rest (DB) and in transit (HTTPS/TLS)", - "status": "partial", + "action": "write", + "description": "Navigate to security settings and record the current password policy configuration", + "status": "automated", "file": "tests/core/security.spec.ts", - "partialNotes": "HTTPS/TLS configuration verified via portal; DB-level at-rest encryption requires SSH/CLI access", "steps": [ "Open admin portal or repository URL in browser context", "Log in to the admin portal (if required)", "Navigate to the relevant settings section", "Read current configuration values via UI or API" ], - "automatable": [ - "Portal UI configuration and verification steps (already partially automated)", - "Data extraction and reporting of current settings" - ], - "notYet": [ - "HTTPS/TLS configuration verified via portal; DB-level at-rest encryption requires SSH/CLI access", - "Requires external SIP endpoints or physical phones for media/audio validation" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-installation-check-fresh_installation", - "group": "core-installation", - "module": "core", - "action": "check", - "description": "Verify complete fresh installation from scratch succeeds on each supported hypervisor", - "status": "manual", - "file": "tests/core/installation.spec.ts", - "manualReason": "Requires provisioning a clean VM, mounting ISO/OVA, and running the installation wizard", - "steps": [ - "Open admin portal or repository URL in browser context", - "Prepare clean or previous-version VM/image", - "Perform installation or upgrade procedure", - "Post-install verification via portal + external tools" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires provisioning a clean VM, mounting ISO/OVA, and running the installation wizard", - "Requires external SIP endpoints or physical phones for media/audio validation" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-installation-check-post_install_service_status_and_port_verification", - "group": "core-installation", - "module": "core", - "action": "check", - "description": "Verify all required services are running and expected ports are open after installation", - "status": "partial", - "file": "tests/core/installation.spec.ts", - "partialNotes": "Service status via admin portal automated; TCP port verification requires nmap from external host", - "steps": [ - "Open admin portal or repository URL in browser context", - "Prepare clean or previous-version VM/image", - "Perform installation or upgrade procedure", - "Post-install verification via portal + external tools" - ], - "automatable": [ - "Portal UI configuration and verification steps (already partially automated)", - "Data extraction and reporting of current settings" - ], - "notYet": [ - "Service status via admin portal automated; TCP port verification requires nmap from external host", - "Requires external SIP endpoints or physical phones for media/audio validation" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-installation-check-initial_configuration", - "group": "core-installation", - "module": "core", - "action": "check", - "description": "Verify the initial configuration wizard completes successfully", - "status": "automated", - "file": "tests/core/installation.spec.ts", - "steps": [ - "Open admin portal or repository URL in browser context", - "Prepare clean or previous-version VM/image", - "Perform installation or upgrade procedure", - "Post-install verification via portal + external tools" - ], "automatable": [ "Full end-to-end execution via Playwright against the admin portal UI", "Navigation, form interaction, and assertions are scriptable" @@ -1802,93 +1481,6 @@ } ] }, - { - "id": "core-installation-check-license_activation", - "group": "core-installation", - "module": "core", - "action": "check", - "description": "Verify license activation completes successfully and licensed features are unlocked", - "status": "automated", - "file": "tests/core/installation.spec.ts", - "steps": [ - "Open admin portal or repository URL in browser context", - "Prepare clean or previous-version VM/image", - "Perform installation or upgrade procedure", - "Post-install verification via portal + external tools" - ], - "automatable": [ - "Full end-to-end execution via Playwright against the admin portal UI", - "Navigation, form interaction, and assertions are scriptable" - ], - "notYet": [], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "core-upgrade-check-in_place_upgrade_from_previous_major_version", - "group": "core-upgrade", - "module": "core", - "action": "check", - "description": "Verify in-place upgrade from the previous major version completes successfully without data loss", - "status": "manual", - "file": "tests/core/upgrade.spec.ts", - "manualReason": "Requires a running instance of the previous version and dedicated upgrade test environment", - "steps": [ - "Open admin portal or repository URL in browser context", - "Prepare clean or previous-version VM/image", - "Perform installation or upgrade procedure", - "Post-install verification via portal + external tools" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires a running instance of the previous version and dedicated upgrade test environment", - "Requires external SIP endpoints or physical phones for media/audio validation" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, { "id": "core-upgrade-check-configuration_and_database_migration_validation", "group": "core-upgrade", @@ -1897,7 +1489,6 @@ "description": "Verify configuration objects and database content migrate correctly after upgrade", "status": "partial", "file": "tests/core/upgrade.spec.ts", - "partialNotes": "UI configuration checks automated; DB schema integrity validation requires direct database access", "steps": [ "Open admin portal or repository URL in browser context", "Prepare clean or previous-version VM/image", @@ -1933,17 +1524,17 @@ "label": "Test Data", "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" } - ] + ], + "partialNotes": "UI configuration checks automated; DB schema integrity validation requires direct database access" }, { - "id": "core-upgrade-check-schema_upgrade_and_data_integrity_check", + "id": "core-upgrade-check-in_place_upgrade_from_previous_major_version", "group": "core-upgrade", "module": "core", "action": "check", - "description": "Verify database schema is correctly upgraded and all data maintains integrity", + "description": "Verify in-place upgrade from the previous major version completes successfully without data loss", "status": "manual", "file": "tests/core/upgrade.spec.ts", - "manualReason": "Requires direct database access (psql/mysql) and schema comparison tooling", "steps": [ "Open admin portal or repository URL in browser context", "Prepare clean or previous-version VM/image", @@ -1954,7 +1545,7 @@ "Most UI-driven configuration and verification steps via Playwright" ], "notYet": [ - "Requires direct database access (psql/mysql) and schema comparison tooling", + "Requires a running instance of the previous version and dedicated upgrade test environment", "Requires external SIP endpoints or physical phones for media/audio validation" ], "dependencies": [ @@ -1978,52 +1569,8 @@ "label": "Test Data", "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" } - ] - }, - { - "id": "core-upgrade-check-rollback_procedure_execution_and_verification", - "group": "core-upgrade", - "module": "core", - "action": "check", - "description": "Verify the rollback procedure successfully reverts the system to the previous version", - "status": "manual", - "file": "tests/core/upgrade.spec.ts", - "manualReason": "Requires VM snapshot revert or package downgrade; needs physical/hypervisor-level access", - "steps": [ - "Open admin portal or repository URL in browser context", - "Prepare clean or previous-version VM/image", - "Perform installation or upgrade procedure", - "Post-install verification via portal + external tools" ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires VM snapshot revert or package downgrade; needs physical/hypervisor-level access", - "Requires external SIP endpoints or physical phones for media/audio validation" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS (admin portal) + optional SSH/CLI" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] + "manualReason": "Requires a running instance of the previous version and dedicated upgrade test environment" }, { "id": "core-upgrade-check-post_upgrade_regression_of_core_features", @@ -2067,6 +1614,96 @@ } ] }, + { + "id": "core-upgrade-check-rollback_procedure_execution_and_verification", + "group": "core-upgrade", + "module": "core", + "action": "check", + "description": "Verify the rollback procedure successfully reverts the system to the previous version", + "status": "manual", + "file": "tests/core/upgrade.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Prepare clean or previous-version VM/image", + "Perform installation or upgrade procedure", + "Post-install verification via portal + external tools" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires VM snapshot revert or package downgrade; needs physical/hypervisor-level access", + "Requires external SIP endpoints or physical phones for media/audio validation" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires VM snapshot revert or package downgrade; needs physical/hypervisor-level access" + }, + { + "id": "core-upgrade-check-schema_upgrade_and_data_integrity_check", + "group": "core-upgrade", + "module": "core", + "action": "check", + "description": "Verify database schema is correctly upgraded and all data maintains integrity", + "status": "manual", + "file": "tests/core/upgrade.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Prepare clean or previous-version VM/image", + "Perform installation or upgrade procedure", + "Post-install verification via portal + external tools" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires direct database access (psql/mysql) and schema comparison tooling", + "Requires external SIP endpoints or physical phones for media/audio validation" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires direct database access (psql/mysql) and schema comparison tooling" + }, { "id": "core-upgrade-check-zero_downtime_upgrade_where_supported", "group": "core-upgrade", @@ -2075,7 +1712,6 @@ "description": "Verify zero-downtime upgrade keeps the service available throughout the upgrade process", "status": "manual", "file": "tests/core/upgrade.spec.ts", - "manualReason": "Requires active call sessions monitored during the upgrade window; calls cannot be managed by Playwright", "steps": [ "Open admin portal or repository URL in browser context", "Prepare clean or previous-version VM/image", @@ -2110,16 +1746,17 @@ "label": "Test Data", "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" } - ] + ], + "manualReason": "Requires active call sessions monitored during the upgrade window; calls cannot be managed by Playwright" }, { - "id": "core-interoperability-check-addm", - "group": "core-interoperability", + "id": "core-virtualization-check-hypervisor_level_high_availability", + "group": "core-virtualization", "module": "core", "action": "check", - "description": "Verify ADDM integration is configured and reporting discovery data correctly", - "status": "automated", - "file": "tests/core/interoperability.spec.ts", + "description": "Verify hypervisor-level HA restarts the PBX VM after a host failure", + "status": "manual", + "file": "tests/core/virtualization.spec.ts", "steps": [ "Open admin portal or repository URL in browser context", "Execute the main verification or configuration action described in the test", @@ -2127,10 +1764,14 @@ "Assert expected outcome" ], "automatable": [ - "Full end-to-end execution via Playwright against the admin portal UI", - "Navigation, form interaction, and assertions are scriptable" + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires physical HA cluster with multiple hypervisor hosts; host failure must be simulated", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", + "Long-running load or HA failover scenarios need dedicated lab infrastructure" ], - "notYet": [], "dependencies": [ { "label": "Admin Portal", @@ -2145,8 +1786,8 @@ "value": "HTTPS (admin portal) + optional SSH/CLI" }, { - "label": "External Systems", - "value": "SIEM server (Splunk, ELK, QRadar) and/or ADDM/ADDM collector" + "label": "Hypervisor Access", + "value": "vCenter, Hyper-V Manager, Proxmox, or virsh (SSH/API)" }, { "label": "Credentials", @@ -2156,16 +1797,17 @@ "label": "Test Data", "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" } - ] + ], + "manualReason": "Requires physical HA cluster with multiple hypervisor hosts; host failure must be simulated" }, { - "id": "core-interoperability-check-siem", - "group": "core-interoperability", + "id": "core-virtualization-check-live_migration_and_active_call_preservation", + "group": "core-virtualization", "module": "core", "action": "check", - "description": "Verify SIEM integration is configured and forwarding security events", - "status": "automated", - "file": "tests/core/interoperability.spec.ts", + "description": "Verify VM live migration preserves active calls without interruption", + "status": "manual", + "file": "tests/core/virtualization.spec.ts", "steps": [ "Open admin portal or repository URL in browser context", "Execute the main verification or configuration action described in the test", @@ -2173,10 +1815,14 @@ "Assert expected outcome" ], "automatable": [ - "Full end-to-end execution via Playwright against the admin portal UI", - "Navigation, form interaction, and assertions are scriptable" + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires HA infrastructure with 2+ hypervisor hosts and active SIP call sessions during migration", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", + "Long-running load or HA failover scenarios need dedicated lab infrastructure" ], - "notYet": [], "dependencies": [ { "label": "Admin Portal", @@ -2191,8 +1837,263 @@ "value": "HTTPS (admin portal) + optional SSH/CLI" }, { - "label": "External Systems", - "value": "SIEM server (Splunk, ELK, QRadar) and/or ADDM/ADDM collector" + "label": "Hypervisor Access", + "value": "vCenter, Hyper-V Manager, Proxmox, or virsh (SSH/API)" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires HA infrastructure with 2+ hypervisor hosts and active SIP call sessions during migration" + }, + { + "id": "core-virtualization-check-snapshot_backup_restore_and_consistency", + "group": "core-virtualization", + "module": "core", + "action": "check", + "description": "Verify VM snapshot and restore operations maintain full system consistency", + "status": "partial", + "file": "tests/core/virtualization.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Portal UI configuration and verification steps (already partially automated)", + "Data extraction and reporting of current settings" + ], + "notYet": [ + "Post-restore consistency checks via admin portal automated; snapshot/restore operation needs hypervisor access", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", + "Long-running load or HA failover scenarios need dedicated lab infrastructure" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Hypervisor Access", + "value": "vCenter, Hyper-V Manager, Proxmox, or virsh (SSH/API)" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "partialNotes": "Post-restore consistency checks via admin portal automated; snapshot/restore operation needs hypervisor access" + }, + { + "id": "core-virtualization-write-guest_agent_integration", + "group": "core-virtualization", + "module": "core", + "action": "write", + "description": "Record guest agent integration status for each supported hypervisor", + "status": "manual", + "file": "tests/core/virtualization.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires direct access to hypervisor console (vCenter, Hyper-V Manager, virsh)", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", + "Long-running load or HA failover scenarios need dedicated lab infrastructure" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Hypervisor Access", + "value": "vCenter, Hyper-V Manager, Proxmox, or virsh (SSH/API)" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires direct access to hypervisor console (vCenter, Hyper-V Manager, virsh)" + }, + { + "id": "core-virtualization-write-resource_allocation_vcpu_vram_vdisk", + "group": "core-virtualization", + "module": "core", + "action": "write", + "description": "Record vCPU, vRAM, and vDisk resource allocation for deployment templates", + "status": "manual", + "file": "tests/core/virtualization.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Hypervisor management plane access required; not exposed in PBX admin portal", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", + "Long-running load or HA failover scenarios need dedicated lab infrastructure" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Hypervisor Access", + "value": "vCenter, Hyper-V Manager, Proxmox, or virsh (SSH/API)" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Hypervisor management plane access required; not exposed in PBX admin portal" + }, + { + "id": "core-virtualization-write-storage_thin_vs_thick_provisioning", + "group": "core-virtualization", + "module": "core", + "action": "write", + "description": "Record storage provisioning type and performance implications for each hypervisor", + "status": "manual", + "file": "tests/core/virtualization.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Storage details only visible in hypervisor storage management interface", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", + "Long-running load or HA failover scenarios need dedicated lab infrastructure" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Hypervisor Access", + "value": "vCenter, Hyper-V Manager, Proxmox, or virsh (SSH/API)" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Storage details only visible in hypervisor storage management interface" + }, + { + "id": "core-virtualization-write-supported_hypervisors_deployment", + "group": "core-virtualization", + "module": "core", + "action": "write", + "description": "Record the list of supported hypervisors and deployment methods from the download portal", + "status": "automated", + "file": "tests/core/virtualization.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Full end-to-end execution via Playwright against the admin portal UI", + "Navigation, form interaction, and assertions are scriptable" + ], + "notYet": [ + "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", + "Long-running load or HA failover scenarios need dedicated lab infrastructure" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Hypervisor Access", + "value": "vCenter, Hyper-V Manager, Proxmox, or virsh (SSH/API)" }, { "label": "Credentials", @@ -2205,11 +2106,1023 @@ ] }, { - "id": "pbx-configuration-check-initial_system_setup_and_network_settings", + "id": "core-virtualization-write-virtual_networking_configuration", + "group": "core-virtualization", + "module": "core", + "action": "write", + "description": "Record virtual networking configuration: virtual switches, VLANs, NIC assignments", + "status": "manual", + "file": "tests/core/virtualization.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires access to hypervisor networking configuration and virtual switch management", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", + "Long-running load or HA failover scenarios need dedicated lab infrastructure" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS (admin portal) + optional SSH/CLI" + }, + { + "label": "Hypervisor Access", + "value": "vCenter, Hyper-V Manager, Proxmox, or virsh (SSH/API)" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires access to hypervisor networking configuration and virtual switch management" + }, + { + "id": "pbx-availability-check-active_passive_or_active_active_failover", + "group": "pbx-availability", + "module": "pbx", + "action": "check", + "description": "Verify Active-Passive or Active-Active failover transitions correctly on node failure", + "status": "manual", + "file": "tests/pbx/availability.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires HA cluster with 2+ nodes; failover must be triggered by stopping the active node", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", + "Long-running load or HA failover scenarios need dedicated lab infrastructure" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "Load Gen", + "value": "SIPp or custom load generator + monitoring (Prometheus/Grafana recommended)" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires HA cluster with 2+ nodes; failover must be triggered by stopping the active node" + }, + { + "id": "pbx-availability-check-automatic_failover_and_call_preservation", + "group": "pbx-availability", + "module": "pbx", + "action": "check", + "description": "Verify automatic failover preserves active calls (no drops, no audio interruption > 200ms)", + "status": "manual", + "file": "tests/pbx/availability.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires active call sessions during failover and simultaneous call-state monitoring", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", + "Long-running load or HA failover scenarios need dedicated lab infrastructure" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "Load Gen", + "value": "SIPp or custom load generator + monitoring (Prometheus/Grafana recommended)" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires active call sessions during failover and simultaneous call-state monitoring" + }, + { + "id": "pbx-availability-check-database_replication_and_sync_integrity", + "group": "pbx-availability", + "module": "pbx", + "action": "check", + "description": "Verify database replication between HA nodes maintains consistency and acceptable lag", + "status": "manual", + "file": "tests/pbx/availability.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires HA database cluster; verifying replication lag needs direct database access", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", + "Long-running load or HA failover scenarios need dedicated lab infrastructure" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "Load Gen", + "value": "SIPp or custom load generator + monitoring (Prometheus/Grafana recommended)" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires HA database cluster; verifying replication lag needs direct database access" + }, + { + "id": "pbx-availability-check-geographic_redundancy_and_geo_distribution", + "group": "pbx-availability", + "module": "pbx", + "action": "check", + "description": "Verify geo-distributed deployment handles site failover without service interruption", + "status": "manual", + "file": "tests/pbx/availability.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires multi-site infrastructure across geographic locations or WAN simulation", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", + "Long-running load or HA failover scenarios need dedicated lab infrastructure" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "Load Gen", + "value": "SIPp or custom load generator + monitoring (Prometheus/Grafana recommended)" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires multi-site infrastructure across geographic locations or WAN simulation" + }, + { + "id": "pbx-calls-check-call_hold_resume_and_music_on_hold", + "group": "pbx-calls", + "module": "pbx", + "action": "check", + "description": "Verify call hold, resume, and Music on Hold playback work correctly", + "status": "manual", + "file": "tests/pbx/calls.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Ensure SIP endpoints / softphones are registered", + "Initiate or receive call using the required scenario", + "Verify audio path, signaling, and media parameters" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires an active two-party call; MoH requires audio monitoring with real SIP phone hardware", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", + "External SIP trunk / PSTN connectivity and DID numbers" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "SIP Endpoints", + "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" + }, + { + "label": "Network", + "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires an active two-party call; MoH requires audio monitoring with real SIP phone hardware" + }, + { + "id": "pbx-calls-check-call_waiting_notification_and_switching", + "group": "pbx-calls", + "module": "pbx", + "action": "check", + "description": "Verify call waiting notification and switching between active and waiting calls", + "status": "manual", + "file": "tests/pbx/calls.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Ensure SIP endpoints / softphones are registered", + "Initiate or receive call using the required scenario", + "Verify audio path, signaling, and media parameters" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires concurrent call sessions on the same extension with physical/softphone capable of call-waiting", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", + "External SIP trunk / PSTN connectivity and DID numbers" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "SIP Endpoints", + "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" + }, + { + "label": "Network", + "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires concurrent call sessions on the same extension with physical/softphone capable of call-waiting" + }, + { + "id": "pbx-calls-check-caller_id_presentation_restriction_and_pai", + "group": "pbx-calls", + "module": "pbx", + "action": "check", + "description": "Verify Caller ID presentation, Anonymous restriction (CLIR), and P-Asserted-Identity header", + "status": "manual", + "file": "tests/pbx/calls.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Ensure SIP endpoints / softphones are registered", + "Initiate or receive call using the required scenario", + "Verify audio path, signaling, and media parameters" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires active call sessions and SIP packet capture to verify PAI header values", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", + "External SIP trunk / PSTN connectivity and DID numbers" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "SIP Endpoints", + "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" + }, + { + "label": "Network", + "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires active call sessions and SIP packet capture to verify PAI header values" + }, + { + "id": "pbx-calls-check-inbound_call_from_sip_trunk_pstn", + "group": "pbx-calls", + "module": "pbx", + "action": "check", + "description": "Verify inbound call from a SIP trunk/PSTN routes correctly to the configured destination", + "status": "manual", + "file": "tests/pbx/calls.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Ensure SIP endpoints / softphones are registered", + "Initiate or receive call using the required scenario", + "Verify audio path, signaling, and media parameters" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires live SIP trunk connectivity to PSTN and a real DID number", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", + "External SIP trunk / PSTN connectivity and DID numbers" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "SIP Endpoints", + "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" + }, + { + "label": "Network", + "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires live SIP trunk connectivity to PSTN and a real DID number" + }, + { + "id": "pbx-calls-check-internal_extension_to_extension_audio_call", + "group": "pbx-calls", + "module": "pbx", + "action": "check", + "description": "Verify internal extension-to-extension audio call connects with bi-directional audio", + "status": "manual", + "file": "tests/pbx/calls.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Ensure SIP endpoints / softphones are registered", + "Initiate or receive call using the required scenario", + "Verify audio path, signaling, and media parameters" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires two active SIP endpoints and human verification of two-way audio quality", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", + "External SIP trunk / PSTN connectivity and DID numbers" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "SIP Endpoints", + "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" + }, + { + "label": "Network", + "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires two active SIP endpoints and human verification of two-way audio quality" + }, + { + "id": "pbx-calls-check-outbound_call_to_sip_trunk_pstn_with_caller_id", + "group": "pbx-calls", + "module": "pbx", + "action": "check", + "description": "Verify outbound call via SIP trunk presents the correct Caller ID on the receiving end", + "status": "manual", + "file": "tests/pbx/calls.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Ensure SIP endpoints / softphones are registered", + "Initiate or receive call using the required scenario", + "Verify audio path, signaling, and media parameters" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires live SIP trunk and verification of Caller ID at receiving PSTN party", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", + "External SIP trunk / PSTN connectivity and DID numbers" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "SIP Endpoints", + "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" + }, + { + "label": "Network", + "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires live SIP trunk and verification of Caller ID at receiving PSTN party" + }, + { + "id": "pbx-calls-check-three_way_conference_and_multi_party_bridge", + "group": "pbx-calls", + "module": "pbx", + "action": "check", + "description": "Verify three-way conference calling and multi-party conference bridge functionality", + "status": "manual", + "file": "tests/pbx/calls.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Ensure SIP endpoints / softphones are registered", + "Initiate or receive call using the required scenario", + "Verify audio path, signaling, and media parameters" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires three or more active SIP endpoints and audio verification by human listeners", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", + "External SIP trunk / PSTN connectivity and DID numbers" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "SIP Endpoints", + "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" + }, + { + "label": "Network", + "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires three or more active SIP endpoints and audio verification by human listeners" + }, + { + "id": "pbx-calls-security-check-acl_ip_whitelisting_and_rate_limiting", + "group": "pbx-calls-security", + "module": "pbx", + "action": "check", + "description": "Verify ACL IP whitelisting rules and SIP rate limiting are configured and enforced", + "status": "partial", + "file": "tests/pbx/calls-security.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Log in to the admin portal (if required)", + "Navigate to the relevant settings section", + "Read current configuration values via UI or API" + ], + "automatable": [ + "Portal UI configuration and verification steps (already partially automated)", + "Data extraction and reporting of current settings" + ], + "notYet": [ + "ACL/rate-limit config via portal automated; functional enforcement testing requires network-level testing from non-whitelisted IP", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", + "External SIP trunk / PSTN connectivity and DID numbers" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "SIP Endpoints", + "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" + }, + { + "label": "Network", + "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "partialNotes": "ACL/rate-limit config via portal automated; functional enforcement testing requires network-level testing from non-whitelisted IP" + }, + { + "id": "pbx-calls-security-check-srtp_sdes_or_dtls_media_encryption", + "group": "pbx-calls-security", + "module": "pbx", + "action": "check", + "description": "Verify SRTP with SDES or DTLS-SRTP is enabled for media encryption on calls", + "status": "partial", + "file": "tests/pbx/calls-security.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Log in to the admin portal (if required)", + "Navigate to the relevant settings section", + "Read current configuration values via UI or API" + ], + "automatable": [ + "Portal UI configuration and verification steps (already partially automated)", + "Data extraction and reporting of current settings" + ], + "notYet": [ + "Encryption config verified via admin portal; confirming live RTP is encrypted requires Wireshark during active call", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", + "External SIP trunk / PSTN connectivity and DID numbers" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "SIP Endpoints", + "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" + }, + { + "label": "Network", + "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "partialNotes": "Encryption config verified via admin portal; confirming live RTP is encrypted requires Wireshark during active call" + }, + { + "id": "pbx-calls-security-check-toll_fraud_prevention_rules_and_alerting", + "group": "pbx-calls-security", + "module": "pbx", + "action": "check", + "description": "Verify toll fraud prevention rules and alert notifications are configured", + "status": "automated", + "file": "tests/pbx/calls-security.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Log in to the admin portal (if required)", + "Navigate to the relevant settings section", + "Read current configuration values via UI or API" + ], + "automatable": [ + "Full end-to-end execution via Playwright against the admin portal UI", + "Navigation, form interaction, and assertions are scriptable" + ], + "notYet": [ + "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", + "External SIP trunk / PSTN connectivity and DID numbers" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "SIP Endpoints", + "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" + }, + { + "label": "Network", + "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ] + }, + { + "id": "pbx-codecs-check-codec_negotiation_g711_g729_opus_g722", + "group": "pbx-codecs", + "module": "pbx", + "action": "check", + "description": "Verify successful codec negotiation for G.711, G.729, Opus, and G.722", + "status": "manual", + "file": "tests/pbx/codecs.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Ensure SIP endpoints / softphones are registered", + "Initiate or receive call using the required scenario", + "Verify audio path, signaling, and media parameters" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires SIP call traffic with codec-constrained endpoints and Wireshark packet capture to verify SDP negotiation", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", + "External SIP trunk / PSTN connectivity and DID numbers" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "SIP Endpoints", + "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" + }, + { + "label": "Network", + "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires SIP call traffic with codec-constrained endpoints and Wireshark packet capture to verify SDP negotiation" + }, + { + "id": "pbx-codecs-check-dtmf_transmission_rfc2833_inband_sip_info", + "group": "pbx-codecs", + "module": "pbx", + "action": "check", + "description": "Verify DTMF digit transmission via RFC2833, in-band audio, and SIP INFO methods", + "status": "manual", + "file": "tests/pbx/codecs.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Ensure SIP endpoints / softphones are registered", + "Initiate or receive call using the required scenario", + "Verify audio path, signaling, and media parameters" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires active call sessions with DTMF generation, packet capture, and IVR system for verification", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", + "External SIP trunk / PSTN connectivity and DID numbers" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "SIP Endpoints", + "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" + }, + { + "label": "Network", + "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires active call sessions with DTMF generation, packet capture, and IVR system for verification" + }, + { + "id": "pbx-codecs-check-t38_fax_passthrough_and_error_correction", + "group": "pbx-codecs", + "module": "pbx", + "action": "check", + "description": "Verify T.38 fax passthrough and error correction (ECM) work correctly", + "status": "manual", + "file": "tests/pbx/codecs.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Ensure SIP endpoints / softphones are registered", + "Initiate or receive call using the required scenario", + "Verify audio path, signaling, and media parameters" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires fax hardware or fax emulator (HylaFAX) and T.38 stack support", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", + "External SIP trunk / PSTN connectivity and DID numbers" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "SIP Endpoints", + "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" + }, + { + "label": "Network", + "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires fax hardware or fax emulator (HylaFAX) and T.38 stack support" + }, + { + "id": "pbx-configuration-check-backup_restore_full_system_configuration", "group": "pbx-configuration", "module": "pbx", "action": "check", - "description": "Verify initial PBX system setup and network settings are correctly configured", + "description": "Verify full system configuration backup and restore operations work correctly", + "status": "automated", + "file": "tests/pbx/configuration.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Log in to the admin portal (if required)", + "Navigate to the relevant settings section", + "Read current configuration values via UI or API" + ], + "automatable": [ + "Full end-to-end execution via Playwright against the admin portal UI", + "Navigation, form interaction, and assertions are scriptable" + ], + "notYet": [], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ] + }, + { + "id": "pbx-configuration-check-bulk_csv_import_export_of_settings", + "group": "pbx-configuration", + "module": "pbx", + "action": "check", + "description": "Verify bulk CSV import and export of settings", "status": "automated", "file": "tests/pbx/configuration.spec.ts", "steps": [ @@ -2289,53 +3202,11 @@ ] }, { - "id": "pbx-configuration-check-backup_restore_full_system_configuration", + "id": "pbx-configuration-check-initial_system_setup_and_network_settings", "group": "pbx-configuration", "module": "pbx", "action": "check", - "description": "Verify full system configuration backup and restore operations work correctly", - "status": "automated", - "file": "tests/pbx/configuration.spec.ts", - "steps": [ - "Open admin portal or repository URL in browser context", - "Log in to the admin portal (if required)", - "Navigate to the relevant settings section", - "Read current configuration values via UI or API" - ], - "automatable": [ - "Full end-to-end execution via Playwright against the admin portal UI", - "Navigation, form interaction, and assertions are scriptable" - ], - "notYet": [], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "pbx-configuration-check-bulk_csv_import_export_of_settings", - "group": "pbx-configuration", - "module": "pbx", - "action": "check", - "description": "Verify bulk CSV import and export of settings", + "description": "Verify initial PBX system setup and network settings are correctly configured", "status": "automated", "file": "tests/pbx/configuration.spec.ts", "steps": [ @@ -2422,59 +3293,6 @@ } ] }, - { - "id": "pbx-extensions-check-extension_registration_with_deskphones_softphones", - "group": "pbx-extensions", - "module": "pbx", - "action": "check", - "description": "Verify SIP extension registers successfully from a desk phone and a softphone client", - "status": "manual", - "file": "tests/pbx/extensions.spec.ts", - "manualReason": "Requires physical SIP desk phone (Yealink, Polycom) or softphone (Zoiper, MicroSIP)", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires physical SIP desk phone (Yealink, Polycom) or softphone (Zoiper, MicroSIP)", - "Requires external SIP endpoints or physical phones for media/audio validation" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "SIP Endpoints", - "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" - }, - { - "label": "Network", - "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, { "id": "pbx-extensions-check-device_provisioning", "group": "pbx-extensions", @@ -2483,7 +3301,6 @@ "description": "Verify automatic device provisioning: profile generation and server URL accessible", "status": "partial", "file": "tests/pbx/extensions.spec.ts", - "partialNotes": "Provisioning profile creation via admin portal automated; actual device provisioning requires physical phone", "steps": [ "Open admin portal or repository URL in browser context", "Execute the main verification or configuration action described in the test", @@ -2527,31 +3344,29 @@ "label": "Test Data", "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" } - ] + ], + "partialNotes": "Provisioning profile creation via admin portal automated; actual device provisioning requires physical phone" }, { - "id": "pbx-calls-check-internal_extension_to_extension_audio_call", - "group": "pbx-calls", + "id": "pbx-extensions-check-extension_registration_with_deskphones_softphones", + "group": "pbx-extensions", "module": "pbx", "action": "check", - "description": "Verify internal extension-to-extension audio call connects with bi-directional audio", + "description": "Verify SIP extension registers successfully from a desk phone and a softphone client", "status": "manual", - "file": "tests/pbx/calls.spec.ts", - "manualReason": "Requires two active SIP endpoints and human verification of two-way audio quality", + "file": "tests/pbx/extensions.spec.ts", "steps": [ "Open admin portal or repository URL in browser context", - "Ensure SIP endpoints / softphones are registered", - "Initiate or receive call using the required scenario", - "Verify audio path, signaling, and media parameters" + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" ], "automatable": [ "Most UI-driven configuration and verification steps via Playwright" ], "notYet": [ - "Requires two active SIP endpoints and human verification of two-way audio quality", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", - "External SIP trunk / PSTN connectivity and DID numbers" + "Requires physical SIP desk phone (Yealink, Polycom) or softphone (Zoiper, MicroSIP)", + "Requires external SIP endpoints or physical phones for media/audio validation" ], "dependencies": [ { @@ -2582,1034 +3397,17 @@ "label": "Test Data", "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" } - ] + ], + "manualReason": "Requires physical SIP desk phone (Yealink, Polycom) or softphone (Zoiper, MicroSIP)" }, { - "id": "pbx-calls-check-inbound_call_from_sip_trunk_pstn", - "group": "pbx-calls", + "id": "pbx-logs-check-call_quality_metrics_mos_jitter_loss_per_call", + "group": "pbx-logs", "module": "pbx", "action": "check", - "description": "Verify inbound call from a SIP trunk/PSTN routes correctly to the configured destination", - "status": "manual", - "file": "tests/pbx/calls.spec.ts", - "manualReason": "Requires live SIP trunk connectivity to PSTN and a real DID number", - "steps": [ - "Open admin portal or repository URL in browser context", - "Ensure SIP endpoints / softphones are registered", - "Initiate or receive call using the required scenario", - "Verify audio path, signaling, and media parameters" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires live SIP trunk connectivity to PSTN and a real DID number", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", - "External SIP trunk / PSTN connectivity and DID numbers" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "SIP Endpoints", - "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" - }, - { - "label": "Network", - "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "pbx-calls-check-outbound_call_to_sip_trunk_pstn_with_caller_id", - "group": "pbx-calls", - "module": "pbx", - "action": "check", - "description": "Verify outbound call via SIP trunk presents the correct Caller ID on the receiving end", - "status": "manual", - "file": "tests/pbx/calls.spec.ts", - "manualReason": "Requires live SIP trunk and verification of Caller ID at receiving PSTN party", - "steps": [ - "Open admin portal or repository URL in browser context", - "Ensure SIP endpoints / softphones are registered", - "Initiate or receive call using the required scenario", - "Verify audio path, signaling, and media parameters" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires live SIP trunk and verification of Caller ID at receiving PSTN party", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", - "External SIP trunk / PSTN connectivity and DID numbers" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "SIP Endpoints", - "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" - }, - { - "label": "Network", - "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "pbx-calls-check-caller_id_presentation_restriction_and_pai", - "group": "pbx-calls", - "module": "pbx", - "action": "check", - "description": "Verify Caller ID presentation, Anonymous restriction (CLIR), and P-Asserted-Identity header", - "status": "manual", - "file": "tests/pbx/calls.spec.ts", - "manualReason": "Requires active call sessions and SIP packet capture to verify PAI header values", - "steps": [ - "Open admin portal or repository URL in browser context", - "Ensure SIP endpoints / softphones are registered", - "Initiate or receive call using the required scenario", - "Verify audio path, signaling, and media parameters" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires active call sessions and SIP packet capture to verify PAI header values", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", - "External SIP trunk / PSTN connectivity and DID numbers" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "SIP Endpoints", - "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" - }, - { - "label": "Network", - "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "pbx-calls-check-call_hold_resume_and_music_on_hold", - "group": "pbx-calls", - "module": "pbx", - "action": "check", - "description": "Verify call hold, resume, and Music on Hold playback work correctly", - "status": "manual", - "file": "tests/pbx/calls.spec.ts", - "manualReason": "Requires an active two-party call; MoH requires audio monitoring with real SIP phone hardware", - "steps": [ - "Open admin portal or repository URL in browser context", - "Ensure SIP endpoints / softphones are registered", - "Initiate or receive call using the required scenario", - "Verify audio path, signaling, and media parameters" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires an active two-party call; MoH requires audio monitoring with real SIP phone hardware", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", - "External SIP trunk / PSTN connectivity and DID numbers" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "SIP Endpoints", - "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" - }, - { - "label": "Network", - "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "pbx-calls-check-call_waiting_notification_and_switching", - "group": "pbx-calls", - "module": "pbx", - "action": "check", - "description": "Verify call waiting notification and switching between active and waiting calls", - "status": "manual", - "file": "tests/pbx/calls.spec.ts", - "manualReason": "Requires concurrent call sessions on the same extension with physical/softphone capable of call-waiting", - "steps": [ - "Open admin portal or repository URL in browser context", - "Ensure SIP endpoints / softphones are registered", - "Initiate or receive call using the required scenario", - "Verify audio path, signaling, and media parameters" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires concurrent call sessions on the same extension with physical/softphone capable of call-waiting", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", - "External SIP trunk / PSTN connectivity and DID numbers" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "SIP Endpoints", - "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" - }, - { - "label": "Network", - "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "pbx-calls-check-three_way_conference_and_multi_party_bridge", - "group": "pbx-calls", - "module": "pbx", - "action": "check", - "description": "Verify three-way conference calling and multi-party conference bridge functionality", - "status": "manual", - "file": "tests/pbx/calls.spec.ts", - "manualReason": "Requires three or more active SIP endpoints and audio verification by human listeners", - "steps": [ - "Open admin portal or repository URL in browser context", - "Ensure SIP endpoints / softphones are registered", - "Initiate or receive call using the required scenario", - "Verify audio path, signaling, and media parameters" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires three or more active SIP endpoints and audio verification by human listeners", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", - "External SIP trunk / PSTN connectivity and DID numbers" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "SIP Endpoints", - "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" - }, - { - "label": "Network", - "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "pbx-codecs-check-codec_negotiation_g711_g729_opus_g722", - "group": "pbx-codecs", - "module": "pbx", - "action": "check", - "description": "Verify successful codec negotiation for G.711, G.729, Opus, and G.722", - "status": "manual", - "file": "tests/pbx/codecs.spec.ts", - "manualReason": "Requires SIP call traffic with codec-constrained endpoints and Wireshark packet capture to verify SDP negotiation", - "steps": [ - "Open admin portal or repository URL in browser context", - "Ensure SIP endpoints / softphones are registered", - "Initiate or receive call using the required scenario", - "Verify audio path, signaling, and media parameters" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires SIP call traffic with codec-constrained endpoints and Wireshark packet capture to verify SDP negotiation", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", - "External SIP trunk / PSTN connectivity and DID numbers" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "SIP Endpoints", - "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" - }, - { - "label": "Network", - "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "pbx-codecs-check-dtmf_transmission_rfc2833_inband_sip_info", - "group": "pbx-codecs", - "module": "pbx", - "action": "check", - "description": "Verify DTMF digit transmission via RFC2833, in-band audio, and SIP INFO methods", - "status": "manual", - "file": "tests/pbx/codecs.spec.ts", - "manualReason": "Requires active call sessions with DTMF generation, packet capture, and IVR system for verification", - "steps": [ - "Open admin portal or repository URL in browser context", - "Ensure SIP endpoints / softphones are registered", - "Initiate or receive call using the required scenario", - "Verify audio path, signaling, and media parameters" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires active call sessions with DTMF generation, packet capture, and IVR system for verification", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", - "External SIP trunk / PSTN connectivity and DID numbers" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "SIP Endpoints", - "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" - }, - { - "label": "Network", - "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "pbx-codecs-check-t38_fax_passthrough_and_error_correction", - "group": "pbx-codecs", - "module": "pbx", - "action": "check", - "description": "Verify T.38 fax passthrough and error correction (ECM) work correctly", - "status": "manual", - "file": "tests/pbx/codecs.spec.ts", - "manualReason": "Requires fax hardware or fax emulator (HylaFAX) and T.38 stack support", - "steps": [ - "Open admin portal or repository URL in browser context", - "Ensure SIP endpoints / softphones are registered", - "Initiate or receive call using the required scenario", - "Verify audio path, signaling, and media parameters" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires fax hardware or fax emulator (HylaFAX) and T.38 stack support", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", - "External SIP trunk / PSTN connectivity and DID numbers" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "SIP Endpoints", - "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" - }, - { - "label": "Network", - "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "pbx-calls-security-check-srtp_sdes_or_dtls_media_encryption", - "group": "pbx-calls-security", - "module": "pbx", - "action": "check", - "description": "Verify SRTP with SDES or DTLS-SRTP is enabled for media encryption on calls", + "description": "Verify per-call quality metrics (MOS score, jitter, packet loss) are collected and displayed", "status": "partial", - "file": "tests/pbx/calls-security.spec.ts", - "partialNotes": "Encryption config verified via admin portal; confirming live RTP is encrypted requires Wireshark during active call", - "steps": [ - "Open admin portal or repository URL in browser context", - "Log in to the admin portal (if required)", - "Navigate to the relevant settings section", - "Read current configuration values via UI or API" - ], - "automatable": [ - "Portal UI configuration and verification steps (already partially automated)", - "Data extraction and reporting of current settings" - ], - "notYet": [ - "Encryption config verified via admin portal; confirming live RTP is encrypted requires Wireshark during active call", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", - "External SIP trunk / PSTN connectivity and DID numbers" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "SIP Endpoints", - "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" - }, - { - "label": "Network", - "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "pbx-calls-security-check-acl_ip_whitelisting_and_rate_limiting", - "group": "pbx-calls-security", - "module": "pbx", - "action": "check", - "description": "Verify ACL IP whitelisting rules and SIP rate limiting are configured and enforced", - "status": "partial", - "file": "tests/pbx/calls-security.spec.ts", - "partialNotes": "ACL/rate-limit config via portal automated; functional enforcement testing requires network-level testing from non-whitelisted IP", - "steps": [ - "Open admin portal or repository URL in browser context", - "Log in to the admin portal (if required)", - "Navigate to the relevant settings section", - "Read current configuration values via UI or API" - ], - "automatable": [ - "Portal UI configuration and verification steps (already partially automated)", - "Data extraction and reporting of current settings" - ], - "notYet": [ - "ACL/rate-limit config via portal automated; functional enforcement testing requires network-level testing from non-whitelisted IP", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", - "External SIP trunk / PSTN connectivity and DID numbers" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "SIP Endpoints", - "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" - }, - { - "label": "Network", - "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "pbx-calls-security-check-toll_fraud_prevention_rules_and_alerting", - "group": "pbx-calls-security", - "module": "pbx", - "action": "check", - "description": "Verify toll fraud prevention rules and alert notifications are configured", - "status": "automated", - "file": "tests/pbx/calls-security.spec.ts", - "steps": [ - "Open admin portal or repository URL in browser context", - "Log in to the admin portal (if required)", - "Navigate to the relevant settings section", - "Read current configuration values via UI or API" - ], - "automatable": [ - "Full end-to-end execution via Playwright against the admin portal UI", - "Navigation, form interaction, and assertions are scriptable" - ], - "notYet": [ - "Real RTP/SRTP media path and audio quality verification (human ear or PESQ/MOS tools)", - "External SIP trunk / PSTN connectivity and DID numbers" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "SIP Endpoints", - "value": "At least 2 registered SIP clients (deskphone or softphone: Zoiper, MicroSIP, Yealink, etc.)" - }, - { - "label": "Network", - "value": "SIP trunk or local Asterisk/FreeSWITCH simulator for PSTN simulation" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "pbx-performance-check-cpu_memory_disk_io_utilization_under_sustained_load", - "group": "pbx-performance", - "module": "pbx", - "action": "check", - "description": "Verify CPU, memory, and disk I/O remain within limits under sustained call load", - "status": "manual", - "file": "tests/pbx/performance.spec.ts", - "manualReason": "Requires SIPp load generator, server-side performance monitoring, and dedicated test environment", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires SIPp load generator, server-side performance monitoring, and dedicated test environment", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", - "Long-running load or HA failover scenarios need dedicated lab infrastructure" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "Load Gen", - "value": "SIPp or custom load generator + monitoring (Prometheus/Grafana recommended)" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "pbx-performance-check-long_duration_stability_72h_test", - "group": "pbx-performance", - "module": "pbx", - "action": "check", - "description": "Verify system stability under continuous call load over a 72-hour period", - "status": "manual", - "file": "tests/pbx/performance.spec.ts", - "manualReason": "72-hour test requires dedicated environment, SIPp continuous load, and automated monitoring with alerting", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "72-hour test requires dedicated environment, SIPp continuous load, and automated monitoring with alerting", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", - "Long-running load or HA failover scenarios need dedicated lab infrastructure" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "Load Gen", - "value": "SIPp or custom load generator + monitoring (Prometheus/Grafana recommended)" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "pbx-performance-check-memory_leak_and_resource_cleanup_detection", - "group": "pbx-performance", - "module": "pbx", - "action": "check", - "description": "Detect memory leaks and verify proper resource cleanup over extended operation", - "status": "manual", - "file": "tests/pbx/performance.spec.ts", - "manualReason": "Requires extended monitoring with active call load and memory profiling tools (Valgrind, heap dumps)", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires extended monitoring with active call load and memory profiling tools (Valgrind, heap dumps)", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", - "Long-running load or HA failover scenarios need dedicated lab infrastructure" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "Load Gen", - "value": "SIPp or custom load generator + monitoring (Prometheus/Grafana recommended)" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "pbx-availability-check-active_passive_or_active_active_failover", - "group": "pbx-availability", - "module": "pbx", - "action": "check", - "description": "Verify Active-Passive or Active-Active failover transitions correctly on node failure", - "status": "manual", - "file": "tests/pbx/availability.spec.ts", - "manualReason": "Requires HA cluster with 2+ nodes; failover must be triggered by stopping the active node", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires HA cluster with 2+ nodes; failover must be triggered by stopping the active node", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", - "Long-running load or HA failover scenarios need dedicated lab infrastructure" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "Load Gen", - "value": "SIPp or custom load generator + monitoring (Prometheus/Grafana recommended)" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "pbx-availability-check-database_replication_and_sync_integrity", - "group": "pbx-availability", - "module": "pbx", - "action": "check", - "description": "Verify database replication between HA nodes maintains consistency and acceptable lag", - "status": "manual", - "file": "tests/pbx/availability.spec.ts", - "manualReason": "Requires HA database cluster; verifying replication lag needs direct database access", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires HA database cluster; verifying replication lag needs direct database access", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", - "Long-running load or HA failover scenarios need dedicated lab infrastructure" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "Load Gen", - "value": "SIPp or custom load generator + monitoring (Prometheus/Grafana recommended)" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "pbx-availability-check-automatic_failover_and_call_preservation", - "group": "pbx-availability", - "module": "pbx", - "action": "check", - "description": "Verify automatic failover preserves active calls (no drops, no audio interruption > 200ms)", - "status": "manual", - "file": "tests/pbx/availability.spec.ts", - "manualReason": "Requires active call sessions during failover and simultaneous call-state monitoring", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires active call sessions during failover and simultaneous call-state monitoring", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", - "Long-running load or HA failover scenarios need dedicated lab infrastructure" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "Load Gen", - "value": "SIPp or custom load generator + monitoring (Prometheus/Grafana recommended)" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "pbx-availability-check-geographic_redundancy_and_geo_distribution", - "group": "pbx-availability", - "module": "pbx", - "action": "check", - "description": "Verify geo-distributed deployment handles site failover without service interruption", - "status": "manual", - "file": "tests/pbx/availability.spec.ts", - "manualReason": "Requires multi-site infrastructure across geographic locations or WAN simulation", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires multi-site infrastructure across geographic locations or WAN simulation", - "Requires external SIP endpoints or physical phones for media/audio validation", - "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", - "Long-running load or HA failover scenarios need dedicated lab infrastructure" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "Load Gen", - "value": "SIPp or custom load generator + monitoring (Prometheus/Grafana recommended)" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, - { - "id": "pbx-management-check-cli_management", - "group": "pbx-management", - "module": "pbx", - "action": "check", - "description": "Verify CLI management interface is accessible and key management commands execute correctly", - "status": "partial", - "file": "tests/pbx/management.spec.ts", - "partialNotes": "Web console (if present) verified via Playwright; full CLI coverage requires SSH automation integrated in CI pipeline", + "file": "tests/pbx/logs.spec.ts", "steps": [ "Open admin portal or repository URL in browser context", "Execute the main verification or configuration action described in the test", @@ -3621,7 +3419,7 @@ "Data extraction and reporting of current settings" ], "notYet": [ - "Web console (if present) verified via Playwright; full CLI coverage requires SSH automation integrated in CI pipeline", + "QoS metrics display UI automated; actual metric generation requires active call sessions with network impairment", "Requires external SIP endpoints or physical phones for media/audio validation" ], "dependencies": [ @@ -3645,49 +3443,8 @@ "label": "Test Data", "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" } - ] - }, - { - "id": "pbx-management-check-gui_management", - "group": "pbx-management", - "module": "pbx", - "action": "check", - "description": "Verify all main admin portal sections load correctly and management actions are functional", - "status": "automated", - "file": "tests/pbx/management.spec.ts", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" ], - "automatable": [ - "Full end-to-end execution via Playwright against the admin portal UI", - "Navigation, form interaction, and assertions are scriptable" - ], - "notYet": [], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] + "partialNotes": "QoS metrics display UI automated; actual metric generation requires active call sessions with network impairment" }, { "id": "pbx-logs-check-cdr_generation_accuracy_completeness_and_export", @@ -3731,48 +3488,6 @@ } ] }, - { - "id": "pbx-logs-check-real_time_active_call_and_registration_monitoring", - "group": "pbx-logs", - "module": "pbx", - "action": "check", - "description": "Verify real-time monitoring dashboard shows active calls and SIP registrations", - "status": "automated", - "file": "tests/pbx/logs.spec.ts", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" - ], - "automatable": [ - "Full end-to-end execution via Playwright against the admin portal UI", - "Navigation, form interaction, and assertions are scriptable" - ], - "notYet": [], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] - }, { "id": "pbx-logs-check-detailed_logging_levels_rotation_and_search", "group": "pbx-logs", @@ -3815,6 +3530,48 @@ } ] }, + { + "id": "pbx-logs-check-real_time_active_call_and_registration_monitoring", + "group": "pbx-logs", + "module": "pbx", + "action": "check", + "description": "Verify real-time monitoring dashboard shows active calls and SIP registrations", + "status": "automated", + "file": "tests/pbx/logs.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Full end-to-end execution via Playwright against the admin portal UI", + "Navigation, form interaction, and assertions are scriptable" + ], + "notYet": [], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ] + }, { "id": "pbx-logs-check-threshold_alarms_cpu_channels_disk_memory", "group": "pbx-logs", @@ -3858,14 +3615,13 @@ ] }, { - "id": "pbx-logs-check-call_quality_metrics_mos_jitter_loss_per_call", - "group": "pbx-logs", + "id": "pbx-management-check-cli_management", + "group": "pbx-management", "module": "pbx", "action": "check", - "description": "Verify per-call quality metrics (MOS score, jitter, packet loss) are collected and displayed", + "description": "Verify CLI management interface is accessible and key management commands execute correctly", "status": "partial", - "file": "tests/pbx/logs.spec.ts", - "partialNotes": "QoS metrics display UI automated; actual metric generation requires active call sessions with network impairment", + "file": "tests/pbx/management.spec.ts", "steps": [ "Open admin portal or repository URL in browser context", "Execute the main verification or configuration action described in the test", @@ -3877,9 +3633,52 @@ "Data extraction and reporting of current settings" ], "notYet": [ - "QoS metrics display UI automated; actual metric generation requires active call sessions with network impairment", + "Web console (if present) verified via Playwright; full CLI coverage requires SSH automation integrated in CI pipeline", "Requires external SIP endpoints or physical phones for media/audio validation" ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "partialNotes": "Web console (if present) verified via Playwright; full CLI coverage requires SSH automation integrated in CI pipeline" + }, + { + "id": "pbx-management-check-gui_management", + "group": "pbx-management", + "module": "pbx", + "action": "check", + "description": "Verify all main admin portal sections load correctly and management actions are functional", + "status": "automated", + "file": "tests/pbx/management.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Full end-to-end execution via Playwright against the admin portal UI", + "Navigation, form interaction, and assertions are scriptable" + ], + "notYet": [], "dependencies": [ { "label": "Admin Portal", @@ -3903,6 +3702,159 @@ } ] }, + { + "id": "pbx-performance-check-cpu_memory_disk_io_utilization_under_sustained_load", + "group": "pbx-performance", + "module": "pbx", + "action": "check", + "description": "Verify CPU, memory, and disk I/O remain within limits under sustained call load", + "status": "manual", + "file": "tests/pbx/performance.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires SIPp load generator, server-side performance monitoring, and dedicated test environment", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", + "Long-running load or HA failover scenarios need dedicated lab infrastructure" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "Load Gen", + "value": "SIPp or custom load generator + monitoring (Prometheus/Grafana recommended)" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires SIPp load generator, server-side performance monitoring, and dedicated test environment" + }, + { + "id": "pbx-performance-check-long_duration_stability_72h_test", + "group": "pbx-performance", + "module": "pbx", + "action": "check", + "description": "Verify system stability under continuous call load over a 72-hour period", + "status": "manual", + "file": "tests/pbx/performance.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "72-hour test requires dedicated environment, SIPp continuous load, and automated monitoring with alerting", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", + "Long-running load or HA failover scenarios need dedicated lab infrastructure" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "Load Gen", + "value": "SIPp or custom load generator + monitoring (Prometheus/Grafana recommended)" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "72-hour test requires dedicated environment, SIPp continuous load, and automated monitoring with alerting" + }, + { + "id": "pbx-performance-check-memory_leak_and_resource_cleanup_detection", + "group": "pbx-performance", + "module": "pbx", + "action": "check", + "description": "Detect memory leaks and verify proper resource cleanup over extended operation", + "status": "manual", + "file": "tests/pbx/performance.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires extended monitoring with active call load and memory profiling tools (Valgrind, heap dumps)", + "Requires external SIP endpoints or physical phones for media/audio validation", + "Hypervisor-level operations (vCenter, libvirt, vSphere) not reachable from browser automation", + "Long-running load or HA failover scenarios need dedicated lab infrastructure" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "Load Gen", + "value": "SIPp or custom load generator + monitoring (Prometheus/Grafana recommended)" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires extended monitoring with active call load and memory profiling tools (Valgrind, heap dumps)" + }, { "id": "pbx-regression-check-core_call_features_after_any_code_change", "group": "pbx-regression", @@ -3911,7 +3863,6 @@ "description": "Run regression checks on core features after any code change to detect regressions", "status": "partial", "file": "tests/pbx/regression.spec.ts", - "partialNotes": "Admin portal regression automated; call-flow regression (inbound/outbound/hold/transfer) requires SIP endpoints", "steps": [ "Open admin portal or repository URL in browser context", "Execute the main verification or configuration action described in the test", @@ -3947,7 +3898,53 @@ "label": "Test Data", "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" } - ] + ], + "partialNotes": "Admin portal regression automated; call-flow regression (inbound/outbound/hold/transfer) requires SIP endpoints" + }, + { + "id": "pbx-regression-check-performance_baselines_comparison_against_previous_version", + "group": "pbx-regression", + "module": "pbx", + "action": "check", + "description": "Compare key performance metrics against baselines from the previous version", + "status": "manual", + "file": "tests/pbx/regression.spec.ts", + "steps": [ + "Open admin portal or repository URL in browser context", + "Execute the main verification or configuration action described in the test", + "Capture evidence (screenshot, log, API response)", + "Assert expected outcome" + ], + "automatable": [ + "Most UI-driven configuration and verification steps via Playwright" + ], + "notYet": [ + "Requires SIPp load tests and statistical comparison of results against previous version baseline", + "Requires external SIP endpoints or physical phones for media/audio validation" + ], + "dependencies": [ + { + "label": "Admin Portal", + "value": "https://pbx.local:4443 (configure via $BASE_URL)" + }, + { + "label": "Repository URL", + "value": "${BASE_URL}/downloads or $REPO_URL" + }, + { + "label": "Protocol", + "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" + }, + { + "label": "Credentials", + "value": "Admin user with sufficient privileges (portal + SSH where needed)" + }, + { + "label": "Test Data", + "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" + } + ], + "manualReason": "Requires SIPp load tests and statistical comparison of results against previous version baseline" }, { "id": "pbx-regression-check-previously_fixed_bugs_and_edge_cases_reverification", @@ -3957,7 +3954,6 @@ "description": "Verify all previously fixed bugs and known edge cases have not regressed", "status": "partial", "file": "tests/pbx/regression.spec.ts", - "partialNotes": "UI bug regressions automated; telephony-layer bug regressions require SIP client or SSH verification", "steps": [ "Open admin portal or repository URL in browser context", "Execute the main verification or configuration action described in the test", @@ -3993,52 +3989,8 @@ "label": "Test Data", "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" } - ] - }, - { - "id": "pbx-regression-check-performance_baselines_comparison_against_previous_version", - "group": "pbx-regression", - "module": "pbx", - "action": "check", - "description": "Compare key performance metrics against baselines from the previous version", - "status": "manual", - "file": "tests/pbx/regression.spec.ts", - "manualReason": "Requires SIPp load tests and statistical comparison of results against previous version baseline", - "steps": [ - "Open admin portal or repository URL in browser context", - "Execute the main verification or configuration action described in the test", - "Capture evidence (screenshot, log, API response)", - "Assert expected outcome" ], - "automatable": [ - "Most UI-driven configuration and verification steps via Playwright" - ], - "notYet": [ - "Requires SIPp load tests and statistical comparison of results against previous version baseline", - "Requires external SIP endpoints or physical phones for media/audio validation" - ], - "dependencies": [ - { - "label": "Admin Portal", - "value": "https://pbx.local:4443 (configure via $BASE_URL)" - }, - { - "label": "Repository URL", - "value": "${BASE_URL}/downloads or $REPO_URL" - }, - { - "label": "Protocol", - "value": "HTTPS + SIP (UDP/TCP/TLS) + RTP/SRTP" - }, - { - "label": "Credentials", - "value": "Admin user with sufficient privileges (portal + SSH where needed)" - }, - { - "label": "Test Data", - "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" - } - ] + "partialNotes": "UI bug regressions automated; telephony-layer bug regressions require SIP client or SSH verification" }, { "id": "pbx-regression-check-security_hardening_and_vulnerability_scan_baseline", @@ -4048,7 +4000,6 @@ "description": "Verify security hardening settings and compare vulnerability scan baseline against previous version", "status": "partial", "file": "tests/pbx/regression.spec.ts", - "partialNotes": "Security config checks via portal automated; full CVE scan baseline requires Trivy/OpenVAS in CI pipeline", "steps": [ "Open admin portal or repository URL in browser context", "Execute the main verification or configuration action described in the test", @@ -4085,6 +4036,7 @@ "label": "Test Data", "value": "Clean test tenant or lab PBX instance (recommended isolated environment)" } - ] + ], + "partialNotes": "Security config checks via portal automated; full CVE scan baseline requires Trivy/OpenVAS in CI pipeline" } ] \ No newline at end of file diff --git a/node_modules/.bin/js-yaml b/node_modules/.bin/js-yaml new file mode 120000 index 0000000..9dbd010 --- /dev/null +++ b/node_modules/.bin/js-yaml @@ -0,0 +1 @@ +../js-yaml/bin/js-yaml.js \ No newline at end of file diff --git a/editor/node_modules/.bin/mime b/node_modules/.bin/mime similarity index 100% rename from editor/node_modules/.bin/mime rename to node_modules/.bin/mime diff --git a/node_modules/.bin/playwright b/node_modules/.bin/playwright new file mode 120000 index 0000000..c30d07f --- /dev/null +++ b/node_modules/.bin/playwright @@ -0,0 +1 @@ +../@playwright/test/cli.js \ No newline at end of file diff --git a/node_modules/.bin/playwright-core b/node_modules/.bin/playwright-core new file mode 120000 index 0000000..08d6c28 --- /dev/null +++ b/node_modules/.bin/playwright-core @@ -0,0 +1 @@ +../playwright-core/cli.js \ No newline at end of file diff --git a/node_modules/.bin/tsc b/node_modules/.bin/tsc new file mode 120000 index 0000000..0863208 --- /dev/null +++ b/node_modules/.bin/tsc @@ -0,0 +1 @@ +../typescript/bin/tsc \ No newline at end of file diff --git a/node_modules/.bin/tsserver b/node_modules/.bin/tsserver new file mode 120000 index 0000000..f8f8f1a --- /dev/null +++ b/node_modules/.bin/tsserver @@ -0,0 +1 @@ +../typescript/bin/tsserver \ No newline at end of file diff --git a/editor/node_modules/.package-lock.json b/node_modules/.package-lock.json similarity index 88% rename from editor/node_modules/.package-lock.json rename to node_modules/.package-lock.json index ea437b6..d0df699 100644 --- a/editor/node_modules/.package-lock.json +++ b/node_modules/.package-lock.json @@ -1,9 +1,35 @@ { - "name": "test-plan-editor", - "version": "0.1.0", + "name": "pbx-autotest", + "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { + "node_modules/@playwright/test": { + "version": "1.60.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.60.0.tgz", + "integrity": "sha512-O71yZIbAh/PxDMNGns37GHBIfrVkEVyn+AXyIa5dOTfb4/xNvRWV+Vv/NMbNCtODB/pO7vLlF2OTmMVLhmr7Ag==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.60.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@types/node": { + "version": "22.19.19", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.19.tgz", + "integrity": "sha512-dyh/xO2Fh5bYrfWaaqGrRQQGkNdmYw6AmaAUvYeUMNTWQtvb796ikLdmTchRmOlOiIJ1TDXfWgVx1QkUlQ6Hew==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, "node_modules/accepts": { "version": "1.3.8", "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", @@ -17,6 +43,12 @@ "node": ">= 0.6" } }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "license": "Python-2.0" + }, "node_modules/array-flatten": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", @@ -166,6 +198,19 @@ "npm": "1.2.8000 || >= 1.4.16" } }, + "node_modules/dotenv": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, "node_modules/dunder-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", @@ -214,9 +259,9 @@ } }, "node_modules/es-object-atoms": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", - "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", "license": "MIT", "dependencies": { "es-errors": "^1.3.0" @@ -451,6 +496,18 @@ "node": ">= 0.10" } }, + "node_modules/js-yaml": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", + "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -583,6 +640,38 @@ "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==", "license": "MIT" }, + "node_modules/playwright": { + "version": "1.60.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.60.0.tgz", + "integrity": "sha512-hheHdokM8cdqCb0lcE3s+zT4t4W+vvjpGxsZlDnikarzx8tSzMebh3UiFtgqwFwnTnjYQcsyMF8ei2mCO/tpeA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.60.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.60.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.60.0.tgz", + "integrity": "sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/proxy-addr": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", @@ -815,6 +904,27 @@ "node": ">= 0.6" } }, + "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": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, "node_modules/unpipe": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", diff --git a/node_modules/@playwright/test/LICENSE b/node_modules/@playwright/test/LICENSE new file mode 100644 index 0000000..df11237 --- /dev/null +++ b/node_modules/@playwright/test/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Portions Copyright (c) Microsoft Corporation. + Portions Copyright 2017 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@playwright/test/NOTICE b/node_modules/@playwright/test/NOTICE new file mode 100644 index 0000000..814ec16 --- /dev/null +++ b/node_modules/@playwright/test/NOTICE @@ -0,0 +1,5 @@ +Playwright +Copyright (c) Microsoft Corporation + +This software contains code derived from the Puppeteer project (https://github.com/puppeteer/puppeteer), +available under the Apache 2.0 license (https://github.com/puppeteer/puppeteer/blob/master/LICENSE). diff --git a/node_modules/@playwright/test/README.md b/node_modules/@playwright/test/README.md new file mode 100644 index 0000000..17feb3c --- /dev/null +++ b/node_modules/@playwright/test/README.md @@ -0,0 +1,318 @@ +# 🎭 Playwright + +[![npm version](https://img.shields.io/npm/v/playwright.svg)](https://www.npmjs.com/package/playwright) [![Chromium version](https://img.shields.io/badge/chromium-148.0.7778.96-blue.svg?logo=google-chrome)](https://www.chromium.org/Home) [![Firefox version](https://img.shields.io/badge/firefox-150.0.2-blue.svg?logo=firefoxbrowser)](https://www.mozilla.org/en-US/firefox/new/) [![WebKit version](https://img.shields.io/badge/webkit-26.4-blue.svg?logo=safari)](https://webkit.org/) [![Join Discord](https://img.shields.io/badge/join-discord-informational)](https://aka.ms/playwright/discord) + +## [Documentation](https://playwright.dev) | [API reference](https://playwright.dev/docs/api/class-playwright) + +Playwright is a framework for web automation and testing. It drives Chromium, Firefox, and WebKit with a single API — in your tests, in your scripts, and as a tool for AI agents. + +## Get Started + +Choose the path that fits your workflow: + +| | Best for | Install | +|---|---|---| +| **[Playwright Test](#playwright-test)** | End-to-end testing | `npm init playwright@latest` | +| **[Playwright CLI](#playwright-cli)** | Coding agents (Claude Code, Copilot) | `npm i -g @playwright/cli@latest` | +| **[Playwright MCP](#playwright-mcp)** | AI agents and LLM-driven automation | `npx @playwright/mcp@latest` | +| **[Playwright Library](#playwright-library)** | Browser automation scripts | `npm i playwright` | +| **[VS Code Extension](#vs-code-extension)** | Test authoring and debugging in VS Code | [Install from Marketplace](https://marketplace.visualstudio.com/items?itemName=ms-playwright.playwright) | + +--- + +## Playwright Test + +Playwright Test is a full-featured test runner built for end-to-end testing. It runs tests across Chromium, Firefox, and WebKit with full browser isolation, auto-waiting, and web-first assertions. + +### Install + +```bash +npm init playwright@latest +``` + +Or add manually: + +```bash +npm i -D @playwright/test +npx playwright install +``` + +### Write a test + +```TypeScript +import { test, expect } from '@playwright/test'; + +test('has title', async ({ page }) => { + await page.goto('https://playwright.dev/'); + await expect(page).toHaveTitle(/Playwright/); +}); + +test('get started link', async ({ page }) => { + await page.goto('https://playwright.dev/'); + await page.getByRole('link', { name: 'Get started' }).click(); + await expect(page.getByRole('heading', { name: 'Installation' })).toBeVisible(); +}); +``` + +### Run tests + +```bash +npx playwright test +``` + +Tests run in parallel across all configured browsers, in headless mode by default. Each test gets a fresh browser context — full isolation with near-zero overhead. + +### Key capabilities + +**Auto-wait and web-first assertions.** No artificial timeouts. Playwright waits for elements to be actionable, and assertions automatically retry until conditions are met. + +**Locators.** Find elements with resilient locators that mirror how users see the page: + +```TypeScript +page.getByRole('button', { name: 'Submit' }) +page.getByLabel('Email') +page.getByPlaceholder('Search...') +page.getByTestId('login-form') +``` + +**Test isolation.** Each test runs in its own browser context — equivalent to a fresh browser profile. Save authentication state once and reuse it across tests: + +```TypeScript +// Save state after login +await page.context().storageState({ path: 'auth.json' }); + +// Reuse in other tests +test.use({ storageState: 'auth.json' }); +``` + +**Tracing.** Capture execution traces, screenshots, and videos on failure. Inspect every action, DOM snapshot, network request, and console message in the [Trace Viewer](https://playwright.dev/docs/trace-viewer): + +```TypeScript +// playwright.config.ts +export default defineConfig({ + use: { + trace: 'on-first-retry', + }, +}); +``` + +```bash +npx playwright show-trace trace.zip +``` + + + +**Parallelism.** Tests run in parallel by default across all configured browsers. + +[Full testing documentation](https://playwright.dev/docs/intro) + +--- + +## Playwright CLI + +[Playwright CLI](https://github.com/microsoft/playwright-cli) is a command-line interface for browser automation designed for coding agents. It's more token-efficient than MCP — commands avoid loading large tool schemas and accessibility trees into the model context. + +### Install + +```bash +npm install -g @playwright/cli@latest +``` + +Optionally install skills for richer agent integration: + +```bash +playwright-cli install --skills +``` + +### Usage + +Point your coding agent at a task: + +``` +Test the "add todo" flow on https://demo.playwright.dev/todomvc using playwright-cli. +Take screenshots for all successful and failing scenarios. +``` + +Or run commands directly: + +```bash +playwright-cli open https://demo.playwright.dev/todomvc/ --headed +playwright-cli type "Buy groceries" +playwright-cli press Enter +playwright-cli screenshot +``` + +### Session monitoring + +Use `playwright-cli show` to open a visual dashboard with live screencast previews of all running browser sessions. Click any session to zoom in and take remote control. + +```bash +playwright-cli show +``` + + + +[Full CLI documentation](https://playwright.dev/docs/cli-agent) | [GitHub](https://github.com/microsoft/playwright-cli) + +--- + +## Playwright MCP + +The [Playwright MCP server](https://github.com/microsoft/playwright-mcp) gives AI agents full browser control through the [Model Context Protocol](https://modelcontextprotocol.io). Agents interact with pages using structured accessibility snapshots — no vision models or screenshots required. + +### Setup + +Add to your MCP client (VS Code, Cursor, Claude Desktop, Windsurf, etc.): + +```json +{ + "mcpServers": { + "playwright": { + "command": "npx", + "args": ["@playwright/mcp@latest"] + } + } +} +``` + +**One-click install for VS Code:** + +[Install in VS Code](https://insiders.vscode.dev/redirect?url=vscode%3Amcp%2Finstall%3F%257B%2522name%2522%253A%2522playwright%2522%252C%2522command%2522%253A%2522npx%2522%252C%2522args%2522%253A%255B%2522%2540playwright%252Fmcp%2540latest%2522%255D%257D) + +**For Claude Code:** + +```bash +claude mcp add playwright npx @playwright/mcp@latest +``` + +### How it works + +Ask your AI assistant to interact with any web page: + +``` +Navigate to https://demo.playwright.dev/todomvc and add a few todo items. +``` + +The agent sees the page as a structured accessibility tree: + +``` +- heading "todos" [level=1] +- textbox "What needs to be done?" [ref=e5] +- listitem: + - checkbox "Toggle Todo" [ref=e10] + - text: "Buy groceries" +``` + +It uses element refs like `e5` and `e10` to click, type, and interact — deterministically and without visual ambiguity. Tools cover navigation, form filling, screenshots, network mocking, storage management, and more. + +[Full MCP documentation](https://playwright.dev/docs/mcp) | [GitHub](https://github.com/microsoft/playwright-mcp) + +--- + +## Playwright Library + +Use `playwright` as a library for browser automation scripts — web scraping, PDF generation, screenshot capture, and any workflow that needs programmatic browser control without a test runner. + +### Install + +```bash +npm i playwright +``` + +### Examples + +**Take a screenshot:** + +```TypeScript +import { chromium } from 'playwright'; + +const browser = await chromium.launch(); +const page = await browser.newPage(); +await page.goto('https://playwright.dev/'); +await page.screenshot({ path: 'screenshot.png' }); +await browser.close(); +``` + +**Generate a PDF:** + +```TypeScript +import { chromium } from 'playwright'; + +const browser = await chromium.launch(); +const page = await browser.newPage(); +await page.goto('https://playwright.dev/'); +await page.pdf({ path: 'page.pdf', format: 'A4' }); +await browser.close(); +``` + +**Emulate a mobile device:** + +```TypeScript +import { chromium, devices } from 'playwright'; + +const browser = await chromium.launch(); +const context = await browser.newContext(devices['iPhone 15']); +const page = await context.newPage(); +await page.goto('https://playwright.dev/'); +await page.screenshot({ path: 'mobile.png' }); +await browser.close(); +``` + +**Intercept network requests:** + +```TypeScript +import { chromium } from 'playwright'; + +const browser = await chromium.launch(); +const page = await browser.newPage(); +await page.route('**/*.{png,jpg,jpeg}', route => route.abort()); +await page.goto('https://playwright.dev/'); +await browser.close(); +``` + +[Library documentation](https://playwright.dev/docs/library) | [API reference](https://playwright.dev/docs/api/class-playwright) + +--- + +## VS Code Extension + +The [Playwright VS Code extension](https://marketplace.visualstudio.com/items?itemName=ms-playwright.playwright) brings test running, debugging, and code generation directly into your editor. + + + +**Run and debug tests** from the editor with a single click. Set breakpoints, inspect variables, and step through test execution with a live browser view. + +**Generate tests with CodeGen.** Click "Record new" to open a browser — navigate and interact with your app while Playwright writes the test code for you. + +**Pick locators.** Hover over any element in the browser to see the best available locator, then click to copy it to your clipboard. + +**Trace Viewer integration.** Enable "Show Trace Viewer" in the sidebar to get a full execution trace after each test run — DOM snapshots, network requests, console logs, and screenshots at every step. + +[Install the extension](https://marketplace.visualstudio.com/items?itemName=ms-playwright.playwright) | [VS Code guide](https://playwright.dev/docs/getting-started-vscode) + +--- + +## Cross-Browser Support + +| | Linux | macOS | Windows | +| :--- | :---: | :---: | :---: | +| Chromium1 148.0.7778.96 | :white_check_mark: | :white_check_mark: | :white_check_mark: | +| WebKit 26.4 | :white_check_mark: | :white_check_mark: | :white_check_mark: | +| Firefox 150.0.2 | :white_check_mark: | :white_check_mark: | :white_check_mark: | + +Headless and headed execution on all platforms. 1 Uses [Chrome for Testing](https://developer.chrome.com/blog/chrome-for-testing) by default. + +## Other Languages + +Playwright is also available for [Python](https://playwright.dev/python/docs/intro), [.NET](https://playwright.dev/dotnet/docs/intro), and [Java](https://playwright.dev/java/docs/intro). + +## Resources + +* [Documentation](https://playwright.dev) +* [API reference](https://playwright.dev/docs/api/class-playwright) +* [MCP server](https://github.com/microsoft/playwright-mcp) +* [CLI for coding agents](https://github.com/microsoft/playwright-cli) +* [VS Code extension](https://github.com/microsoft/playwright-vscode) +* [Contribution guide](CONTRIBUTING.md) +* [Changelog](https://github.com/microsoft/playwright/releases) +* [Discord](https://aka.ms/playwright/discord) diff --git a/node_modules/@playwright/test/cli.js b/node_modules/@playwright/test/cli.js new file mode 100755 index 0000000..e42facb --- /dev/null +++ b/node_modules/@playwright/test/cli.js @@ -0,0 +1,19 @@ +#!/usr/bin/env node +/** + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const { program } = require('playwright/lib/program'); +program.parse(process.argv); diff --git a/node_modules/@playwright/test/index.d.ts b/node_modules/@playwright/test/index.d.ts new file mode 100644 index 0000000..8d99c91 --- /dev/null +++ b/node_modules/@playwright/test/index.d.ts @@ -0,0 +1,18 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export * from 'playwright/test'; +export { default } from 'playwright/test'; diff --git a/node_modules/@playwright/test/index.js b/node_modules/@playwright/test/index.js new file mode 100644 index 0000000..8536f06 --- /dev/null +++ b/node_modules/@playwright/test/index.js @@ -0,0 +1,17 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +module.exports = require('playwright/test'); diff --git a/node_modules/@playwright/test/index.mjs b/node_modules/@playwright/test/index.mjs new file mode 100644 index 0000000..8d99c91 --- /dev/null +++ b/node_modules/@playwright/test/index.mjs @@ -0,0 +1,18 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export * from 'playwright/test'; +export { default } from 'playwright/test'; diff --git a/node_modules/@playwright/test/package.json b/node_modules/@playwright/test/package.json new file mode 100644 index 0000000..2898afa --- /dev/null +++ b/node_modules/@playwright/test/package.json @@ -0,0 +1,35 @@ +{ + "name": "@playwright/test", + "version": "1.60.0", + "description": "A high-level API to automate web browsers", + "repository": { + "type": "git", + "url": "git+https://github.com/microsoft/playwright.git" + }, + "homepage": "https://playwright.dev", + "engines": { + "node": ">=18" + }, + "author": { + "name": "Microsoft Corporation" + }, + "license": "Apache-2.0", + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./index.mjs", + "require": "./index.js", + "default": "./index.js" + }, + "./cli": "./cli.js", + "./package.json": "./package.json", + "./reporter": "./reporter.js" + }, + "bin": { + "playwright": "cli.js" + }, + "scripts": {}, + "dependencies": { + "playwright": "1.60.0" + } +} diff --git a/node_modules/@playwright/test/reporter.d.ts b/node_modules/@playwright/test/reporter.d.ts new file mode 100644 index 0000000..806d13f --- /dev/null +++ b/node_modules/@playwright/test/reporter.d.ts @@ -0,0 +1,17 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export * from 'playwright/types/testReporter'; diff --git a/node_modules/@playwright/test/reporter.js b/node_modules/@playwright/test/reporter.js new file mode 100644 index 0000000..485e880 --- /dev/null +++ b/node_modules/@playwright/test/reporter.js @@ -0,0 +1,17 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// We only export types in reporter.d.ts. diff --git a/node_modules/@playwright/test/reporter.mjs b/node_modules/@playwright/test/reporter.mjs new file mode 100644 index 0000000..485e880 --- /dev/null +++ b/node_modules/@playwright/test/reporter.mjs @@ -0,0 +1,17 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// We only export types in reporter.d.ts. diff --git a/node_modules/@types/node/LICENSE b/node_modules/@types/node/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/node/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/node/README.md b/node_modules/@types/node/README.md new file mode 100644 index 0000000..c76e77c --- /dev/null +++ b/node_modules/@types/node/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for node (https://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node/v22. + +### Additional Details + * Last updated: Mon, 11 May 2026 22:25:21 GMT + * Dependencies: [undici-types](https://npmjs.com/package/undici-types) + +# Credits +These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [Alberto Schiabel](https://github.com/jkomyno), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [David Junger](https://github.com/touffy), [Mohsen Azimi](https://github.com/mohsen1), [Nikita Galkin](https://github.com/galkin), [Sebastian Silbermann](https://github.com/eps1lon), [Wilco Bakker](https://github.com/WilcoBakker), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), [Dmitry Semigradsky](https://github.com/Semigradsky), and [René](https://github.com/Renegade334). diff --git a/node_modules/@types/node/assert.d.ts b/node_modules/@types/node/assert.d.ts new file mode 100644 index 0000000..330d860 --- /dev/null +++ b/node_modules/@types/node/assert.d.ts @@ -0,0 +1,1078 @@ +/** + * The `node:assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/assert.js) + */ +declare module "assert" { + import strict = require("assert/strict"); + /** + * An alias of {@link assert.ok}. + * @since v0.5.9 + * @param value The input that is checked for being truthy. + */ + function assert(value: unknown, message?: string | Error): asserts value; + const kOptions: unique symbol; + namespace assert { + type AssertMethodNames = + | "deepEqual" + | "deepStrictEqual" + | "doesNotMatch" + | "doesNotReject" + | "doesNotThrow" + | "equal" + | "fail" + | "ifError" + | "match" + | "notDeepEqual" + | "notDeepStrictEqual" + | "notEqual" + | "notStrictEqual" + | "ok" + | "partialDeepStrictEqual" + | "rejects" + | "strictEqual" + | "throws"; + interface AssertOptions { + /** + * If set to `'full'`, shows the full diff in assertion errors. + * @default 'simple' + */ + diff?: "simple" | "full" | undefined; + /** + * If set to `true`, non-strict methods behave like their + * corresponding strict methods. + * @default true + */ + strict?: boolean | undefined; + } + interface Assert extends Pick { + readonly [kOptions]: AssertOptions & { strict: false }; + } + interface AssertStrict extends Pick { + readonly [kOptions]: AssertOptions & { strict: true }; + } + /** + * The `Assert` class allows creating independent assertion instances with custom options. + * @since v22.19.0 + */ + var Assert: { + /** + * Creates a new assertion instance. The `diff` option controls the verbosity of diffs in assertion error messages. + * + * ```js + * const { Assert } = require('node:assert'); + * const assertInstance = new Assert({ diff: 'full' }); + * assertInstance.deepStrictEqual({ a: 1 }, { a: 2 }); + * // Shows a full diff in the error message. + * ``` + * + * **Important**: When destructuring assertion methods from an `Assert` instance, + * the methods lose their connection to the instance's configuration options (such as `diff` and `strict` settings). + * The destructured methods will fall back to default behavior instead. + * + * ```js + * const myAssert = new Assert({ diff: 'full' }); + * + * // This works as expected - uses 'full' diff + * myAssert.strictEqual({ a: 1 }, { b: { c: 1 } }); + * + * // This loses the 'full' diff setting - falls back to default 'simple' diff + * const { strictEqual } = myAssert; + * strictEqual({ a: 1 }, { b: { c: 1 } }); + * ``` + * + * When destructured, methods lose access to the instance's `this` context and revert to default assertion behavior + * (diff: 'simple', non-strict mode). + * To maintain custom options when using destructured methods, avoid + * destructuring and call methods directly on the instance. + * @since v22.19.0 + */ + new( + options?: AssertOptions & { strict?: true }, + ): AssertStrict; + new( + options: AssertOptions, + ): Assert; + }; + interface AssertionErrorOptions { + /** + * If provided, the error message is set to this value. + */ + message?: string | undefined; + /** + * The `actual` property on the error instance. + */ + actual?: unknown; + /** + * The `expected` property on the error instance. + */ + expected?: unknown; + /** + * The `operator` property on the error instance. + */ + operator?: string | undefined; + /** + * If provided, the generated stack trace omits frames before this function. + */ + stackStartFn?: Function | undefined; + /** + * If set to `'full'`, shows the full diff in assertion errors. + * @default 'simple' + */ + diff?: "simple" | "full" | undefined; + } + /** + * Indicates the failure of an assertion. All errors thrown by the `node:assert` module will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + constructor(options: AssertionErrorOptions); + /** + * Set to the `actual` argument for methods such as {@link assert.strictEqual()}. + */ + actual: unknown; + /** + * Set to the `expected` argument for methods such as {@link assert.strictEqual()}. + */ + expected: unknown; + /** + * Indicates if the message was auto-generated (`true`) or not. + */ + generatedMessage: boolean; + /** + * Value is always `ERR_ASSERTION` to show that the error is an assertion error. + */ + code: "ERR_ASSERTION"; + /** + * Set to the passed in operator value. + */ + operator: string; + } + /** + * This feature is deprecated and will be removed in a future version. + * Please consider using alternatives such as the `mock` helper function. + * @since v14.2.0, v12.19.0 + * @deprecated Deprecated + */ + class CallTracker { + /** + * The wrapper function is expected to be called exactly `exact` times. If the + * function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an + * error. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func); + * ``` + * @since v14.2.0, v12.19.0 + * @param [fn='A no-op function'] + * @param [exact=1] + * @return A function that wraps `fn`. + */ + calls(exact?: number): () => void; + calls any>(fn?: Func, exact?: number): Func; + /** + * Example: + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * callsfunc(1, 2, 3); + * + * assert.deepStrictEqual(tracker.getCalls(callsfunc), + * [{ thisArg: undefined, arguments: [1, 2, 3] }]); + * ``` + * @since v18.8.0, v16.18.0 + * @return An array with all the calls to a tracked function. + */ + getCalls(fn: Function): CallTrackerCall[]; + /** + * The arrays contains information about the expected and actual number of calls of + * the functions that have not been called the expected number of times. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * // Returns an array containing information on callsfunc() + * console.log(tracker.report()); + * // [ + * // { + * // message: 'Expected the func function to be executed 2 time(s) but was + * // executed 0 time(s).', + * // actual: 0, + * // expected: 2, + * // operator: 'func', + * // stack: stack trace + * // } + * // ] + * ``` + * @since v14.2.0, v12.19.0 + * @return An array of objects containing information about the wrapper functions returned by {@link tracker.calls()}. + */ + report(): CallTrackerReportInformation[]; + /** + * Reset calls of the call tracker. If a tracked function is passed as an argument, the calls will be reset for it. + * If no arguments are passed, all tracked functions will be reset. + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * + * callsfunc(); + * // Tracker was called once + * assert.strictEqual(tracker.getCalls(callsfunc).length, 1); + * + * tracker.reset(callsfunc); + * assert.strictEqual(tracker.getCalls(callsfunc).length, 0); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn a tracked function to reset. + */ + reset(fn?: Function): void; + /** + * Iterates through the list of functions passed to {@link tracker.calls()} and will throw an error for functions that + * have not been called the expected number of times. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * callsfunc(); + * + * // Will throw an error since callsfunc() was only called once. + * tracker.verify(); + * ``` + * @since v14.2.0, v12.19.0 + */ + verify(): void; + } + interface CallTrackerCall { + thisArg: object; + arguments: unknown[]; + } + interface CallTrackerReportInformation { + message: string; + /** The actual number of times the function was called. */ + actual: number; + /** The number of times the function was expected to be called. */ + expected: number; + /** The name of the function that is wrapped. */ + operator: string; + /** A stack trace of the function. */ + stack: object; + } + type AssertPredicate = RegExp | (new() => object) | ((thrown: unknown) => boolean) | object | Error; + /** + * Throws an `AssertionError` with the provided error message or a default + * error message. If the `message` parameter is an instance of an `Error` then + * it will be thrown instead of the `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.fail(); + * // AssertionError [ERR_ASSERTION]: Failed + * + * assert.fail('boom'); + * // AssertionError [ERR_ASSERTION]: boom + * + * assert.fail(new TypeError('need array')); + * // TypeError: need array + * ``` + * + * Using `assert.fail()` with more than two arguments is possible but deprecated. + * See below for further details. + * @since v0.1.21 + * @param [message='Failed'] + */ + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: unknown, + expected: unknown, + message?: string | Error, + operator?: string, + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + stackStartFn?: Function, + ): never; + /** + * Tests if `value` is truthy. It is equivalent to `assert.equal(!!value, true, message)`. + * + * If `value` is not truthy, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is `undefined`, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. + * + * Be aware that in the `repl` the error message will be different to the one + * thrown in a file! See below for further details. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ok(true); + * // OK + * assert.ok(1); + * // OK + * + * assert.ok(); + * // AssertionError: No value argument passed to `assert.ok()` + * + * assert.ok(false, 'it\'s false'); + * // AssertionError: it's false + * + * // In the repl: + * assert.ok(typeof 123 === 'string'); + * // AssertionError: false == true + * + * // In a file (e.g. test.js): + * assert.ok(typeof 123 === 'string'); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(typeof 123 === 'string') + * + * assert.ok(false); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(false) + * + * assert.ok(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(0) + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * // Using `assert()` works the same: + * assert(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert(0) + * ``` + * @since v0.1.21 + */ + function ok(value: unknown, message?: string | Error): asserts value; + /** + * **Strict assertion mode** + * + * An alias of {@link strictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link strictEqual} instead. + * + * Tests shallow, coercive equality between the `actual` and `expected` parameters + * using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled + * and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.equal(1, 1); + * // OK, 1 == 1 + * assert.equal(1, '1'); + * // OK, 1 == '1' + * assert.equal(NaN, NaN); + * // OK + * + * assert.equal(1, 2); + * // AssertionError: 1 == 2 + * assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); + * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } + * ``` + * + * If the values are not equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v0.1.21 + */ + function equal(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. + * + * Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is + * specially handled and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.notEqual(1, 2); + * // OK + * + * assert.notEqual(1, 1); + * // AssertionError: 1 != 1 + * + * assert.notEqual(1, '1'); + * // AssertionError: 1 != '1' + * ``` + * + * If the values are equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default error + * message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v0.1.21 + */ + function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link deepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. + * + * Tests for deep equality between the `actual` and `expected` parameters. Consider + * using {@link deepStrictEqual} instead. {@link deepEqual} can have + * surprising results. + * + * _Deep equality_ means that the enumerable "own" properties of child objects + * are also recursively evaluated by the following rules. + * @since v0.1.21 + */ + function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notDeepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. + * + * Tests for any deep inequality. Opposite of {@link deepEqual}. + * + * ```js + * import assert from 'node:assert'; + * + * const obj1 = { + * a: { + * b: 1, + * }, + * }; + * const obj2 = { + * a: { + * b: 2, + * }, + * }; + * const obj3 = { + * a: { + * b: 1, + * }, + * }; + * const obj4 = { __proto__: obj1 }; + * + * assert.notDeepEqual(obj1, obj1); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj2); + * // OK + * + * assert.notDeepEqual(obj1, obj3); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj4); + * // OK + * ``` + * + * If the values are deeply equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests strict equality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.strictEqual(1, 2); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + * // 1 !== 2 + * + * assert.strictEqual(1, 1); + * // OK + * + * assert.strictEqual('Hello foobar', 'Hello World!'); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + actual - expected + * // + * // + 'Hello foobar' + * // - 'Hello World!' + * // ^ + * + * const apples = 1; + * const oranges = 2; + * assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); + * // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 + * + * assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); + * // TypeError: Inputs are not identical + * ``` + * + * If the values are not strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a + * default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function strictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests strict inequality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notStrictEqual(1, 2); + * // OK + * + * assert.notStrictEqual(1, 1); + * // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: + * // + * // 1 + * + * assert.notStrictEqual(1, '1'); + * // OK + * ``` + * + * If the values are strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a + * default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests for deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. + * @since v1.2.0 + */ + function deepStrictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); + * // OK + * ``` + * + * If the values are deeply and strictly equal, an `AssertionError` is thrown + * with a `message` property set equal to the value of the `message` parameter. If + * the `message` parameter is undefined, a default error message is assigned. If + * the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v1.2.0 + */ + function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Expects the function `fn` to throw an error. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * a validation object where each property will be tested for strict deep equality, + * or an instance of error where each property will be tested for strict deep + * equality including the non-enumerable `message` and `name` properties. When + * using an object, it is also possible to use a regular expression, when + * validating against a string property. See below for examples. + * + * If specified, `message` will be appended to the message provided by the `AssertionError` if the `fn` call fails to throw or in case the error validation + * fails. + * + * Custom validation object/error instance: + * + * ```js + * import assert from 'node:assert/strict'; + * + * const err = new TypeError('Wrong value'); + * err.code = 404; + * err.foo = 'bar'; + * err.info = { + * nested: true, + * baz: 'text', + * }; + * err.reg = /abc/i; + * + * assert.throws( + * () => { + * throw err; + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * info: { + * nested: true, + * baz: 'text', + * }, + * // Only properties on the validation object will be tested for. + * // Using nested objects requires all properties to be present. Otherwise + * // the validation is going to fail. + * }, + * ); + * + * // Using regular expressions to validate error properties: + * assert.throws( + * () => { + * throw err; + * }, + * { + * // The `name` and `message` properties are strings and using regular + * // expressions on those will match against the string. If they fail, an + * // error is thrown. + * name: /^TypeError$/, + * message: /Wrong/, + * foo: 'bar', + * info: { + * nested: true, + * // It is not possible to use regular expressions for nested properties! + * baz: 'text', + * }, + * // The `reg` property contains a regular expression and only if the + * // validation object contains an identical regular expression, it is going + * // to pass. + * reg: /abc/i, + * }, + * ); + * + * // Fails due to the different `message` and `name` properties: + * assert.throws( + * () => { + * const otherErr = new Error('Not found'); + * // Copy all enumerable properties from `err` to `otherErr`. + * for (const [key, value] of Object.entries(err)) { + * otherErr[key] = value; + * } + * throw otherErr; + * }, + * // The error's `message` and `name` properties will also be checked when using + * // an error as validation object. + * err, + * ); + * ``` + * + * Validate instanceof using constructor: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * Error, + * ); + * ``` + * + * Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): + * + * Using a regular expression runs `.toString` on the error object, and will + * therefore also include the error name. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * /^Error: Wrong value$/, + * ); + * ``` + * + * Custom error validation: + * + * The function must return `true` to indicate all internal validations passed. + * It will otherwise fail with an `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * (err) => { + * assert(err instanceof Error); + * assert(/value/.test(err)); + * // Avoid returning anything from validation functions besides `true`. + * // Otherwise, it's not clear what part of the validation failed. Instead, + * // throw an error about the specific validation that failed (as done in this + * // example) and add as much helpful debugging information to that error as + * // possible. + * return true; + * }, + * 'unexpected error', + * ); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Using the same + * message as the thrown error message is going to result in an `ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using + * a string as the second argument gets considered: + * + * ```js + * import assert from 'node:assert/strict'; + * + * function throwingFirst() { + * throw new Error('First'); + * } + * + * function throwingSecond() { + * throw new Error('Second'); + * } + * + * function notThrowing() {} + * + * // The second argument is a string and the input function threw an Error. + * // The first case will not throw as it does not match for the error message + * // thrown by the input function! + * assert.throws(throwingFirst, 'Second'); + * // In the next example the message has no benefit over the message from the + * // error and since it is not clear if the user intended to actually match + * // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. + * assert.throws(throwingSecond, 'Second'); + * // TypeError [ERR_AMBIGUOUS_ARGUMENT] + * + * // The string is only used (as message) in case the function does not throw: + * assert.throws(notThrowing, 'Second'); + * // AssertionError [ERR_ASSERTION]: Missing expected exception: Second + * + * // If it was intended to match for the error message do this instead: + * // It does not throw because the error messages match. + * assert.throws(throwingSecond, /Second$/); + * + * // If the error message does not match, an AssertionError is thrown. + * assert.throws(throwingFirst, /Second$/); + * // AssertionError [ERR_ASSERTION] + * ``` + * + * Due to the confusing error-prone notation, avoid a string as the second + * argument. + * @since v0.1.21 + */ + function throws(block: () => unknown, message?: string | Error): void; + function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Asserts that the function `fn` does not throw an error. + * + * Using `assert.doesNotThrow()` is actually not useful because there + * is no benefit in catching an error and then rethrowing it. Instead, consider + * adding a comment next to the specific code path that should not throw and keep + * error messages as expressive as possible. + * + * When `assert.doesNotThrow()` is called, it will immediately call the `fn` function. + * + * If an error is thrown and it is the same type as that specified by the `error` parameter, then an `AssertionError` is thrown. If the error is of a + * different type, or if the `error` parameter is undefined, the error is + * propagated back to the caller. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * The following, for instance, will throw the `TypeError` because there is no + * matching error type in the assertion: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * However, the following will result in an `AssertionError` with the message + * 'Got unwanted exception...': + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * TypeError, + * ); + * ``` + * + * If an `AssertionError` is thrown and a value is provided for the `message` parameter, the value of `message` will be appended to the `AssertionError` message: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * /Wrong value/, + * 'Whoops', + * ); + * // Throws: AssertionError: Got unwanted exception: Whoops + * ``` + * @since v0.1.21 + */ + function doesNotThrow(block: () => unknown, message?: string | Error): void; + function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Throws `value` if `value` is not `undefined` or `null`. This is useful when + * testing the `error` argument in callbacks. The stack trace contains all frames + * from the error passed to `ifError()` including the potential new frames for `ifError()` itself. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ifError(null); + * // OK + * assert.ifError(0); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 + * assert.ifError('error'); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' + * assert.ifError(new Error()); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error + * + * // Create some random error frames. + * let err; + * (function errorFrame() { + * err = new Error('test error'); + * })(); + * + * (function ifErrorFrame() { + * assert.ifError(err); + * })(); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error + * // at ifErrorFrame + * // at errorFrame + * ``` + * @since v0.1.97 + */ + function ifError(value: unknown): asserts value is null | undefined; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is rejected. + * + * If `asyncFn` is a function and it throws an error synchronously, `assert.rejects()` will return a rejected `Promise` with that error. If the + * function does not return a promise, `assert.rejects()` will return a rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v22.x/api/errors.html#err_invalid_return_value) + * error. In both cases the error handler is skipped. + * + * Besides the async nature to await the completion behaves identically to {@link throws}. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * an object where each property will be tested for, or an instance of error where + * each property will be tested for including the non-enumerable `message` and `name` properties. + * + * If specified, `message` will be the message provided by the `{@link AssertionError}` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * (err) => { + * assert.strictEqual(err.name, 'TypeError'); + * assert.strictEqual(err.message, 'Wrong value'); + * return true; + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.rejects( + * Promise.reject(new Error('Wrong value')), + * Error, + * ).then(() => { + * // ... + * }); + * ``` + * + * `error` cannot be a string. If a string is provided as the second argument, then `error` is assumed to + * be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Please read the + * example in {@link throws} carefully if using a string as the second argument gets considered. + * @since v10.0.0 + */ + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is not rejected. + * + * If `asyncFn` is a function and it throws an error synchronously, `assert.doesNotReject()` will return a rejected `Promise` with that error. If + * the function does not return a promise, `assert.doesNotReject()` will return a + * rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v22.x/api/errors.html#err_invalid_return_value) error. In both cases + * the error handler is skipped. + * + * Using `assert.doesNotReject()` is actually not useful because there is little + * benefit in catching a rejection and then rejecting it again. Instead, consider + * adding a comment next to the specific code path that should not reject and keep + * error messages as expressive as possible. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) + * .then(() => { + * // ... + * }); + * ``` + * @since v10.0.0 + */ + function doesNotReject( + block: (() => Promise) | Promise, + message?: string | Error, + ): Promise; + function doesNotReject( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Expects the `string` input to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.match('I will fail', /pass/); + * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... + * + * assert.match(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.match('I will pass', /pass/); + * // OK + * ``` + * + * If the values do not match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an [Error](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. + * @since v13.6.0, v12.16.0 + */ + function match(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Expects the `string` input not to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotMatch('I will fail', /fail/); + * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... + * + * assert.doesNotMatch(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.doesNotMatch('I will pass', /different/); + * // OK + * ``` + * + * If the values do match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an [Error](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. + * @since v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Tests for partial deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. "Partial" equality means + * that only properties that exist on the `expected` parameter are going to be + * compared. + * + * This method always passes the same test cases as `assert.deepStrictEqual()`, + * behaving as a super set of it. + * @since v22.13.0 + */ + function partialDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + } + namespace assert { + export { strict }; + } + export = assert; +} +declare module "node:assert" { + import assert = require("assert"); + export = assert; +} diff --git a/node_modules/@types/node/assert/strict.d.ts b/node_modules/@types/node/assert/strict.d.ts new file mode 100644 index 0000000..83ce1fe --- /dev/null +++ b/node_modules/@types/node/assert/strict.d.ts @@ -0,0 +1,111 @@ +/** + * In strict assertion mode, non-strict methods behave like their corresponding + * strict methods. For example, `assert.deepEqual()` will behave like + * `assert.deepStrictEqual()`. + * + * In strict assertion mode, error messages for objects display a diff. In legacy + * assertion mode, error messages for objects display the objects, often truncated. + * + * To use strict assertion mode: + * + * ```js + * import { strict as assert } from 'node:assert'; + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * ``` + * + * Example error diff: + * + * ```js + * import { strict as assert } from 'node:assert'; + * + * assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]); + * // AssertionError: Expected inputs to be strictly deep-equal: + * // + actual - expected ... Lines skipped + * // + * // [ + * // [ + * // ... + * // 2, + * // + 3 + * // - '3' + * // ], + * // ... + * // 5 + * // ] + * ``` + * + * To deactivate the colors, use the `NO_COLOR` or `NODE_DISABLE_COLORS` + * environment variables. This will also deactivate the colors in the REPL. For + * more on color support in terminal environments, read the tty + * [`getColorDepth()`](https://nodejs.org/docs/latest-v22.x/api/tty.html#writestreamgetcolordepthenv) documentation. + * @since v15.0.0 + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/assert/strict.js) + */ +declare module "assert/strict" { + import { + Assert, + AssertionError, + AssertionErrorOptions, + AssertOptions, + AssertPredicate, + AssertStrict, + CallTracker, + CallTrackerCall, + CallTrackerReportInformation, + deepStrictEqual, + doesNotMatch, + doesNotReject, + doesNotThrow, + fail, + ifError, + match, + notDeepStrictEqual, + notStrictEqual, + ok, + partialDeepStrictEqual, + rejects, + strictEqual, + throws, + } from "node:assert"; + function strict(value: unknown, message?: string | Error): asserts value; + namespace strict { + export { + Assert, + AssertionError, + AssertionErrorOptions, + AssertOptions, + AssertPredicate, + AssertStrict, + CallTracker, + CallTrackerCall, + CallTrackerReportInformation, + deepStrictEqual, + deepStrictEqual as deepEqual, + doesNotMatch, + doesNotReject, + doesNotThrow, + fail, + ifError, + match, + notDeepStrictEqual, + notDeepStrictEqual as notDeepEqual, + notStrictEqual, + notStrictEqual as notEqual, + ok, + partialDeepStrictEqual, + rejects, + strict, + strictEqual, + strictEqual as equal, + throws, + }; + } + export = strict; +} +declare module "node:assert/strict" { + import strict = require("assert/strict"); + export = strict; +} diff --git a/node_modules/@types/node/async_hooks.d.ts b/node_modules/@types/node/async_hooks.d.ts new file mode 100644 index 0000000..01d21d4 --- /dev/null +++ b/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,603 @@ +/** + * We strongly discourage the use of the `async_hooks` API. + * Other APIs that can cover most of its use cases include: + * + * * [`AsyncLocalStorage`](https://nodejs.org/docs/latest-v22.x/api/async_context.html#class-asynclocalstorage) tracks async context + * * [`process.getActiveResourcesInfo()`](https://nodejs.org/docs/latest-v22.x/api/process.html#processgetactiveresourcesinfo) tracks active resources + * + * The `node:async_hooks` module provides an API to track asynchronous resources. + * It can be accessed using: + * + * ```js + * import async_hooks from 'node:async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/async_hooks.js) + */ +declare module "async_hooks" { + /** + * ```js + * import { executionAsyncId } from 'node:async_hooks'; + * import fs from 'node:fs'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * const path = '.'; + * fs.open(path, 'r', (err, fd) => { + * console.log(executionAsyncId()); // 6 - open() + * }); + * ``` + * + * The ID returned from `executionAsyncId()` is related to execution timing, not + * causality (which is covered by `triggerAsyncId()`): + * + * ```js + * const server = net.createServer((conn) => { + * // Returns the ID of the server, not of the new connection, because the + * // callback runs in the execution scope of the server's MakeCallback(). + * async_hooks.executionAsyncId(); + * + * }).listen(port, () => { + * // Returns the ID of a TickObject (process.nextTick()) because all + * // callbacks passed to .listen() are wrapped in a nextTick(). + * async_hooks.executionAsyncId(); + * }); + * ``` + * + * Promise contexts may not get precise `executionAsyncIds` by default. + * See the section on [promise execution tracking](https://nodejs.org/docs/latest-v22.x/api/async_hooks.html#promise-execution-tracking). + * @since v8.1.0 + * @return The `asyncId` of the current execution context. Useful to track when something calls. + */ + function executionAsyncId(): number; + /** + * Resource objects returned by `executionAsyncResource()` are most often internal + * Node.js handle objects with undocumented APIs. Using any functions or properties + * on the object is likely to crash your application and should be avoided. + * + * Using `executionAsyncResource()` in the top-level execution context will + * return an empty object as there is no handle or request object to use, + * but having an object representing the top-level can be helpful. + * + * ```js + * import { open } from 'node:fs'; + * import { executionAsyncId, executionAsyncResource } from 'node:async_hooks'; + * + * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} + * open(new URL(import.meta.url), 'r', (err, fd) => { + * console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap + * }); + * ``` + * + * This can be used to implement continuation local storage without the + * use of a tracking `Map` to store the metadata: + * + * ```js + * import { createServer } from 'node:http'; + * import { + * executionAsyncId, + * executionAsyncResource, + * createHook, + * } from 'node:async_hooks'; + * const sym = Symbol('state'); // Private symbol to avoid pollution + * + * createHook({ + * init(asyncId, type, triggerAsyncId, resource) { + * const cr = executionAsyncResource(); + * if (cr) { + * resource[sym] = cr[sym]; + * } + * }, + * }).enable(); + * + * const server = createServer((req, res) => { + * executionAsyncResource()[sym] = { state: req.url }; + * setTimeout(function() { + * res.end(JSON.stringify(executionAsyncResource()[sym])); + * }, 100); + * }).listen(3000); + * ``` + * @since v13.9.0, v12.17.0 + * @return The resource representing the current execution. Useful to store data within the resource. + */ + function executionAsyncResource(): object; + /** + * ```js + * const server = net.createServer((conn) => { + * // The resource that caused (or triggered) this callback to be called + * // was that of the new connection. Thus the return value of triggerAsyncId() + * // is the asyncId of "conn". + * async_hooks.triggerAsyncId(); + * + * }).listen(port, () => { + * // Even though all callbacks passed to .listen() are wrapped in a nextTick() + * // the callback itself exists because the call to the server's .listen() + * // was made. So the return value would be the ID of the server. + * async_hooks.triggerAsyncId(); + * }); + * ``` + * + * Promise contexts may not get valid `triggerAsyncId`s by default. See + * the section on [promise execution tracking](https://nodejs.org/docs/latest-v22.x/api/async_hooks.html#promise-execution-tracking). + * @return The ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId A unique ID for the async resource + * @param type The type of the async resource + * @param triggerAsyncId The unique ID of the async resource in whose execution context this async resource was created + * @param resource Reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + /** + * Called immediately after the callback specified in `before` is completed. + * + * If an uncaught exception occurs during execution of the callback, then `after` will run after the `'uncaughtException'` event is emitted or a `domain`'s handler runs. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + /** + * Registers functions to be called for different lifetime events of each async + * operation. + * + * The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the + * respective asynchronous event during a resource's lifetime. + * + * All callbacks are optional. For example, if only resource cleanup needs to + * be tracked, then only the `destroy` callback needs to be passed. The + * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. + * + * ```js + * import { createHook } from 'node:async_hooks'; + * + * const asyncHook = createHook({ + * init(asyncId, type, triggerAsyncId, resource) { }, + * destroy(asyncId) { }, + * }); + * ``` + * + * The callbacks will be inherited via the prototype chain: + * + * ```js + * class MyAsyncCallbacks { + * init(asyncId, type, triggerAsyncId, resource) { } + * destroy(asyncId) {} + * } + * + * class MyAddedCallbacks extends MyAsyncCallbacks { + * before(asyncId) { } + * after(asyncId) { } + * } + * + * const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); + * ``` + * + * Because promises are asynchronous resources whose lifecycle is tracked + * via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. + * @since v8.1.0 + * @param callbacks The `Hook Callbacks` to register + * @return Instance used for disabling and enabling hooks + */ + function createHook(callbacks: HookCallbacks): AsyncHook; + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * @default executionAsyncId() + */ + triggerAsyncId?: number | undefined; + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * @default false + */ + requireManualDestroy?: boolean | undefined; + } + /** + * The class `AsyncResource` is designed to be extended by the embedder's async + * resources. Using this, users can easily trigger the lifetime events of their + * own resources. + * + * The `init` hook will trigger when an `AsyncResource` is instantiated. + * + * The following is an overview of the `AsyncResource` API. + * + * ```js + * import { AsyncResource, executionAsyncId } from 'node:async_hooks'; + * + * // AsyncResource() is meant to be extended. Instantiating a + * // new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * // async_hook.executionAsyncId() is used. + * const asyncResource = new AsyncResource( + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }, + * ); + * + * // Run a function in the execution context of the resource. This will + * // * establish the context of the resource + * // * trigger the AsyncHooks before callbacks + * // * call the provided function `fn` with the supplied arguments + * // * trigger the AsyncHooks after callbacks + * // * restore the original execution context + * asyncResource.runInAsyncScope(fn, thisArg, ...args); + * + * // Call AsyncHooks destroy callbacks. + * asyncResource.emitDestroy(); + * + * // Return the unique ID assigned to the AsyncResource instance. + * asyncResource.asyncId(); + * + * // Return the trigger ID for the AsyncResource instance. + * asyncResource.triggerAsyncId(); + * ``` + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since v9.3.0) + */ + constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); + /** + * Binds the given function to the current execution context. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current execution context. + * @param type An optional name to associate with the underlying `AsyncResource`. + */ + static bind any, ThisArg>( + fn: Func, + type?: string, + thisArg?: ThisArg, + ): Func; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>(fn: Func): Func; + /** + * Call the provided function with the provided arguments in the execution context + * of the async resource. This will establish the context, trigger the AsyncHooks + * before callbacks, call the function, trigger the AsyncHooks after callbacks, and + * then restore the original execution context. + * @since v9.6.0 + * @param fn The function to call in the execution context of this async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope( + fn: (this: This, ...args: any[]) => Result, + thisArg?: This, + ...args: any[] + ): Result; + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + * @return A reference to `asyncResource`. + */ + emitDestroy(): this; + /** + * @return The unique `asyncId` assigned to the resource. + */ + asyncId(): number; + /** + * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. + */ + triggerAsyncId(): number; + } + /** + * This class creates stores that stay coherent through asynchronous operations. + * + * While you can create your own implementation on top of the `node:async_hooks` module, `AsyncLocalStorage` should be preferred as it is a performant and memory + * safe implementation that involves significant optimizations that are non-obvious + * to implement. + * + * The following example uses `AsyncLocalStorage` to build a simple logger + * that assigns IDs to incoming HTTP requests and includes them in messages + * logged within each request. + * + * ```js + * import http from 'node:http'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const asyncLocalStorage = new AsyncLocalStorage(); + * + * function logWithId(msg) { + * const id = asyncLocalStorage.getStore(); + * console.log(`${id !== undefined ? id : '-'}:`, msg); + * } + * + * let idSeq = 0; + * http.createServer((req, res) => { + * asyncLocalStorage.run(idSeq++, () => { + * logWithId('start'); + * // Imagine any chain of async operations here + * setImmediate(() => { + * logWithId('finish'); + * res.end(); + * }); + * }); + * }).listen(8080); + * + * http.get('http://localhost:8080'); + * http.get('http://localhost:8080'); + * // Prints: + * // 0: start + * // 0: finish + * // 1: start + * // 1: finish + * ``` + * + * Each instance of `AsyncLocalStorage` maintains an independent storage context. + * Multiple instances can safely exist simultaneously without risk of interfering + * with each other's data. + * @since v13.10.0, v12.17.0 + */ + class AsyncLocalStorage { + /** + * Binds the given function to the current execution context. + * @since v19.8.0 + * @param fn The function to bind to the current execution context. + * @return A new function that calls `fn` within the captured execution context. + */ + static bind any>(fn: Func): Func; + /** + * Captures the current execution context and returns a function that accepts a + * function as an argument. Whenever the returned function is called, it + * calls the function passed to it within the captured context. + * + * ```js + * const asyncLocalStorage = new AsyncLocalStorage(); + * const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot()); + * const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); + * console.log(result); // returns 123 + * ``` + * + * AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple + * async context tracking purposes, for example: + * + * ```js + * class Foo { + * #runInAsyncScope = AsyncLocalStorage.snapshot(); + * + * get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } + * } + * + * const foo = asyncLocalStorage.run(123, () => new Foo()); + * console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 + * ``` + * @since v19.8.0 + * @return A new function with the signature `(fn: (...args) : R, ...args) : R`. + */ + static snapshot(): (fn: (...args: TArgs) => R, ...args: TArgs) => R; + /** + * Disables the instance of `AsyncLocalStorage`. All subsequent calls + * to `asyncLocalStorage.getStore()` will return `undefined` until `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. + * + * When calling `asyncLocalStorage.disable()`, all current contexts linked to the + * instance will be exited. + * + * Calling `asyncLocalStorage.disable()` is required before the `asyncLocalStorage` can be garbage collected. This does not apply to stores + * provided by the `asyncLocalStorage`, as those objects are garbage collected + * along with the corresponding async resources. + * + * Use this method when the `asyncLocalStorage` is not in use anymore + * in the current process. + * @since v13.10.0, v12.17.0 + * @experimental + */ + disable(): void; + /** + * Returns the current store. + * If called outside of an asynchronous context initialized by + * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it + * returns `undefined`. + * @since v13.10.0, v12.17.0 + */ + getStore(): T | undefined; + /** + * Runs a function synchronously within a context and returns its + * return value. The store is not accessible outside of the callback function. + * The store is accessible to any asynchronous operations created within the + * callback. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `run()` too. + * The stacktrace is not impacted by this call and the context is exited. + * + * Example: + * + * ```js + * const store = { id: 2 }; + * try { + * asyncLocalStorage.run(store, () => { + * asyncLocalStorage.getStore(); // Returns the store object + * setTimeout(() => { + * asyncLocalStorage.getStore(); // Returns the store object + * }, 200); + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns undefined + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + */ + run(store: T, callback: () => R): R; + run(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Runs a function synchronously outside of a context and returns its + * return value. The store is not accessible within the callback function or + * the asynchronous operations created within the callback. Any `getStore()` call done within the callback function will always return `undefined`. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `exit()` too. + * The stacktrace is not impacted by this call and the context is re-entered. + * + * Example: + * + * ```js + * // Within a call to run + * try { + * asyncLocalStorage.getStore(); // Returns the store object or value + * asyncLocalStorage.exit(() => { + * asyncLocalStorage.getStore(); // Returns undefined + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns the same object or value + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + * @experimental + */ + exit(callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Transitions into the context for the remainder of the current + * synchronous execution and then persists the store through any following + * asynchronous calls. + * + * Example: + * + * ```js + * const store = { id: 1 }; + * // Replaces previous store with the given store object + * asyncLocalStorage.enterWith(store); + * asyncLocalStorage.getStore(); // Returns the store object + * someAsyncOperation(() => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * ``` + * + * This transition will continue for the _entire_ synchronous execution. + * This means that if, for example, the context is entered within an event + * handler subsequent event handlers will also run within that context unless + * specifically bound to another context with an `AsyncResource`. That is why `run()` should be preferred over `enterWith()` unless there are strong reasons + * to use the latter method. + * + * ```js + * const store = { id: 1 }; + * + * emitter.on('my-event', () => { + * asyncLocalStorage.enterWith(store); + * }); + * emitter.on('my-event', () => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * + * asyncLocalStorage.getStore(); // Returns undefined + * emitter.emit('my-event'); + * asyncLocalStorage.getStore(); // Returns the same object + * ``` + * @since v13.11.0, v12.17.0 + * @experimental + */ + enterWith(store: T): void; + } + /** + * @since v17.2.0, v16.14.0 + * @return A map of provider types to the corresponding numeric id. + * This map contains all the event types that might be emitted by the `async_hooks.init()` event. + */ + namespace asyncWrapProviders { + const NONE: number; + const DIRHANDLE: number; + const DNSCHANNEL: number; + const ELDHISTOGRAM: number; + const FILEHANDLE: number; + const FILEHANDLECLOSEREQ: number; + const FIXEDSIZEBLOBCOPY: number; + const FSEVENTWRAP: number; + const FSREQCALLBACK: number; + const FSREQPROMISE: number; + const GETADDRINFOREQWRAP: number; + const GETNAMEINFOREQWRAP: number; + const HEAPSNAPSHOT: number; + const HTTP2SESSION: number; + const HTTP2STREAM: number; + const HTTP2PING: number; + const HTTP2SETTINGS: number; + const HTTPINCOMINGMESSAGE: number; + const HTTPCLIENTREQUEST: number; + const JSSTREAM: number; + const JSUDPWRAP: number; + const MESSAGEPORT: number; + const PIPECONNECTWRAP: number; + const PIPESERVERWRAP: number; + const PIPEWRAP: number; + const PROCESSWRAP: number; + const PROMISE: number; + const QUERYWRAP: number; + const SHUTDOWNWRAP: number; + const SIGNALWRAP: number; + const STATWATCHER: number; + const STREAMPIPE: number; + const TCPCONNECTWRAP: number; + const TCPSERVERWRAP: number; + const TCPWRAP: number; + const TTYWRAP: number; + const UDPSENDWRAP: number; + const UDPWRAP: number; + const SIGINTWATCHDOG: number; + const WORKER: number; + const WORKERHEAPSNAPSHOT: number; + const WRITEWRAP: number; + const ZLIB: number; + const CHECKPRIMEREQUEST: number; + const PBKDF2REQUEST: number; + const KEYPAIRGENREQUEST: number; + const KEYGENREQUEST: number; + const KEYEXPORTREQUEST: number; + const CIPHERREQUEST: number; + const DERIVEBITSREQUEST: number; + const HASHREQUEST: number; + const RANDOMBYTESREQUEST: number; + const RANDOMPRIMEREQUEST: number; + const SCRYPTREQUEST: number; + const SIGNREQUEST: number; + const TLSWRAP: number; + const VERIFYREQUEST: number; + } +} +declare module "node:async_hooks" { + export * from "async_hooks"; +} diff --git a/node_modules/@types/node/buffer.buffer.d.ts b/node_modules/@types/node/buffer.buffer.d.ts new file mode 100644 index 0000000..8823dee --- /dev/null +++ b/node_modules/@types/node/buffer.buffer.d.ts @@ -0,0 +1,472 @@ +declare module "buffer" { + type ImplicitArrayBuffer> = T extends + { valueOf(): infer V extends ArrayBufferLike } ? V : T; + global { + interface BufferConstructor { + // see buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: ArrayLike): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: TArrayBuffer): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * If `array` is an `Array`-like object (that is, one with a `length` property of + * type `number`), it is treated as if it is an array, unless it is a `Buffer` or + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an + * `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use + * `Buffer.copyBytesFrom()`. + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal + * `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from(array: WithImplicitCoercion>): Buffer; + /** + * This creates a view of the `ArrayBuffer` without copying the underlying + * memory. For example, when passed a reference to the `.buffer` property of a + * `TypedArray` instance, the newly created `Buffer` will share the same + * allocated memory as the `TypedArray`'s underlying `ArrayBuffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arr = new Uint16Array(2); + * + * arr[0] = 5000; + * arr[1] = 4000; + * + * // Shares memory with `arr`. + * const buf = Buffer.from(arr.buffer); + * + * console.log(buf); + * // Prints: + * + * // Changing the original Uint16Array changes the Buffer also. + * arr[1] = 6000; + * + * console.log(buf); + * // Prints: + * ``` + * + * The optional `byteOffset` and `length` arguments specify a memory range within + * the `arrayBuffer` that will be shared by the `Buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const ab = new ArrayBuffer(10); + * const buf = Buffer.from(ab, 0, 2); + * + * console.log(buf.length); + * // Prints: 2 + * ``` + * + * A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer` or a + * `SharedArrayBuffer` or another type appropriate for `Buffer.from()` + * variants. + * + * It is important to remember that a backing `ArrayBuffer` can cover a range + * of memory that extends beyond the bounds of a `TypedArray` view. A new + * `Buffer` created using the `buffer` property of a `TypedArray` may extend + * beyond the range of the `TypedArray`: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements + * const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements + * console.log(arrA.buffer === arrB.buffer); // true + * + * const buf = Buffer.from(arrB.buffer); + * console.log(buf); + * // Prints: + * ``` + * @since v5.10.0 + * @param arrayBuffer An `ArrayBuffer`, `SharedArrayBuffer`, for example the + * `.buffer` property of a `TypedArray`. + * @param byteOffset Index of first byte to expose. **Default:** `0`. + * @param length Number of bytes to expose. **Default:** + * `arrayBuffer.byteLength - byteOffset`. + */ + from>( + arrayBuffer: TArrayBuffer, + byteOffset?: number, + length?: number, + ): Buffer>; + /** + * Creates a new `Buffer` containing `string`. The `encoding` parameter identifies + * the character encoding to be used when converting `string` into bytes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('this is a tést'); + * const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); + * + * console.log(buf1.toString()); + * // Prints: this is a tést + * console.log(buf2.toString()); + * // Prints: this is a tést + * console.log(buf1.toString('latin1')); + * // Prints: this is a tést + * ``` + * + * A `TypeError` will be thrown if `string` is not a string or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(string)` may also use the internal `Buffer` pool like + * `Buffer.allocUnsafe()` does. + * @since v5.10.0 + * @param string A string to encode. + * @param encoding The encoding of `string`. **Default:** `'utf8'`. + */ + from(string: WithImplicitCoercion, encoding?: BufferEncoding): Buffer; + from(arrayOrString: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. If the combined length of the `Buffer`s in `list` is + * less than `totalLength`, the remaining space is filled with zeros. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: readonly Uint8Array[], totalLength?: number): Buffer; + /** + * Copies the underlying memory of `view` into a new `Buffer`. + * + * ```js + * const u16 = new Uint16Array([0, 0xffff]); + * const buf = Buffer.copyBytesFrom(u16, 1, 1); + * u16[1] = 0; + * console.log(buf.length); // 2 + * console.log(buf[0]); // 255 + * console.log(buf[1]); // 255 + * ``` + * @since v19.8.0 + * @param view The {TypedArray} to copy. + * @param [offset=0] The starting offset within `view`. + * @param [length=view.length - offset] The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if + * `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + } + interface Buffer extends Uint8Array { + // see buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + } + // TODO: remove globals in future version + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedBuffer = Buffer; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type AllowSharedBuffer = Buffer; + } + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + var SlowBuffer: { + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + new(size: number): Buffer; + prototype: Buffer; + }; +} diff --git a/node_modules/@types/node/buffer.d.ts b/node_modules/@types/node/buffer.d.ts new file mode 100644 index 0000000..354e08a --- /dev/null +++ b/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,1934 @@ +// If lib.dom.d.ts or lib.webworker.d.ts is loaded, then use the global types. +// Otherwise, use the types from node. +type _Blob = typeof globalThis extends { onmessage: any; Blob: any } ? {} : import("buffer").Blob; +type _File = typeof globalThis extends { onmessage: any; File: any } ? {} : import("buffer").File; + +/** + * `Buffer` objects are used to represent a fixed-length sequence of bytes. Many + * Node.js APIs support `Buffer`s. + * + * The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and + * extends it with methods that cover additional use cases. Node.js APIs accept + * plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) s wherever `Buffer`s are supported as well. + * + * While the `Buffer` class is available within the global scope, it is still + * recommended to explicitly reference it via an import or require statement. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a zero-filled Buffer of length 10. + * const buf1 = Buffer.alloc(10); + * + * // Creates a Buffer of length 10, + * // filled with bytes which all have the value `1`. + * const buf2 = Buffer.alloc(10, 1); + * + * // Creates an uninitialized buffer of length 10. + * // This is faster than calling Buffer.alloc() but the returned + * // Buffer instance might contain old data that needs to be + * // overwritten using fill(), write(), or other functions that fill the Buffer's + * // contents. + * const buf3 = Buffer.allocUnsafe(10); + * + * // Creates a Buffer containing the bytes [1, 2, 3]. + * const buf4 = Buffer.from([1, 2, 3]); + * + * // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries + * // are all truncated using `(value & 255)` to fit into the range 0–255. + * const buf5 = Buffer.from([257, 257.5, -255, '1']); + * + * // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': + * // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) + * // [116, 195, 169, 115, 116] (in decimal notation) + * const buf6 = Buffer.from('tést'); + * + * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. + * const buf7 = Buffer.from('tést', 'latin1'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/buffer.js) + */ +declare module "buffer" { + import { BinaryLike } from "node:crypto"; + import { ReadableStream as WebReadableStream } from "node:stream/web"; + /** + * This function returns `true` if `input` contains only valid UTF-8-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.4.0, v18.14.0 + * @param input The input to validate. + */ + export function isUtf8(input: ArrayBuffer | NodeJS.TypedArray): boolean; + /** + * This function returns `true` if `input` contains only valid ASCII-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.6.0, v18.15.0 + * @param input The input to validate. + */ + export function isAscii(input: ArrayBuffer | NodeJS.TypedArray): boolean; + export let INSPECT_MAX_BYTES: number; + export const kMaxLength: number; + export const kStringMaxLength: number; + export const constants: { + MAX_LENGTH: number; + MAX_STRING_LENGTH: number; + }; + export type TranscodeEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "latin1" + | "binary"; + /** + * Re-encodes the given `Buffer` or `Uint8Array` instance from one character + * encoding to another. Returns a new `Buffer` instance. + * + * Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if + * conversion from `fromEnc` to `toEnc` is not permitted. + * + * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`, `'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. + * + * The transcoding process will use substitution characters if a given byte + * sequence cannot be adequately represented in the target encoding. For instance: + * + * ```js + * import { Buffer, transcode } from 'node:buffer'; + * + * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); + * console.log(newBuf.toString('ascii')); + * // Prints: '?' + * ``` + * + * Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced + * with `?` in the transcoded `Buffer`. + * @since v7.1.0 + * @param source A `Buffer` or `Uint8Array` instance. + * @param fromEnc The current encoding. + * @param toEnc To target encoding. + */ + export function transcode( + source: Uint8Array, + fromEnc: TranscodeEncoding, + toEnc: TranscodeEncoding, + ): NonSharedBuffer; + /** + * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using + * a prior call to `URL.createObjectURL()`. + * @since v16.7.0 + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + export function resolveObjectURL(id: string): Blob | undefined; + export { type AllowSharedBuffer, Buffer, type NonSharedBuffer }; + /** + * @experimental + */ + export interface BlobOptions { + /** + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts + * will be converted to the platform native line-ending as specified by `import { EOL } from 'node:os'`. + */ + endings?: "transparent" | "native"; + /** + * The Blob content-type. The intent is for `type` to convey + * the MIME media type of the data, however no validation of the type format + * is performed. + */ + type?: string | undefined; + } + /** + * A `Blob` encapsulates immutable, raw data that can be safely shared across + * multiple worker threads. + * @since v15.7.0, v14.18.0 + */ + export class Blob { + /** + * The total size of the `Blob` in bytes. + * @since v15.7.0, v14.18.0 + */ + readonly size: number; + /** + * The content-type of the `Blob`. + * @since v15.7.0, v14.18.0 + */ + readonly type: string; + /** + * Creates a new `Blob` object containing a concatenation of the given sources. + * + * {ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into + * the 'Blob' and can therefore be safely modified after the 'Blob' is created. + * + * String sources are also copied into the `Blob`. + */ + constructor(sources: Array, options?: BlobOptions); + /** + * Returns a promise that fulfills with an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of + * the `Blob` data. + * @since v15.7.0, v14.18.0 + */ + arrayBuffer(): Promise; + /** + * The `blob.bytes()` method returns the byte of the `Blob` object as a `Promise`. + * + * ```js + * const blob = new Blob(['hello']); + * blob.bytes().then((bytes) => { + * console.log(bytes); // Outputs: Uint8Array(5) [ 104, 101, 108, 108, 111 ] + * }); + * ``` + */ + bytes(): Promise; + /** + * Creates and returns a new `Blob` containing a subset of this `Blob` objects + * data. The original `Blob` is not altered. + * @since v15.7.0, v14.18.0 + * @param start The starting index. + * @param end The ending index. + * @param type The content-type for the new `Blob` + */ + slice(start?: number, end?: number, type?: string): Blob; + /** + * Returns a promise that fulfills with the contents of the `Blob` decoded as a + * UTF-8 string. + * @since v15.7.0, v14.18.0 + */ + text(): Promise; + /** + * Returns a new `ReadableStream` that allows the content of the `Blob` to be read. + * @since v16.7.0 + */ + stream(): WebReadableStream; + } + export interface FileOptions { + /** + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be + * converted to the platform native line-ending as specified by `import { EOL } from 'node:os'`. + */ + endings?: "native" | "transparent"; + /** The File content-type. */ + type?: string; + /** The last modified date of the file. `Default`: Date.now(). */ + lastModified?: number; + } + /** + * A [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) provides information about files. + * @since v19.2.0, v18.13.0 + */ + export class File extends Blob { + constructor(sources: Array, fileName: string, options?: FileOptions); + /** + * The name of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly name: string; + /** + * The last modified date of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly lastModified: number; + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + export type WithImplicitCoercion = + | T + | { valueOf(): T } + | (T extends string ? { [Symbol.toPrimitive](hint: "string"): T } : never); + global { + namespace NodeJS { + export { BufferEncoding }; + } + // Buffer class + type BufferEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex"; + /** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex' + */ + interface BufferConstructor { + // see buffer.buffer.d.ts for implementation specific to TypeScript 5.7 and later + // see ts5.6/buffer.buffer.d.ts for implementation specific to TypeScript 5.6 and earlier + + /** + * Returns `true` if `obj` is a `Buffer`, `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * Buffer.isBuffer(Buffer.alloc(10)); // true + * Buffer.isBuffer(Buffer.from('foo')); // true + * Buffer.isBuffer('a string'); // false + * Buffer.isBuffer([]); // false + * Buffer.isBuffer(new Uint8Array(1024)); // false + * ``` + * @since v0.1.101 + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns `true` if `encoding` is the name of a supported character encoding, + * or `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * console.log(Buffer.isEncoding('utf8')); + * // Prints: true + * + * console.log(Buffer.isEncoding('hex')); + * // Prints: true + * + * console.log(Buffer.isEncoding('utf/8')); + * // Prints: false + * + * console.log(Buffer.isEncoding('')); + * // Prints: false + * ``` + * @since v0.9.1 + * @param encoding A character encoding name to check. + */ + isEncoding(encoding: string): encoding is BufferEncoding; + /** + * Returns the byte length of a string when encoded using `encoding`. + * This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account + * for the encoding that is used to convert the string into bytes. + * + * For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input. + * For strings that contain non-base64/hex-encoded data (e.g. whitespace), the + * return value might be greater than the length of a `Buffer` created from the + * string. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const str = '\u00bd + \u00bc = \u00be'; + * + * console.log(`${str}: ${str.length} characters, ` + + * `${Buffer.byteLength(str, 'utf8')} bytes`); + * // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes + * ``` + * + * When `string` is a + * `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- + * Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop- + * er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned. + * @since v0.1.90 + * @param string A value to calculate the length of. + * @param [encoding='utf8'] If `string` is a string, this is its encoding. + * @return The number of bytes contained within `string`. + */ + byteLength( + string: string | NodeJS.ArrayBufferView | ArrayBufferLike, + encoding?: BufferEncoding, + ): number; + /** + * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of `Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('1234'); + * const buf2 = Buffer.from('0123'); + * const arr = [buf1, buf2]; + * + * console.log(arr.sort(Buffer.compare)); + * // Prints: [ , ] + * // (This result is equal to: [buf2, buf1].) + * ``` + * @since v0.11.13 + * @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details. + */ + compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1; + /** + * This is the size (in bytes) of pre-allocated internal `Buffer` instances used + * for pooling. This value may be modified. + * @since v0.11.3 + */ + poolSize: number; + } + interface Buffer { + // see buffer.buffer.d.ts for implementation specific to TypeScript 5.7 and later + // see ts5.6/buffer.buffer.d.ts for implementation specific to TypeScript 5.6 and earlier + + /** + * Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did + * not contain enough space to fit the entire string, only part of `string` will be + * written. However, partially encoded characters will not be written. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(256); + * + * const len = buf.write('\u00bd + \u00bc = \u00be', 0); + * + * console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); + * // Prints: 12 bytes: ½ + ¼ = ¾ + * + * const buffer = Buffer.alloc(10); + * + * const length = buffer.write('abcd', 8); + * + * console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); + * // Prints: 2 bytes : ab + * ``` + * @since v0.1.90 + * @param string String to write to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write `string`. + * @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). + * @param [encoding='utf8'] The character encoding of `string`. + * @return Number of bytes written. + */ + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + /** + * Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`. + * + * If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, + * then each invalid byte is replaced with the replacement character `U+FFFD`. + * + * The maximum length of a string instance (in UTF-16 code units) is available + * as {@link constants.MAX_STRING_LENGTH}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * console.log(buf1.toString('utf8')); + * // Prints: abcdefghijklmnopqrstuvwxyz + * console.log(buf1.toString('utf8', 0, 5)); + * // Prints: abcde + * + * const buf2 = Buffer.from('tést'); + * + * console.log(buf2.toString('hex')); + * // Prints: 74c3a97374 + * console.log(buf2.toString('utf8', 0, 3)); + * // Prints: té + * console.log(buf2.toString(undefined, 0, 3)); + * // Prints: té + * ``` + * @since v0.1.90 + * @param [encoding='utf8'] The character encoding to use. + * @param [start=0] The byte offset to start decoding at. + * @param [end=buf.length] The byte offset to stop decoding at (not inclusive). + */ + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + /** + * Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls + * this function when stringifying a `Buffer` instance. + * + * `Buffer.from()` accepts objects in the format returned from this method. + * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); + * const json = JSON.stringify(buf); + * + * console.log(json); + * // Prints: {"type":"Buffer","data":[1,2,3,4,5]} + * + * const copy = JSON.parse(json, (key, value) => { + * return value && value.type === 'Buffer' ? + * Buffer.from(value) : + * value; + * }); + * + * console.log(copy); + * // Prints: + * ``` + * @since v0.9.2 + */ + toJSON(): { + type: "Buffer"; + data: number[]; + }; + /** + * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('414243', 'hex'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.equals(buf2)); + * // Prints: true + * console.log(buf1.equals(buf3)); + * // Prints: false + * ``` + * @since v0.11.13 + * @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`. + */ + equals(otherBuffer: Uint8Array): boolean; + /** + * Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. + * Comparison is based on the actual sequence of bytes in each `Buffer`. + * + * * `0` is returned if `target` is the same as `buf` + * * `1` is returned if `target` should come _before_`buf` when sorted. + * * `-1` is returned if `target` should come _after_`buf` when sorted. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('BCD'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.compare(buf1)); + * // Prints: 0 + * console.log(buf1.compare(buf2)); + * // Prints: -1 + * console.log(buf1.compare(buf3)); + * // Prints: -1 + * console.log(buf2.compare(buf1)); + * // Prints: 1 + * console.log(buf2.compare(buf3)); + * // Prints: 1 + * console.log([buf1, buf2, buf3].sort(Buffer.compare)); + * // Prints: [ , , ] + * // (This result is equal to: [buf1, buf3, buf2].) + * ``` + * + * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd` arguments can be used to limit the comparison to specific ranges within `target` and `buf` respectively. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); + * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + * + * console.log(buf1.compare(buf2, 5, 9, 0, 4)); + * // Prints: 0 + * console.log(buf1.compare(buf2, 0, 6, 4)); + * // Prints: -1 + * console.log(buf1.compare(buf2, 5, 6, 5)); + * // Prints: 1 + * ``` + * + * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`, `targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * @since v0.11.13 + * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. + * @param [targetStart=0] The offset within `target` at which to begin comparison. + * @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive). + * @param [sourceStart=0] The offset within `buf` at which to begin comparison. + * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). + */ + compare( + target: Uint8Array, + targetStart?: number, + targetEnd?: number, + sourceStart?: number, + sourceEnd?: number, + ): -1 | 0 | 1; + /** + * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. + * + * [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available + * for all TypedArrays, including Node.js `Buffer`s, although it takes + * different function arguments. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create two `Buffer` instances. + * const buf1 = Buffer.allocUnsafe(26); + * const buf2 = Buffer.allocUnsafe(26).fill('!'); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. + * buf1.copy(buf2, 8, 16, 20); + * // This is equivalent to: + * // buf2.set(buf1.subarray(16, 20), 8); + * + * console.log(buf2.toString('ascii', 0, 25)); + * // Prints: !!!!!!!!qrst!!!!!!!!!!!!! + * ``` + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` and copy data from one region to an overlapping region + * // within the same `Buffer`. + * + * const buf = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf[i] = i + 97; + * } + * + * buf.copy(buf, 0, 4, 10); + * + * console.log(buf.toString()); + * // Prints: efghijghijklmnopqrstuvwxyz + * ``` + * @since v0.1.90 + * @param target A `Buffer` or {@link Uint8Array} to copy into. + * @param [targetStart=0] The offset within `target` at which to begin writing. + * @param [sourceStart=0] The offset within `buf` from which to begin copying. + * @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive). + * @return The number of bytes copied. + */ + copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64BE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64LE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64LE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * This function is also available under the `writeBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64BE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64LE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * + * This function is also available under the `writeBigUint64LE` alias. + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64LE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64LE(value: bigint, offset?: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntLE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntLE + * @since v14.9.0, v12.19.0 + */ + writeUintLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntBE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntBE + * @since v14.9.0, v12.19.0 + */ + writeUintBE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than a signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a + * signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntBE(value: number, offset: number, byteLength: number): number; + /** + * Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64BE(0)); + * // Prints: 4294967295n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64BE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + readBigUint64BE(offset?: number): bigint; + /** + * Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64LE(0)); + * // Prints: 18446744069414584320n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64LE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + readBigUint64LE(offset?: number): bigint; + /** + * Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64BE(offset?: number): bigint; + /** + * Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64LE(offset?: number): bigint; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an unsigned, little-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntLE(0, 6).toString(16)); + * // Prints: ab9078563412 + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntLE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntLE + * @since v14.9.0, v12.19.0 + */ + readUintLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an unsigned big-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readUIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntBE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntBE + * @since v14.9.0, v12.19.0 + */ + readUintBE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a little-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntLE(0, 6).toString(16)); + * // Prints: -546f87a9cbee + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a big-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * console.log(buf.readIntBE(1, 0).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntBE(offset: number, byteLength: number): number; + /** + * Reads an unsigned 8-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, -2]); + * + * console.log(buf.readUInt8(0)); + * // Prints: 1 + * console.log(buf.readUInt8(1)); + * // Prints: 254 + * console.log(buf.readUInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readUInt8(offset?: number): number; + /** + * @alias Buffer.readUInt8 + * @since v14.9.0, v12.19.0 + */ + readUint8(offset?: number): number; + /** + * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16LE(0).toString(16)); + * // Prints: 3412 + * console.log(buf.readUInt16LE(1).toString(16)); + * // Prints: 5634 + * console.log(buf.readUInt16LE(2).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16LE(offset?: number): number; + /** + * @alias Buffer.readUInt16LE + * @since v14.9.0, v12.19.0 + */ + readUint16LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16BE(0).toString(16)); + * // Prints: 1234 + * console.log(buf.readUInt16BE(1).toString(16)); + * // Prints: 3456 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16BE(offset?: number): number; + /** + * @alias Buffer.readUInt16BE + * @since v14.9.0, v12.19.0 + */ + readUint16BE(offset?: number): number; + /** + * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32LE(0).toString(16)); + * // Prints: 78563412 + * console.log(buf.readUInt32LE(1).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32LE(offset?: number): number; + /** + * @alias Buffer.readUInt32LE + * @since v14.9.0, v12.19.0 + */ + readUint32LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32BE(0).toString(16)); + * // Prints: 12345678 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32BE(offset?: number): number; + /** + * @alias Buffer.readUInt32BE + * @since v14.9.0, v12.19.0 + */ + readUint32BE(offset?: number): number; + /** + * Reads a signed 8-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([-1, 5]); + * + * console.log(buf.readInt8(0)); + * // Prints: -1 + * console.log(buf.readInt8(1)); + * // Prints: 5 + * console.log(buf.readInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readInt8(offset?: number): number; + /** + * Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16LE(0)); + * // Prints: 1280 + * console.log(buf.readInt16LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16LE(offset?: number): number; + /** + * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16BE(offset?: number): number; + /** + * Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32LE(0)); + * // Prints: 83886080 + * console.log(buf.readInt32LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32LE(offset?: number): number; + /** + * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32BE(offset?: number): number; + /** + * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatLE(0)); + * // Prints: 1.539989614439558e-36 + * console.log(buf.readFloatLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatLE(offset?: number): number; + /** + * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatBE(0)); + * // Prints: 2.387939260590663e-38 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatBE(offset?: number): number; + /** + * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleLE(0)); + * // Prints: 5.447603722011605e-270 + * console.log(buf.readDoubleLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleLE(offset?: number): number; + /** + * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleBE(0)); + * // Prints: 8.20788039913184e-304 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleBE(offset?: number): number; + reverse(): this; + /** + * Interprets `buf` as an array of unsigned 16-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap16(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap16(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * + * One convenient use of `buf.swap16()` is to perform a fast in-place conversion + * between UTF-16 little-endian and UTF-16 big-endian: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); + * buf.swap16(); // Convert to big-endian UTF-16 text. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap16(): this; + /** + * Interprets `buf` as an array of unsigned 32-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap32(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap32(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap32(): this; + /** + * Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. + * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap64(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap64(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v6.3.0 + * @return A reference to `buf`. + */ + swap64(): this; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a + * valid unsigned 8-bit integer. Behavior is undefined when `value` is anything + * other than an unsigned 8-bit integer. + * + * This function is also available under the `writeUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt8(0x3, 0); + * buf.writeUInt8(0x4, 1); + * buf.writeUInt8(0x23, 2); + * buf.writeUInt8(0x42, 3); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeUInt8(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt8 + * @since v14.9.0, v12.19.0 + */ + writeUint8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 16-bit integer. + * + * This function is also available under the `writeUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16LE(0xdead, 0); + * buf.writeUInt16LE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16LE + * @since v14.9.0, v12.19.0 + */ + writeUint16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 16-bit integer. + * + * This function is also available under the `writeUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16BE(0xdead, 0); + * buf.writeUInt16BE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16BE + * @since v14.9.0, v12.19.0 + */ + writeUint16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 32-bit integer. + * + * This function is also available under the `writeUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32LE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32LE + * @since v14.9.0, v12.19.0 + */ + writeUint32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 32-bit integer. + * + * This function is also available under the `writeUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32BE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32BE + * @since v14.9.0, v12.19.0 + */ + writeUint32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a valid + * signed 8-bit integer. Behavior is undefined when `value` is anything other than + * a signed 8-bit integer. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt8(2, 0); + * buf.writeInt8(-2, 1); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16LE(0x0304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16BE(0x0102, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32LE(0x05060708, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32BE(0x01020304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatLE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatBE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatBE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleLE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleBE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleBE(value: number, offset?: number): number; + /** + * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, + * the entire `buf` will be filled: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * + * // Fill a buffer with empty string + * const c = Buffer.allocUnsafe(5).fill(''); + * + * console.log(c.fill('')); + * // Prints: + * ``` + * + * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or + * integer. If the resulting integer is greater than `255` (decimal), `buf` will be + * filled with `value & 255`. + * + * If the final write of a `fill()` operation falls on a multi-byte character, + * then only the bytes of that character that fit into `buf` are written: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with character that takes up two bytes in UTF-8. + * + * console.log(Buffer.allocUnsafe(5).fill('\u0222')); + * // Prints: + * ``` + * + * If `value` contains invalid characters, it is truncated; if no valid + * fill data remains, an exception is thrown: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(5); + * + * console.log(buf.fill('a')); + * // Prints: + * console.log(buf.fill('aazz', 'hex')); + * // Prints: + * console.log(buf.fill('zz', 'hex')); + * // Throws an exception. + * ``` + * @since v0.5.0 + * @param value The value with which to fill `buf`. Empty value (string, Uint8Array, Buffer) is coerced to `0`. + * @param [offset=0] Number of bytes to skip before starting to fill `buf`. + * @param [end=buf.length] Where to stop filling `buf` (not inclusive). + * @param [encoding='utf8'] The encoding for `value` if `value` is a string. + * @return A reference to `buf`. + */ + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + fill(value: string | Uint8Array | number, offset: number, encoding: BufferEncoding): this; + fill(value: string | Uint8Array | number, encoding: BufferEncoding): this; + /** + * If `value` is: + * + * * a string, `value` is interpreted according to the character encoding in `encoding`. + * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. + * To compare a partial `Buffer`, use `buf.subarray`. + * * a number, `value` will be interpreted as an unsigned 8-bit integer + * value between `0` and `255`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.indexOf('this')); + * // Prints: 0 + * console.log(buf.indexOf('is')); + * // Prints: 2 + * console.log(buf.indexOf(Buffer.from('a buffer'))); + * // Prints: 8 + * console.log(buf.indexOf(97)); + * // Prints: 8 (97 is the decimal ASCII value for 'a') + * console.log(buf.indexOf(Buffer.from('a buffer example'))); + * // Prints: -1 + * console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: 8 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); + * // Prints: 4 + * console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); + * // Prints: 6 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a `TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. If the result + * of coercion is `NaN` or `0`, then the entire buffer will be searched. This + * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.indexOf(99.9)); + * console.log(b.indexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN or 0. + * // Prints: 1, searching the whole buffer. + * console.log(b.indexOf('b', undefined)); + * console.log(b.indexOf('b', {})); + * console.log(b.indexOf('b', null)); + * console.log(b.indexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer` and `byteOffset` is less + * than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. + * @since v1.5.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + indexOf(value: string | number | Uint8Array, encoding: BufferEncoding): number; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this buffer is a buffer'); + * + * console.log(buf.lastIndexOf('this')); + * // Prints: 0 + * console.log(buf.lastIndexOf('buffer')); + * // Prints: 17 + * console.log(buf.lastIndexOf(Buffer.from('buffer'))); + * // Prints: 17 + * console.log(buf.lastIndexOf(97)); + * // Prints: 15 (97 is the decimal ASCII value for 'a') + * console.log(buf.lastIndexOf(Buffer.from('yolo'))); + * // Prints: -1 + * console.log(buf.lastIndexOf('buffer', 5)); + * // Prints: 5 + * console.log(buf.lastIndexOf('buffer', 4)); + * // Prints: -1 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); + * // Prints: 6 + * console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); + * // Prints: 4 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a `TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. Any arguments + * that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. + * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.lastIndexOf(99.9)); + * console.log(b.lastIndexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN. + * // Prints: 1, searching the whole buffer. + * console.log(b.lastIndexOf('b', undefined)); + * console.log(b.lastIndexOf('b', {})); + * + * // Passing a byteOffset that coerces to 0. + * // Prints: -1, equivalent to passing 0. + * console.log(b.lastIndexOf('b', null)); + * console.log(b.lastIndexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. + * @since v6.0.0 + * @param value What to search for. + * @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + lastIndexOf(value: string | number | Uint8Array, encoding: BufferEncoding): number; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.includes('this')); + * // Prints: true + * console.log(buf.includes('is')); + * // Prints: true + * console.log(buf.includes(Buffer.from('a buffer'))); + * // Prints: true + * console.log(buf.includes(97)); + * // Prints: true (97 is the decimal ASCII value for 'a') + * console.log(buf.includes(Buffer.from('a buffer example'))); + * // Prints: false + * console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: true + * console.log(buf.includes('this', 4)); + * // Prints: false + * ``` + * @since v5.3.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is its encoding. + * @return `true` if `value` was found in `buf`, `false` otherwise. + */ + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + includes(value: string | number | Buffer, encoding: BufferEncoding): boolean; + } + var Buffer: BufferConstructor; + /** + * Decodes a string of Base64-encoded data into bytes, and encodes those bytes + * into a string using Latin-1 (ISO-8859-1). + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @legacy Use `Buffer.from(data, 'base64')` instead. + * @param data The Base64-encoded input string. + */ + function atob(data: string): string; + /** + * Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes + * into a string using Base64. + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @legacy Use `buf.toString('base64')` instead. + * @param data An ASCII (Latin1) string. + */ + function btoa(data: string): string; + interface Blob extends _Blob {} + /** + * `Blob` class is a global reference for `import { Blob } from 'node:buffer'` + * https://nodejs.org/api/buffer.html#class-blob + * @since v18.0.0 + */ + var Blob: typeof globalThis extends { onmessage: any; Blob: infer T } ? T + : typeof import("buffer").Blob; + interface File extends _File {} + /** + * `File` class is a global reference for `import { File } from 'node:buffer'` + * https://nodejs.org/api/buffer.html#class-file + * @since v20.0.0 + */ + var File: typeof globalThis extends { onmessage: any; File: infer T } ? T + : typeof import("buffer").File; + } +} +declare module "node:buffer" { + export * from "buffer"; +} diff --git a/node_modules/@types/node/child_process.d.ts b/node_modules/@types/node/child_process.d.ts new file mode 100644 index 0000000..313c33c --- /dev/null +++ b/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,1476 @@ +/** + * The `node:child_process` module provides the ability to spawn subprocesses in + * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability + * is primarily provided by the {@link spawn} function: + * + * ```js + * import { spawn } from 'node:child_process'; + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * By default, pipes for `stdin`, `stdout`, and `stderr` are established between + * the parent Node.js process and the spawned subprocess. These pipes have + * limited (and platform-specific) capacity. If the subprocess writes to + * stdout in excess of that limit without the output being captured, the + * subprocess blocks, waiting for the pipe buffer to accept more data. This is + * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }` option if the output will not be consumed. + * + * The command lookup is performed using the `options.env.PATH` environment + * variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is + * used. If `options.env` is set without `PATH`, lookup on Unix is performed + * on a default search path search of `/usr/bin:/bin` (see your operating system's + * manual for execvpe/execvp), on Windows the current processes environment + * variable `PATH` is used. + * + * On Windows, environment variables are case-insensitive. Node.js + * lexicographically sorts the `env` keys and uses the first one that + * case-insensitively matches. Only first (in lexicographic order) entry will be + * passed to the subprocess. This might lead to issues on Windows when passing + * objects to the `env` option that have multiple variants of the same key, such as `PATH` and `Path`. + * + * The {@link spawn} method spawns the child process asynchronously, + * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks + * the event loop until the spawned process either exits or is terminated. + * + * For convenience, the `node:child_process` module provides a handful of + * synchronous and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * top of {@link spawn} or {@link spawnSync}. + * + * * {@link exec}: spawns a shell and runs a command within that + * shell, passing the `stdout` and `stderr` to a callback function when + * complete. + * * {@link execFile}: similar to {@link exec} except + * that it spawns the command directly without first spawning a shell by + * default. + * * {@link fork}: spawns a new Node.js process and invokes a + * specified module with an IPC communication channel established that allows + * sending messages between parent and child. + * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop. + * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop. + * + * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, + * the synchronous methods can have significant impact on performance due to + * stalling the event loop while spawned processes complete. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/child_process.js) + */ +declare module "child_process" { + import { NonSharedBuffer } from "node:buffer"; + import { Abortable, EventEmitter } from "node:events"; + import * as dgram from "node:dgram"; + import * as net from "node:net"; + import { Readable, Stream, Writable } from "node:stream"; + import { URL } from "node:url"; + type Serializable = string | object | number | boolean | bigint; + type SendHandle = net.Socket | net.Server | dgram.Socket | undefined; + /** + * Instances of the `ChildProcess` represent spawned child processes. + * + * Instances of `ChildProcess` are not intended to be created directly. Rather, + * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create + * instances of `ChildProcess`. + * @since v2.2.0 + */ + class ChildProcess extends EventEmitter { + /** + * A `Writable Stream` that represents the child process's `stdin`. + * + * If a child process waits to read all of its input, the child will not continue + * until this stream has been closed via `end()`. + * + * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will + * refer to the same value. + * + * The `subprocess.stdin` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdin: Writable | null; + /** + * A `Readable Stream` that represents the child process's `stdout`. + * + * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will + * refer to the same value. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdout: Readable | null; + /** + * A `Readable Stream` that represents the child process's `stderr`. + * + * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will + * refer to the same value. + * + * The `subprocess.stderr` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stderr: Readable | null; + /** + * The `subprocess.channel` property is a reference to the child's IPC channel. If + * no IPC channel exists, this property is `undefined`. + * @since v7.1.0 + */ + readonly channel?: Control | null; + /** + * A sparse array of pipes to the child process, corresponding with positions in + * the `stdio` option passed to {@link spawn} that have been set + * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and `subprocess.stdio[2]` are also available as `subprocess.stdin`, `subprocess.stdout`, and `subprocess.stderr`, + * respectively. + * + * In the following example, only the child's fd `1` (stdout) is configured as a + * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values + * in the array are `null`. + * + * ```js + * import assert from 'node:assert'; + * import fs from 'node:fs'; + * import child_process from 'node:child_process'; + * + * const subprocess = child_process.spawn('ls', { + * stdio: [ + * 0, // Use parent's stdin for child. + * 'pipe', // Pipe child's stdout to parent. + * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. + * ], + * }); + * + * assert.strictEqual(subprocess.stdio[0], null); + * assert.strictEqual(subprocess.stdio[0], subprocess.stdin); + * + * assert(subprocess.stdout); + * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); + * + * assert.strictEqual(subprocess.stdio[2], null); + * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); + * ``` + * + * The `subprocess.stdio` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.7.10 + */ + readonly stdio: [ + Writable | null, + // stdin + Readable | null, + // stdout + Readable | null, + // stderr + Readable | Writable | null | undefined, + // extra + Readable | Writable | null | undefined, // extra + ]; + /** + * The `subprocess.killed` property indicates whether the child process + * successfully received a signal from `subprocess.kill()`. The `killed` property + * does not indicate that the child process has been terminated. + * @since v0.5.10 + */ + readonly killed: boolean; + /** + * Returns the process identifier (PID) of the child process. If the child process + * fails to spawn due to errors, then the value is `undefined` and `error` is + * emitted. + * + * ```js + * import { spawn } from 'node:child_process'; + * const grep = spawn('grep', ['ssh']); + * + * console.log(`Spawned child pid: ${grep.pid}`); + * grep.stdin.end(); + * ``` + * @since v0.1.90 + */ + readonly pid?: number | undefined; + /** + * The `subprocess.connected` property indicates whether it is still possible to + * send and receive messages from a child process. When `subprocess.connected` is `false`, it is no longer possible to send or receive messages. + * @since v0.7.2 + */ + readonly connected: boolean; + /** + * The `subprocess.exitCode` property indicates the exit code of the child process. + * If the child process is still running, the field will be `null`. + */ + readonly exitCode: number | null; + /** + * The `subprocess.signalCode` property indicates the signal received by + * the child process if any, else `null`. + */ + readonly signalCode: NodeJS.Signals | null; + /** + * The `subprocess.spawnargs` property represents the full list of command-line + * arguments the child process was launched with. + */ + readonly spawnargs: string[]; + /** + * The `subprocess.spawnfile` property indicates the executable file name of + * the child process that is launched. + * + * For {@link fork}, its value will be equal to `process.execPath`. + * For {@link spawn}, its value will be the name of + * the executable file. + * For {@link exec}, its value will be the name of the shell + * in which the child process is launched. + */ + readonly spawnfile: string; + /** + * The `subprocess.kill()` method sends a signal to the child process. If no + * argument is given, the process will be sent the `'SIGTERM'` signal. See [`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function + * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. + * + * ```js + * import { spawn } from 'node:child_process'; + * const grep = spawn('grep', ['ssh']); + * + * grep.on('close', (code, signal) => { + * console.log( + * `child process terminated due to receipt of signal ${signal}`); + * }); + * + * // Send SIGHUP to process. + * grep.kill('SIGHUP'); + * ``` + * + * The `ChildProcess` object may emit an `'error'` event if the signal + * cannot be delivered. Sending a signal to a child process that has already exited + * is not an error but may have unforeseen consequences. Specifically, if the + * process identifier (PID) has been reassigned to another process, the signal will + * be delivered to that process instead which can have unexpected results. + * + * While the function is called `kill`, the signal delivered to the child process + * may not actually terminate the process. + * + * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. + * + * On Windows, where POSIX signals do not exist, the `signal` argument will be + * ignored, and the process will be killed forcefully and abruptly (similar to `'SIGKILL'`). + * See `Signal Events` for more details. + * + * On Linux, child processes of child processes will not be terminated + * when attempting to kill their parent. This is likely to happen when running a + * new process in a shell or with the use of the `shell` option of `ChildProcess`: + * + * ```js + * 'use strict'; + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn( + * 'sh', + * [ + * '-c', + * `node -e "setInterval(() => { + * console.log(process.pid, 'is alive') + * }, 500);"`, + * ], { + * stdio: ['inherit', 'inherit', 'inherit'], + * }, + * ); + * + * setTimeout(() => { + * subprocess.kill(); // Does not terminate the Node.js process in the shell. + * }, 2000); + * ``` + * @since v0.1.90 + */ + kill(signal?: NodeJS.Signals | number): boolean; + /** + * Calls {@link ChildProcess.kill} with `'SIGTERM'`. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + /** + * When an IPC channel has been established between the parent and child ( + * i.e. when using {@link fork}), the `subprocess.send()` method can + * be used to send messages to the child process. When the child process is a + * Node.js instance, these messages can be received via the `'message'` event. + * + * The message goes through serialization and parsing. The resulting + * message might not be the same as what is originally sent. + * + * For example, in the parent script: + * + * ```js + * import cp from 'node:child_process'; + * const n = cp.fork(`${__dirname}/sub.js`); + * + * n.on('message', (m) => { + * console.log('PARENT got message:', m); + * }); + * + * // Causes the child to print: CHILD got message: { hello: 'world' } + * n.send({ hello: 'world' }); + * ``` + * + * And then the child script, `'sub.js'` might look like this: + * + * ```js + * process.on('message', (m) => { + * console.log('CHILD got message:', m); + * }); + * + * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } + * process.send({ foo: 'bar', baz: NaN }); + * ``` + * + * Child Node.js processes will have a `process.send()` method of their own + * that allows the child to send messages back to the parent. + * + * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages + * containing a `NODE_` prefix in the `cmd` property are reserved for use within + * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the `'internalMessage'` event and are consumed internally by Node.js. + * Applications should avoid using such messages or listening for `'internalMessage'` events as it is subject to change without notice. + * + * The optional `sendHandle` argument that may be passed to `subprocess.send()` is + * for passing a TCP server or socket object to the child process. The child will + * receive the object as the second argument passed to the callback function + * registered on the `'message'` event. Any data that is received and buffered in + * the socket will not be sent to the child. Sending IPC sockets is not supported on Windows. + * + * The optional `callback` is a function that is invoked after the message is + * sent but before the child may have received it. The function is called with a + * single argument: `null` on success, or an `Error` object on failure. + * + * If no `callback` function is provided and the message cannot be sent, an `'error'` event will be emitted by the `ChildProcess` object. This can + * happen, for instance, when the child process has already exited. + * + * `subprocess.send()` will return `false` if the channel has closed or when the + * backlog of unsent messages exceeds a threshold that makes it unwise to send + * more. Otherwise, the method returns `true`. The `callback` function can be + * used to implement flow control. + * + * #### Example: sending a server object + * + * The `sendHandle` argument can be used, for instance, to pass the handle of + * a TCP server object to the child process as illustrated in the example below: + * + * ```js + * import { createServer } from 'node:net'; + * import { fork } from 'node:child_process'; + * const subprocess = fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = createServer(); + * server.on('connection', (socket) => { + * socket.end('handled by parent'); + * }); + * server.listen(1337, () => { + * subprocess.send('server', server); + * }); + * ``` + * + * The child would then receive the server object as: + * + * ```js + * process.on('message', (m, server) => { + * if (m === 'server') { + * server.on('connection', (socket) => { + * socket.end('handled by child'); + * }); + * } + * }); + * ``` + * + * Once the server is now shared between the parent and child, some connections + * can be handled by the parent and some by the child. + * + * While the example above uses a server created using the `node:net` module, `node:dgram` module servers use exactly the same workflow with the exceptions of + * listening on a `'message'` event instead of `'connection'` and using `server.bind()` instead of `server.listen()`. This is, however, only + * supported on Unix platforms. + * + * #### Example: sending a socket object + * + * Similarly, the `sendHandler` argument can be used to pass the handle of a + * socket to the child process. The example below spawns two children that each + * handle connections with "normal" or "special" priority: + * + * ```js + * import { createServer } from 'node:net'; + * import { fork } from 'node:child_process'; + * const normal = fork('subprocess.js', ['normal']); + * const special = fork('subprocess.js', ['special']); + * + * // Open up the server and send sockets to child. Use pauseOnConnect to prevent + * // the sockets from being read before they are sent to the child process. + * const server = createServer({ pauseOnConnect: true }); + * server.on('connection', (socket) => { + * + * // If this is special priority... + * if (socket.remoteAddress === '74.125.127.100') { + * special.send('socket', socket); + * return; + * } + * // This is normal priority. + * normal.send('socket', socket); + * }); + * server.listen(1337); + * ``` + * + * The `subprocess.js` would receive the socket handle as the second argument + * passed to the event callback function: + * + * ```js + * process.on('message', (m, socket) => { + * if (m === 'socket') { + * if (socket) { + * // Check that the client socket exists. + * // It is possible for the socket to be closed between the time it is + * // sent and the time it is received in the child process. + * socket.end(`Request handled with ${process.argv[2]} priority`); + * } + * } + * }); + * ``` + * + * Do not use `.maxConnections` on a socket that has been passed to a subprocess. + * The parent cannot track when the socket is destroyed. + * + * Any `'message'` handlers in the subprocess should verify that `socket` exists, + * as the connection may have been closed during the time it takes to send the + * connection to the child. + * @since v0.5.9 + * @param sendHandle `undefined`, or a [`net.Socket`](https://nodejs.org/docs/latest-v22.x/api/net.html#class-netsocket), [`net.Server`](https://nodejs.org/docs/latest-v22.x/api/net.html#class-netserver), or [`dgram.Socket`](https://nodejs.org/docs/latest-v22.x/api/dgram.html#class-dgramsocket) object. + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: Serializable, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; + send( + message: Serializable, + sendHandle?: SendHandle, + options?: MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * Closes the IPC channel between parent and child, allowing the child to exit + * gracefully once there are no other connections keeping it alive. After calling + * this method the `subprocess.connected` and `process.connected` properties in + * both the parent and child (respectively) will be set to `false`, and it will be + * no longer possible to pass messages between the processes. + * + * The `'disconnect'` event will be emitted when there are no messages in the + * process of being received. This will most often be triggered immediately after + * calling `subprocess.disconnect()`. + * + * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked + * within the child process to close the IPC channel as well. + * @since v0.7.2 + */ + disconnect(): void; + /** + * By default, the parent will wait for the detached child to exit. To prevent the + * parent from waiting for a given `subprocess` to exit, use the `subprocess.unref()` method. Doing so will cause the parent's event loop to not + * include the child in its reference count, allowing the parent to exit + * independently of the child, unless there is an established IPC channel between + * the child and the parent. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * ``` + * @since v0.7.10 + */ + unref(): void; + /** + * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will + * restore the removed reference count for the child process, forcing the parent + * to wait for the child to exit before exiting itself. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * subprocess.ref(); + * ``` + * @since v0.7.10 + */ + ref(): void; + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + * 6. spawn + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + addListener(event: "spawn", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "message", message: Serializable, sendHandle: SendHandle): boolean; + emit(event: "spawn", listener: () => void): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + on(event: "spawn", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + once(event: "spawn", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependListener(event: "spawn", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "close", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "exit", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependOnceListener(event: "spawn", listener: () => void): this; + } + // return this object when stdio option is undefined or not specified + interface ChildProcessWithoutNullStreams extends ChildProcess { + stdin: Writable; + stdout: Readable; + stderr: Readable; + readonly stdio: [ + Writable, + Readable, + Readable, + // stderr + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + // return this object when stdio option is a tuple of 3 + interface ChildProcessByStdio + extends ChildProcess + { + stdin: I; + stdout: O; + stderr: E; + readonly stdio: [ + I, + O, + E, + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + interface Control extends EventEmitter { + ref(): void; + unref(): void; + } + interface MessageOptions { + keepOpen?: boolean | undefined; + } + type IOType = "overlapped" | "pipe" | "ignore" | "inherit"; + type StdioOptions = IOType | Array; + type SerializationType = "json" | "advanced"; + interface MessagingOptions extends Abortable { + /** + * Specify the kind of serialization used for sending messages between processes. + * @default 'json' + */ + serialization?: SerializationType | undefined; + /** + * The signal value to be used when the spawned process will be killed by the abort signal. + * @default 'SIGTERM' + */ + killSignal?: NodeJS.Signals | number | undefined; + /** + * In milliseconds the maximum amount of time the process is allowed to run. + */ + timeout?: number | undefined; + } + interface ProcessEnvOptions { + uid?: number | undefined; + gid?: number | undefined; + cwd?: string | URL | undefined; + env?: NodeJS.ProcessEnv | undefined; + } + interface CommonOptions extends ProcessEnvOptions { + /** + * @default false + */ + windowsHide?: boolean | undefined; + /** + * @default 0 + */ + timeout?: number | undefined; + } + interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { + argv0?: string | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + shell?: boolean | string | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + interface SpawnOptions extends CommonSpawnOptions { + detached?: boolean | undefined; + } + interface SpawnOptionsWithoutStdio extends SpawnOptions { + stdio?: StdioPipeNamed | StdioPipe[] | undefined; + } + type StdioNull = "inherit" | "ignore" | Stream; + type StdioPipeNamed = "pipe" | "overlapped"; + type StdioPipe = undefined | null | StdioPipeNamed; + interface SpawnOptionsWithStdioTuple< + Stdin extends StdioNull | StdioPipe, + Stdout extends StdioNull | StdioPipe, + Stderr extends StdioNull | StdioPipe, + > extends SpawnOptions { + stdio: [Stdin, Stdout, Stderr]; + } + /** + * The `child_process.spawn()` method spawns a new process using the given `command`, with command-line arguments in `args`. If omitted, `args` defaults + * to an empty array. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * A third argument may be used to specify additional options, with these defaults: + * + * ```js + * const defaults = { + * cwd: undefined, + * env: process.env, + * }; + * ``` + * + * Use `cwd` to specify the working directory from which the process is spawned. + * If not given, the default is to inherit the current working directory. If given, + * but the path does not exist, the child process emits an `ENOENT` error + * and exits immediately. `ENOENT` is also emitted when the command + * does not exist. + * + * Use `env` to specify environment variables that will be visible to the new + * process, the default is `process.env`. + * + * `undefined` values in `env` will be ignored. + * + * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the + * exit code: + * + * ```js + * import { spawn } from 'node:child_process'; + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * Example: A very elaborate way to run `ps ax | grep ssh` + * + * ```js + * import { spawn } from 'node:child_process'; + * const ps = spawn('ps', ['ax']); + * const grep = spawn('grep', ['ssh']); + * + * ps.stdout.on('data', (data) => { + * grep.stdin.write(data); + * }); + * + * ps.stderr.on('data', (data) => { + * console.error(`ps stderr: ${data}`); + * }); + * + * ps.on('close', (code) => { + * if (code !== 0) { + * console.log(`ps process exited with code ${code}`); + * } + * grep.stdin.end(); + * }); + * + * grep.stdout.on('data', (data) => { + * console.log(data.toString()); + * }); + * + * grep.stderr.on('data', (data) => { + * console.error(`grep stderr: ${data}`); + * }); + * + * grep.on('close', (code) => { + * if (code !== 0) { + * console.log(`grep process exited with code ${code}`); + * } + * }); + * ``` + * + * Example of checking for failed `spawn`: + * + * ```js + * import { spawn } from 'node:child_process'; + * const subprocess = spawn('bad_command'); + * + * subprocess.on('error', (err) => { + * console.error('Failed to start subprocess.'); + * }); + * ``` + * + * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process + * title while others (Windows, SunOS) will use `command`. + * + * Node.js overwrites `argv[0]` with `process.execPath` on startup, so `process.argv[0]` in a Node.js child process will not match the `argv0` parameter passed to `spawn` from the parent. Retrieve + * it with the `process.argv0` property instead. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { spawn } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const grep = spawn('grep', ['ssh'], { signal }); + * grep.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * ``` + * @since v0.1.90 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptions): ChildProcess; + // overloads of spawn with 'args' + function spawn( + command: string, + args?: readonly string[], + options?: SpawnOptionsWithoutStdio, + ): ChildProcessWithoutNullStreams; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, args: readonly string[], options: SpawnOptions): ChildProcess; + interface ExecOptions extends CommonOptions { + shell?: string | undefined; + signal?: AbortSignal | undefined; + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + encoding?: string | null | undefined; + } + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding?: BufferEncoding | undefined; + } + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: "buffer" | null; // specify `null`. + } + // TODO: Just Plain Wrong™ (see also nodejs/node#57392) + interface ExecException extends Error { + cmd?: string; + killed?: boolean; + code?: number; + signal?: NodeJS.Signals; + stdout?: string; + stderr?: string; + } + /** + * Spawns a shell then executes the `command` within that shell, buffering any + * generated output. The `command` string passed to the exec function is processed + * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) + * need to be dealt with accordingly: + * + * ```js + * import { exec } from 'node:child_process'; + * + * exec('"/path/to/test file/test.sh" arg1 arg2'); + * // Double quotes are used so that the space in the path is not interpreted as + * // a delimiter of multiple arguments. + * + * exec('echo "The \\$HOME variable is $HOME"'); + * // The $HOME variable is escaped in the first instance, but not in the second. + * ``` + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * + * If a `callback` function is provided, it is called with the arguments `(error, stdout, stderr)`. On success, `error` will be `null`. On error, `error` will be an instance of `Error`. The + * `error.code` property will be + * the exit code of the process. By convention, any exit code other than `0` indicates an error. `error.signal` will be the signal that terminated the + * process. + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * ```js + * import { exec } from 'node:child_process'; + * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { + * if (error) { + * console.error(`exec error: ${error}`); + * return; + * } + * console.log(`stdout: ${stdout}`); + * console.error(`stderr: ${stderr}`); + * }); + * ``` + * + * If `timeout` is greater than `0`, the parent will send the signal + * identified by the `killSignal` property (the default is `'SIGTERM'`) if the + * child runs longer than `timeout` milliseconds. + * + * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace + * the existing process and uses a shell to execute the command. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * import util from 'node:util'; + * import child_process from 'node:child_process'; + * const exec = util.promisify(child_process.exec); + * + * async function lsExample() { + * const { stdout, stderr } = await exec('ls'); + * console.log('stdout:', stdout); + * console.error('stderr:', stderr); + * } + * lsExample(); + * ``` + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { exec } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.90 + * @param command The command to run, with space-separated arguments. + * @param callback called with the output when process terminates. + */ + function exec( + command: string, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec( + command: string, + options: ExecOptionsWithBufferEncoding, + callback?: (error: ExecException | null, stdout: NonSharedBuffer, stderr: NonSharedBuffer) => void, + ): ChildProcess; + // `options` with well-known or absent `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: ExecOptionsWithStringEncoding, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: ExecOptions | undefined | null, + callback?: ( + error: ExecException | null, + stdout: string | NonSharedBuffer, + stderr: string | NonSharedBuffer, + ) => void, + ): ChildProcess; + interface PromiseWithChild extends Promise { + child: ChildProcess; + } + namespace exec { + function __promisify__(command: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: NonSharedBuffer; + stderr: NonSharedBuffer; + }>; + function __promisify__( + command: string, + options: ExecOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | NonSharedBuffer; + stderr: string | NonSharedBuffer; + }>; + } + interface ExecFileOptions extends CommonOptions, Abortable { + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + windowsVerbatimArguments?: boolean | undefined; + shell?: boolean | string | undefined; + signal?: AbortSignal | undefined; + encoding?: string | null | undefined; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding?: BufferEncoding | undefined; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: "buffer" | null; + } + /** @deprecated Use `ExecFileOptions` instead. */ + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions {} + // TODO: execFile exceptions can take many forms... this accurately describes none of them + type ExecFileException = + & Omit + & Omit + & { code?: string | number | null }; + /** + * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified + * executable `file` is spawned directly as a new process making it slightly more + * efficient than {@link exec}. + * + * The same options as {@link exec} are supported. Since a shell is + * not spawned, behaviors such as I/O redirection and file globbing are not + * supported. + * + * ```js + * import { execFile } from 'node:child_process'; + * const child = execFile('node', ['--version'], (error, stdout, stderr) => { + * if (error) { + * throw error; + * } + * console.log(stdout); + * }); + * ``` + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * import util from 'node:util'; + * import child_process from 'node:child_process'; + * const execFile = util.promisify(child_process.execFile); + * async function getVersion() { + * const { stdout } = await execFile('node', ['--version']); + * console.log(stdout); + * } + * getVersion(); + * ``` + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { execFile } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.91 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @param callback Called with the output when process terminates. + */ + // no `options` definitely means stdout/stderr are `string`. + function execFile( + file: string, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile( + file: string, + options: ExecFileOptionsWithBufferEncoding, + callback?: (error: ExecFileException | null, stdout: NonSharedBuffer, stderr: NonSharedBuffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback?: (error: ExecFileException | null, stdout: NonSharedBuffer, stderr: NonSharedBuffer) => void, + ): ChildProcess; + // `options` with well-known or absent `encoding` means stdout/stderr are definitely `string`. + function execFile( + file: string, + options: ExecFileOptionsWithStringEncoding, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: ExecFileOptions | undefined | null, + callback: + | (( + error: ExecFileException | null, + stdout: string | NonSharedBuffer, + stderr: string | NonSharedBuffer, + ) => void) + | undefined + | null, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions | undefined | null, + callback: + | (( + error: ExecFileException | null, + stdout: string | NonSharedBuffer, + stderr: string | NonSharedBuffer, + ) => void) + | undefined + | null, + ): ChildProcess; + namespace execFile { + function __promisify__(file: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: NonSharedBuffer; + stderr: NonSharedBuffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: NonSharedBuffer; + stderr: NonSharedBuffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | NonSharedBuffer; + stderr: string | NonSharedBuffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | NonSharedBuffer; + stderr: string | NonSharedBuffer; + }>; + } + interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { + execPath?: string | undefined; + execArgv?: string[] | undefined; + silent?: boolean | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + detached?: boolean | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + /** + * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. + * Like {@link spawn}, a `ChildProcess` object is returned. The + * returned `ChildProcess` will have an additional communication channel + * built-in that allows messages to be passed back and forth between the parent and + * child. See `subprocess.send()` for details. + * + * Keep in mind that spawned Node.js child processes are + * independent of the parent with exception of the IPC communication channel + * that is established between the two. Each process has its own memory, with + * their own V8 instances. Because of the additional resource allocations + * required, spawning a large number of child Node.js processes is not + * recommended. + * + * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the `options` object allows for an alternative + * execution path to be used. + * + * Node.js processes launched with a custom `execPath` will communicate with the + * parent process using the file descriptor (fd) identified using the + * environment variable `NODE_CHANNEL_FD` on the child process. + * + * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the + * current process. + * + * The `shell` option available in {@link spawn} is not supported by `child_process.fork()` and will be ignored if set. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * if (process.argv[2] === 'child') { + * setTimeout(() => { + * console.log(`Hello from ${process.argv[2]}!`); + * }, 1_000); + * } else { + * import { fork } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = fork(__filename, ['child'], { signal }); + * child.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * } + * ``` + * @since v0.5.0 + * @param modulePath The module to run in the child. + * @param args List of string arguments. + */ + function fork(modulePath: string | URL, options?: ForkOptions): ChildProcess; + function fork(modulePath: string | URL, args?: readonly string[], options?: ForkOptions): ChildProcess; + interface SpawnSyncOptions extends CommonSpawnOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding?: "buffer" | null | undefined; + } + interface SpawnSyncReturns { + pid: number; + output: Array; + stdout: T; + stderr: T; + status: number | null; + signal: NodeJS.Signals | null; + error?: Error; + } + /** + * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the process intercepts and handles the `SIGTERM` signal + * and doesn't exit, the parent process will wait until the child process has + * exited. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args: readonly string[]): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithStringEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithBufferEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args?: readonly string[], + options?: SpawnSyncOptions, + ): SpawnSyncReturns; + interface CommonExecOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + /** + * Can be set to 'pipe', 'inherit, or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + killSignal?: NodeJS.Signals | number | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface ExecSyncOptions extends CommonExecOptions { + shell?: string | undefined; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding?: "buffer" | null | undefined; + } + /** + * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the child process intercepts and handles the `SIGTERM` signal and doesn't exit, the parent process will wait until the child process + * has exited. + * + * If the process times out or has a non-zero exit code, this method will throw. + * The `Error` object will contain the entire result from {@link spawnSync}. + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @return The stdout from the command. + */ + function execSync(command: string): NonSharedBuffer; + function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): NonSharedBuffer; + function execSync(command: string, options?: ExecSyncOptions): string | NonSharedBuffer; + interface ExecFileSyncOptions extends CommonExecOptions { + shell?: boolean | string | undefined; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding?: "buffer" | null | undefined; // specify `null`. + } + /** + * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not + * return until the child process has fully closed. When a timeout has been + * encountered and `killSignal` is sent, the method won't return until the process + * has completely exited. + * + * If the child process intercepts and handles the `SIGTERM` signal and + * does not exit, the parent process will still wait until the child process has + * exited. + * + * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @return The stdout from the command. + */ + function execFileSync(file: string): NonSharedBuffer; + function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): NonSharedBuffer; + function execFileSync(file: string, options?: ExecFileSyncOptions): string | NonSharedBuffer; + function execFileSync(file: string, args: readonly string[]): NonSharedBuffer; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithStringEncoding, + ): string; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithBufferEncoding, + ): NonSharedBuffer; + function execFileSync( + file: string, + args?: readonly string[], + options?: ExecFileSyncOptions, + ): string | NonSharedBuffer; +} +declare module "node:child_process" { + export * from "child_process"; +} diff --git a/node_modules/@types/node/cluster.d.ts b/node_modules/@types/node/cluster.d.ts new file mode 100644 index 0000000..eab9783 --- /dev/null +++ b/node_modules/@types/node/cluster.d.ts @@ -0,0 +1,578 @@ +/** + * Clusters of Node.js processes can be used to run multiple instances of Node.js + * that can distribute workloads among their application threads. When process isolation + * is not needed, use the [`worker_threads`](https://nodejs.org/docs/latest-v22.x/api/worker_threads.html) + * module instead, which allows running multiple application threads within a single Node.js instance. + * + * The cluster module allows easy creation of child processes that all share + * server ports. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('exit', (worker, code, signal) => { + * console.log(`worker ${worker.process.pid} died`); + * }); + * } else { + * // Workers can share any TCP connection + * // In this case it is an HTTP server + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * + * console.log(`Worker ${process.pid} started`); + * } + * ``` + * + * Running Node.js will now share port 8000 between the workers: + * + * ```console + * $ node server.js + * Primary 3596 is running + * Worker 4324 started + * Worker 4520 started + * Worker 6056 started + * Worker 5644 started + * ``` + * + * On Windows, it is not yet possible to set up a named pipe server in a worker. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/cluster.js) + */ +declare module "cluster" { + import * as child from "node:child_process"; + import EventEmitter = require("node:events"); + import * as net from "node:net"; + type SerializationType = "json" | "advanced"; + export interface ClusterSettings { + /** + * List of string arguments passed to the Node.js executable. + * @default process.execArgv + */ + execArgv?: string[] | undefined; + /** + * File path to worker file. + * @default process.argv[1] + */ + exec?: string | undefined; + /** + * String arguments passed to worker. + * @default process.argv.slice(2) + */ + args?: readonly string[] | undefined; + /** + * Whether or not to send output to parent's stdio. + * @default false + */ + silent?: boolean | undefined; + /** + * Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must + * contain an `'ipc'` entry. When this option is provided, it overrides `silent`. See [`child_prcess.spawn()`](https://nodejs.org/docs/latest-v22.x/api/child_process.html#child_processspawncommand-args-options)'s + * [`stdio`](https://nodejs.org/docs/latest-v22.x/api/child_process.html#optionsstdio). + */ + stdio?: any[] | undefined; + /** + * Sets the user identity of the process. (See [`setuid(2)`](https://man7.org/linux/man-pages/man2/setuid.2.html).) + */ + uid?: number | undefined; + /** + * Sets the group identity of the process. (See [`setgid(2)`](https://man7.org/linux/man-pages/man2/setgid.2.html).) + */ + gid?: number | undefined; + /** + * Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. + * By default each worker gets its own port, incremented from the primary's `process.debugPort`. + */ + inspectPort?: number | (() => number) | undefined; + /** + * Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. + * See [Advanced serialization for `child_process`](https://nodejs.org/docs/latest-v22.x/api/child_process.html#advanced-serialization) for more details. + * @default false + */ + serialization?: SerializationType | undefined; + /** + * Current working directory of the worker process. + * @default undefined (inherits from parent process) + */ + cwd?: string | undefined; + /** + * Hide the forked processes console window that would normally be created on Windows systems. + * @default false + */ + windowsHide?: boolean | undefined; + } + export interface Address { + address: string; + port: number; + /** + * The `addressType` is one of: + * + * * `4` (TCPv4) + * * `6` (TCPv6) + * * `-1` (Unix domain socket) + * * `'udp4'` or `'udp6'` (UDPv4 or UDPv6) + */ + addressType: 4 | 6 | -1 | "udp4" | "udp6"; + } + /** + * A `Worker` object contains all public information and method about a worker. + * In the primary it can be obtained using `cluster.workers`. In a worker + * it can be obtained using `cluster.worker`. + * @since v0.7.0 + */ + export class Worker extends EventEmitter { + /** + * Each new worker is given its own unique id, this id is stored in the `id`. + * + * While a worker is alive, this is the key that indexes it in `cluster.workers`. + * @since v0.8.0 + */ + id: number; + /** + * All workers are created using [`child_process.fork()`](https://nodejs.org/docs/latest-v22.x/api/child_process.html#child_processforkmodulepath-args-options), the returned object + * from this function is stored as `.process`. In a worker, the global `process` is stored. + * + * See: [Child Process module](https://nodejs.org/docs/latest-v22.x/api/child_process.html#child_processforkmodulepath-args-options). + * + * Workers will call `process.exit(0)` if the `'disconnect'` event occurs + * on `process` and `.exitedAfterDisconnect` is not `true`. This protects against + * accidental disconnection. + * @since v0.7.0 + */ + process: child.ChildProcess; + /** + * Send a message to a worker or primary, optionally with a handle. + * + * In the primary, this sends a message to a specific worker. It is identical to [`ChildProcess.send()`](https://nodejs.org/docs/latest-v22.x/api/child_process.html#subprocesssendmessage-sendhandle-options-callback). + * + * In a worker, this sends a message to the primary. It is identical to `process.send()`. + * + * This example will echo back all messages from the primary: + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * worker.send('hi there'); + * + * } else if (cluster.isWorker) { + * process.on('message', (msg) => { + * process.send(msg); + * }); + * } + * ``` + * @since v0.7.0 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. + */ + send(message: child.Serializable, callback?: (error: Error | null) => void): boolean; + send( + message: child.Serializable, + sendHandle: child.SendHandle, + callback?: (error: Error | null) => void, + ): boolean; + send( + message: child.Serializable, + sendHandle: child.SendHandle, + options?: child.MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * This function will kill the worker. In the primary worker, it does this by + * disconnecting the `worker.process`, and once disconnected, killing with `signal`. In the worker, it does it by killing the process with `signal`. + * + * The `kill()` function kills the worker process without waiting for a graceful + * disconnect, it has the same behavior as `worker.process.kill()`. + * + * This method is aliased as `worker.destroy()` for backwards compatibility. + * + * In a worker, `process.kill()` exists, but it is not this function; + * it is [`kill()`](https://nodejs.org/docs/latest-v22.x/api/process.html#processkillpid-signal). + * @since v0.9.12 + * @param [signal='SIGTERM'] Name of the kill signal to send to the worker process. + */ + kill(signal?: string): void; + destroy(signal?: string): void; + /** + * In a worker, this function will close all servers, wait for the `'close'` event + * on those servers, and then disconnect the IPC channel. + * + * In the primary, an internal message is sent to the worker causing it to call `.disconnect()` on itself. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * After a server is closed, it will no longer accept new connections, + * but connections may be accepted by any other listening worker. Existing + * connections will be allowed to close as usual. When no more connections exist, + * see `server.close()`, the IPC channel to the worker will close allowing it + * to die gracefully. + * + * The above applies _only_ to server connections, client connections are not + * automatically closed by workers, and disconnect does not wait for them to close + * before exiting. + * + * In a worker, `process.disconnect` exists, but it is not this function; + * it is `disconnect()`. + * + * Because long living server connections may block workers from disconnecting, it + * may be useful to send a message, so application specific actions may be taken to + * close them. It also may be useful to implement a timeout, killing a worker if + * the `'disconnect'` event has not been emitted after some time. + * + * ```js + * import net from 'node:net'; + * + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * let timeout; + * + * worker.on('listening', (address) => { + * worker.send('shutdown'); + * worker.disconnect(); + * timeout = setTimeout(() => { + * worker.kill(); + * }, 2000); + * }); + * + * worker.on('disconnect', () => { + * clearTimeout(timeout); + * }); + * + * } else if (cluster.isWorker) { + * const server = net.createServer((socket) => { + * // Connections never end + * }); + * + * server.listen(8000); + * + * process.on('message', (msg) => { + * if (msg === 'shutdown') { + * // Initiate graceful close of any connections to server + * } + * }); + * } + * ``` + * @since v0.7.7 + * @return A reference to `worker`. + */ + disconnect(): this; + /** + * This function returns `true` if the worker is connected to its primary via its + * IPC channel, `false` otherwise. A worker is connected to its primary after it + * has been created. It is disconnected after the `'disconnect'` event is emitted. + * @since v0.11.14 + */ + isConnected(): boolean; + /** + * This function returns `true` if the worker's process has terminated (either + * because of exiting or being signaled). Otherwise, it returns `false`. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('fork', (worker) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * + * cluster.on('exit', (worker, code, signal) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * } else { + * // Workers can share any TCP connection. In this case, it is an HTTP server. + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end(`Current process\n ${process.pid}`); + * process.kill(process.pid); + * }).listen(8000); + * } + * ``` + * @since v0.11.14 + */ + isDead(): boolean; + /** + * This property is `true` if the worker exited due to `.disconnect()`. + * If the worker exited any other way, it is `false`. If the + * worker has not exited, it is `undefined`. + * + * The boolean `worker.exitedAfterDisconnect` allows distinguishing between + * voluntary and accidental exit, the primary may choose not to respawn a worker + * based on this value. + * + * ```js + * cluster.on('exit', (worker, code, signal) => { + * if (worker.exitedAfterDisconnect === true) { + * console.log('Oh, it was just voluntary – no need to worry'); + * } + * }); + * + * // kill worker + * worker.kill(); + * ``` + * @since v6.0.0 + */ + exitedAfterDisconnect: boolean; + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "listening", address: Address): boolean; + emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; + } + export interface Cluster extends EventEmitter { + disconnect(callback?: () => void): void; + /** + * Spawn a new worker process. + * + * This can only be called from the primary process. + * @param env Key/value pairs to add to worker process environment. + * @since v0.6.0 + */ + fork(env?: any): Worker; + /** @deprecated since v16.0.0 - use isPrimary. */ + readonly isMaster: boolean; + /** + * True if the process is a primary. This is determined by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` + * is undefined, then `isPrimary` is `true`. + * @since v16.0.0 + */ + readonly isPrimary: boolean; + /** + * True if the process is not a primary (it is the negation of `cluster.isPrimary`). + * @since v0.6.0 + */ + readonly isWorker: boolean; + /** + * The scheduling policy, either `cluster.SCHED_RR` for round-robin or `cluster.SCHED_NONE` to leave it to the operating system. This is a + * global setting and effectively frozen once either the first worker is spawned, or [`.setupPrimary()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clustersetupprimarysettings) + * is called, whichever comes first. + * + * `SCHED_RR` is the default on all operating systems except Windows. Windows will change to `SCHED_RR` once libuv is able to effectively distribute + * IOCP handles without incurring a large performance hit. + * + * `cluster.schedulingPolicy` can also be set through the `NODE_CLUSTER_SCHED_POLICY` environment variable. Valid values are `'rr'` and `'none'`. + * @since v0.11.2 + */ + schedulingPolicy: number; + /** + * After calling [`.setupPrimary()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clustersetupprimarysettings) + * (or [`.fork()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clusterforkenv)) this settings object will contain + * the settings, including the default values. + * + * This object is not intended to be changed or set manually. + * @since v0.7.1 + */ + readonly settings: ClusterSettings; + /** @deprecated since v16.0.0 - use [`.setupPrimary()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clustersetupprimarysettings) instead. */ + setupMaster(settings?: ClusterSettings): void; + /** + * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in `cluster.settings`. + * + * Any settings changes only affect future calls to [`.fork()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clusterforkenv) + * and have no effect on workers that are already running. + * + * The only attribute of a worker that cannot be set via `.setupPrimary()` is the `env` passed to + * [`.fork()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clusterforkenv). + * + * The defaults above apply to the first call only; the defaults for later calls are the current values at the time of + * `cluster.setupPrimary()` is called. + * + * ```js + * import cluster from 'node:cluster'; + * + * cluster.setupPrimary({ + * exec: 'worker.js', + * args: ['--use', 'https'], + * silent: true, + * }); + * cluster.fork(); // https worker + * cluster.setupPrimary({ + * exec: 'worker.js', + * args: ['--use', 'http'], + * }); + * cluster.fork(); // http worker + * ``` + * + * This can only be called from the primary process. + * @since v16.0.0 + */ + setupPrimary(settings?: ClusterSettings): void; + /** + * A reference to the current worker object. Not available in the primary process. + * + * ```js + * import cluster from 'node:cluster'; + * + * if (cluster.isPrimary) { + * console.log('I am primary'); + * cluster.fork(); + * cluster.fork(); + * } else if (cluster.isWorker) { + * console.log(`I am worker #${cluster.worker.id}`); + * } + * ``` + * @since v0.7.0 + */ + readonly worker?: Worker; + /** + * A hash that stores the active worker objects, keyed by `id` field. This makes it easy to loop through all the workers. It is only available in the primary process. + * + * A worker is removed from `cluster.workers` after the worker has disconnected _and_ exited. The order between these two events cannot be determined in advance. However, it + * is guaranteed that the removal from the `cluster.workers` list happens before the last `'disconnect'` or `'exit'` event is emitted. + * + * ```js + * import cluster from 'node:cluster'; + * + * for (const worker of Object.values(cluster.workers)) { + * worker.send('big announcement to all workers'); + * } + * ``` + * @since v0.7.0 + */ + readonly workers?: NodeJS.Dict; + readonly SCHED_NONE: number; + readonly SCHED_RR: number; + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect", worker: Worker): boolean; + emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + emit(event: "fork", worker: Worker): boolean; + emit(event: "listening", worker: Worker, address: Address): boolean; + emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online", worker: Worker): boolean; + emit(event: "setup", settings: ClusterSettings): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: ClusterSettings) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: ClusterSettings) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + } + const cluster: Cluster; + export default cluster; +} +declare module "node:cluster" { + export * from "cluster"; + export { default as default } from "cluster"; +} diff --git a/node_modules/@types/node/compatibility/disposable.d.ts b/node_modules/@types/node/compatibility/disposable.d.ts new file mode 100644 index 0000000..e23d5a7 --- /dev/null +++ b/node_modules/@types/node/compatibility/disposable.d.ts @@ -0,0 +1,14 @@ +// Polyfills for the explicit resource management types added in TypeScript 5.2. + +interface SymbolConstructor { + readonly dispose: unique symbol; + readonly asyncDispose: unique symbol; +} + +interface Disposable { + [Symbol.dispose](): void; +} + +interface AsyncDisposable { + [Symbol.asyncDispose](): PromiseLike; +} diff --git a/node_modules/@types/node/compatibility/index.d.ts b/node_modules/@types/node/compatibility/index.d.ts new file mode 100644 index 0000000..5c41e37 --- /dev/null +++ b/node_modules/@types/node/compatibility/index.d.ts @@ -0,0 +1,9 @@ +// Declaration files in this directory contain types relating to TypeScript library features +// that are not included in all TypeScript versions supported by DefinitelyTyped, but +// which can be made backwards-compatible without needing `typesVersions`. +// If adding declarations to this directory, please specify which versions of TypeScript require them, +// so that they can be removed when no longer needed. + +/// +/// +/// diff --git a/node_modules/@types/node/compatibility/indexable.d.ts b/node_modules/@types/node/compatibility/indexable.d.ts new file mode 100644 index 0000000..262ba09 --- /dev/null +++ b/node_modules/@types/node/compatibility/indexable.d.ts @@ -0,0 +1,20 @@ +// Polyfill for ES2022's .at() method on string/array prototypes, added to TypeScript in 4.6. + +interface RelativeIndexable { + at(index: number): T | undefined; +} + +interface String extends RelativeIndexable {} +interface Array extends RelativeIndexable {} +interface ReadonlyArray extends RelativeIndexable {} +interface Int8Array extends RelativeIndexable {} +interface Uint8Array extends RelativeIndexable {} +interface Uint8ClampedArray extends RelativeIndexable {} +interface Int16Array extends RelativeIndexable {} +interface Uint16Array extends RelativeIndexable {} +interface Int32Array extends RelativeIndexable {} +interface Uint32Array extends RelativeIndexable {} +interface Float32Array extends RelativeIndexable {} +interface Float64Array extends RelativeIndexable {} +interface BigInt64Array extends RelativeIndexable {} +interface BigUint64Array extends RelativeIndexable {} diff --git a/node_modules/@types/node/compatibility/iterators.d.ts b/node_modules/@types/node/compatibility/iterators.d.ts new file mode 100644 index 0000000..2f9be9c --- /dev/null +++ b/node_modules/@types/node/compatibility/iterators.d.ts @@ -0,0 +1,20 @@ +// Backwards-compatible iterator interfaces, augmented with iterator helper methods by lib.esnext.iterator in TypeScript 5.6. +// The IterableIterator interface does not contain these methods, which creates assignability issues in places where IteratorObjects +// are expected (eg. DOM-compatible APIs) if lib.esnext.iterator is loaded. +// Also ensures that iterators returned by the Node API, which inherit from Iterator.prototype, correctly expose the iterator helper methods +// if lib.esnext.iterator is loaded. + +// Placeholders for TS <5.6 +interface IteratorObject {} +interface AsyncIteratorObject {} + +declare namespace NodeJS { + // Populate iterator methods for TS <5.6 + interface Iterator extends globalThis.Iterator {} + interface AsyncIterator extends globalThis.AsyncIterator {} + + // Polyfill for TS 5.6's instrinsic BuiltinIteratorReturn type, required for DOM-compatible iterators + type BuiltinIteratorReturn = ReturnType extends + globalThis.Iterator ? TReturn + : any; +} diff --git a/node_modules/@types/node/console.d.ts b/node_modules/@types/node/console.d.ts new file mode 100644 index 0000000..3e4c2d9 --- /dev/null +++ b/node_modules/@types/node/console.d.ts @@ -0,0 +1,452 @@ +/** + * The `node:console` module provides a simple debugging console that is similar to + * the JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()`, and `console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/console.js) + */ +declare module "console" { + import console = require("node:console"); + export = console; +} +declare module "node:console" { + import { InspectOptions } from "node:util"; + global { + // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build + interface Console { + Console: console.ConsoleConstructor; + /** + * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only + * writes a message and does not otherwise affect execution. The output always + * starts with `"Assertion failed"`. If provided, `message` is formatted using + * [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args). + * + * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens. + * + * ```js + * console.assert(true, 'does nothing'); + * + * console.assert(false, 'Whoops %s work', 'didn\'t'); + * // Assertion failed: Whoops didn't work + * + * console.assert(); + * // Assertion failed + * ``` + * @since v0.1.101 + * @param value The value tested for being truthy. + * @param message All arguments besides `value` are used as error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the + * TTY. When `stdout` is not a TTY, this method does nothing. + * + * The specific operation of `console.clear()` can vary across operating systems + * and terminal types. For most Linux operating systems, `console.clear()` operates similarly to the `clear` shell command. On Windows, `console.clear()` will clear only the output in the + * current terminal viewport for the Node.js + * binary. + * @since v8.3.0 + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the + * number of times `console.count()` has been called with the given `label`. + * + * ```js + * > console.count() + * default: 1 + * undefined + * > console.count('default') + * default: 2 + * undefined + * > console.count('abc') + * abc: 1 + * undefined + * > console.count('xyz') + * xyz: 1 + * undefined + * > console.count('abc') + * abc: 2 + * undefined + * > console.count() + * default: 3 + * undefined + * > + * ``` + * @since v8.3.0 + * @param [label='default'] The display label for the counter. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + * + * ```js + * > console.count('abc'); + * abc: 1 + * undefined + * > console.countReset('abc'); + * undefined + * > console.count('abc'); + * abc: 1 + * undefined + * > + * ``` + * @since v8.3.0 + * @param [label='default'] The display label for the counter. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link log}. + * @since v8.0.0 + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses [`util.inspect()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilinspectobject-options) on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + * @since v0.1.101 + */ + dir(obj: any, options?: InspectOptions): void; + /** + * This method calls `console.log()` passing it the arguments received. + * This method does not produce any XML formatting. + * @since v8.0.0 + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) + * (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). + * + * ```js + * const code = 5; + * console.error('error #%d', code); + * // Prints: error #5, to stderr + * console.error('error', code); + * // Prints: error 5, to stderr + * ``` + * + * If formatting elements (e.g. `%d`) are not found in the first string then + * [`util.inspect()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilinspectobject-options) is called on each argument and the + * resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) + * for more information. + * @since v0.1.100 + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by spaces for `groupIndentation` length. + * + * If one or more `label`s are provided, those are printed first without the + * additional indentation. + * @since v8.5.0 + */ + group(...label: any[]): void; + /** + * An alias for {@link group}. + * @since v8.5.0 + */ + groupCollapsed(...label: any[]): void; + /** + * Decreases indentation of subsequent lines by spaces for `groupIndentation` length. + * @since v8.5.0 + */ + groupEnd(): void; + /** + * The `console.info()` function is an alias for {@link log}. + * @since v0.1.100 + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) + * (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). + * + * ```js + * const count = 5; + * console.log('count: %d', count); + * // Prints: count: 5, to stdout + * console.log('count:', count); + * // Prints: count: 5, to stdout + * ``` + * + * See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information. + * @since v0.1.100 + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * Try to construct a table with the columns of the properties of `tabularData` (or use `properties`) and rows of `tabularData` and log it. Falls back to just + * logging the argument if it can't be parsed as tabular. + * + * ```js + * // These can't be parsed as tabular data + * console.table(Symbol()); + * // Symbol() + * + * console.table(undefined); + * // undefined + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); + * // ┌─────────┬─────┬─────┐ + * // │ (index) │ a │ b │ + * // ├─────────┼─────┼─────┤ + * // │ 0 │ 1 │ 'Y' │ + * // │ 1 │ 'Z' │ 2 │ + * // └─────────┴─────┴─────┘ + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); + * // ┌─────────┬─────┐ + * // │ (index) │ a │ + * // ├─────────┼─────┤ + * // │ 0 │ 1 │ + * // │ 1 │ 'Z' │ + * // └─────────┴─────┘ + * ``` + * @since v10.0.0 + * @param properties Alternate properties for constructing the table. + */ + table(tabularData: any, properties?: readonly string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers + * are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in + * suitable time units to `stdout`. For example, if the elapsed + * time is 3869ms, `console.timeEnd()` displays "3.869s". + * @since v0.1.104 + * @param [label='default'] + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link time} and + * prints the result to `stdout`: + * + * ```js + * console.time('bunch-of-stuff'); + * // Do a bunch of stuff. + * console.timeEnd('bunch-of-stuff'); + * // Prints: bunch-of-stuff: 225.438ms + * ``` + * @since v0.1.104 + * @param [label='default'] + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link time}, prints + * the elapsed time and other `data` arguments to `stdout`: + * + * ```js + * console.time('process'); + * const value = expensiveProcess1(); // Returns 42 + * console.timeLog('process', value); + * // Prints "process: 365.227ms 42". + * doExpensiveProcess2(value); + * console.timeEnd('process'); + * ``` + * @since v10.7.0 + * @param [label='default'] + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string `'Trace: '`, followed by the [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) + * formatted message and stack trace to the current position in the code. + * + * ```js + * console.trace('Show me'); + * // Prints: (stack trace will vary based on where trace is called) + * // Trace: Show me + * // at repl:2:9 + * // at REPLServer.defaultEval (repl.js:248:27) + * // at bound (domain.js:287:14) + * // at REPLServer.runBound [as eval] (domain.js:300:12) + * // at REPLServer. (repl.js:412:12) + * // at emitOne (events.js:82:20) + * // at REPLServer.emit (events.js:169:7) + * // at REPLServer.Interface._onLine (readline.js:210:10) + * // at REPLServer.Interface._line (readline.js:549:8) + * // at REPLServer.Interface._ttyWrite (readline.js:826:14) + * ``` + * @since v0.1.104 + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The `console.warn()` function is an alias for {@link error}. + * @since v0.1.100 + */ + warn(message?: any, ...optionalParams: any[]): void; + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. The `console.profile()` + * method starts a JavaScript CPU profile with an optional label until {@link profileEnd} + * is called. The profile is then added to the Profile panel of the inspector. + * + * ```js + * console.profile('MyLabel'); + * // Some code + * console.profileEnd('MyLabel'); + * // Adds the profile 'MyLabel' to the Profiles panel of the inspector. + * ``` + * @since v8.0.0 + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. Stops the current + * JavaScript CPU profiling session if one has been started and prints the report to the + * Profiles panel of the inspector. See {@link profile} for an example. + * + * If this method is called without a label, the most recently started profile is stopped. + * @since v8.0.0 + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. The `console.timeStamp()` + * method adds an event with the label `'label'` to the Timeline panel of the inspector. + * @since v8.0.0 + */ + timeStamp(label?: string): void; + } + /** + * The `console` module provides a simple debugging console that is similar to the + * JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/console.js) + */ + namespace console { + interface ConsoleConstructorOptions { + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; + /** + * Ignore errors when writing to the underlying streams. + * @default true + */ + ignoreErrors?: boolean | undefined; + /** + * Set color support for this `Console` instance. Setting to true enables coloring while inspecting + * values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color + * support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the + * respective stream. This option can not be used, if `inspectOptions.colors` is set as well. + * @default auto + */ + colorMode?: boolean | "auto" | undefined; + /** + * Specifies options that are passed along to + * [`util.inspect()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilinspectobject-options). + */ + inspectOptions?: InspectOptions | undefined; + /** + * Set group indentation. + * @default 2 + */ + groupIndentation?: number | undefined; + } + interface ConsoleConstructor { + prototype: Console; + new(stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; + } + } + var console: Console; + } + export = globalThis.console; +} diff --git a/node_modules/@types/node/constants.d.ts b/node_modules/@types/node/constants.d.ts new file mode 100644 index 0000000..5685a9d --- /dev/null +++ b/node_modules/@types/node/constants.d.ts @@ -0,0 +1,21 @@ +/** + * @deprecated The `node:constants` module is deprecated. When requiring access to constants + * relevant to specific Node.js builtin modules, developers should instead refer + * to the `constants` property exposed by the relevant module. For instance, + * `require('node:fs').constants` and `require('node:os').constants`. + */ +declare module "constants" { + const constants: + & typeof import("node:os").constants.dlopen + & typeof import("node:os").constants.errno + & typeof import("node:os").constants.priority + & typeof import("node:os").constants.signals + & typeof import("node:fs").constants + & typeof import("node:crypto").constants; + export = constants; +} + +declare module "node:constants" { + import constants = require("constants"); + export = constants; +} diff --git a/node_modules/@types/node/crypto.d.ts b/node_modules/@types/node/crypto.d.ts new file mode 100644 index 0000000..9023805 --- /dev/null +++ b/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,4545 @@ +/** + * The `node:crypto` module provides cryptographic functionality that includes a + * set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify + * functions. + * + * ```js + * const { createHmac } = await import('node:crypto'); + * + * const secret = 'abcdefg'; + * const hash = createHmac('sha256', secret) + * .update('I love cupcakes') + * .digest('hex'); + * console.log(hash); + * // Prints: + * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/crypto.js) + */ +declare module "crypto" { + import { NonSharedBuffer } from "node:buffer"; + import * as stream from "node:stream"; + import { PeerCertificate } from "node:tls"; + /** + * SPKAC is a Certificate Signing Request mechanism originally implemented by + * Netscape and was specified formally as part of HTML5's `keygen` element. + * + * `` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects + * should not use this element anymore. + * + * The `node:crypto` module provides the `Certificate` class for working with SPKAC + * data. The most common usage is handling output generated by the HTML5 `` element. Node.js uses [OpenSSL's SPKAC + * implementation](https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html) internally. + * @since v0.11.8 + */ + class Certificate { + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const challenge = Certificate.exportChallenge(spkac); + * console.log(challenge.toString('utf8')); + * // Prints: the challenge as a UTF8 string + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The challenge component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportChallenge(spkac: BinaryLike): NonSharedBuffer; + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const publicKey = Certificate.exportPublicKey(spkac); + * console.log(publicKey); + * // Prints: the public key as + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The public key component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportPublicKey(spkac: BinaryLike, encoding?: string): NonSharedBuffer; + /** + * ```js + * import { Buffer } from 'node:buffer'; + * const { Certificate } = await import('node:crypto'); + * + * const spkac = getSpkacSomehow(); + * console.log(Certificate.verifySpkac(Buffer.from(spkac))); + * // Prints: true or false + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return `true` if the given `spkac` data structure is valid, `false` otherwise. + */ + static verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + /** + * @deprecated + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): NonSharedBuffer; + /** + * @deprecated + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): NonSharedBuffer; + /** + * @deprecated + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + } + namespace constants { + // https://nodejs.org/dist/latest-v22.x/docs/api/crypto.html#crypto-constants + const OPENSSL_VERSION_NUMBER: number; + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode for TLS v1.3 */ + const SSL_OP_ALLOW_NO_DHE_KEX: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's version identifier of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + /** Instructs OpenSSL to disable encrypt-then-MAC. */ + const SSL_OP_NO_ENCRYPT_THEN_MAC: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to disable renegotiation. */ + const SSL_OP_NO_RENEGOTIATION: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + /** Instructs OpenSSL to turn off SSL v2 */ + const SSL_OP_NO_SSLv2: number; + /** Instructs OpenSSL to turn off SSL v3 */ + const SSL_OP_NO_SSLv3: number; + /** Instructs OpenSSL to disable use of RFC4507bis tickets. */ + const SSL_OP_NO_TICKET: number; + /** Instructs OpenSSL to turn off TLS v1 */ + const SSL_OP_NO_TLSv1: number; + /** Instructs OpenSSL to turn off TLS v1.1 */ + const SSL_OP_NO_TLSv1_1: number; + /** Instructs OpenSSL to turn off TLS v1.2 */ + const SSL_OP_NO_TLSv1_2: number; + /** Instructs OpenSSL to turn off TLS v1.3 */ + const SSL_OP_NO_TLSv1_3: number; + /** Instructs OpenSSL server to prioritize ChaCha20-Poly1305 when the client does. This option has no effect if `SSL_OP_CIPHER_SERVER_PREFERENCE` is not enabled. */ + const SSL_OP_PRIORITIZE_CHACHA: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + interface HashOptions extends stream.TransformOptions { + /** + * For XOF hash functions such as `shake256`, the + * outputLength option can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + /** @deprecated since v10.0.0 */ + const fips: boolean; + /** + * Creates and returns a `Hash` object that can be used to generate hash digests + * using the given `algorithm`. Optional `options` argument controls stream + * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option + * can be used to specify the desired output length in bytes. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * Example: generating the sha256 sum of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHash, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hash = createHash('sha256'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hash.update(data); + * else { + * console.log(`${hash.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.92 + * @param options `stream.transform` options + */ + function createHash(algorithm: string, options?: HashOptions): Hash; + /** + * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. + * Optional `options` argument controls stream behavior. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is + * a `KeyObject`, its type must be `secret`. If it is a string, please consider `caveats when using strings as inputs to cryptographic APIs`. If it was + * obtained from a cryptographically secure source of entropy, such as {@link randomBytes} or {@link generateKey}, its length should not + * exceed the block size of `algorithm` (e.g., 512 bits for SHA-256). + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hmac.update(data); + * else { + * console.log(`${hmac.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; + // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings + type BinaryToTextEncoding = "base64" | "base64url" | "hex" | "binary"; + type CharacterEncoding = "utf8" | "utf-8" | "utf16le" | "utf-16le" | "latin1"; + type LegacyCharacterEncoding = "ascii" | "binary" | "ucs2" | "ucs-2"; + type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + /** + * The `Hash` class is a utility for creating hash digests of data. It can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed hash digest on the readable side, or + * * Using the `hash.update()` and `hash.digest()` methods to produce the + * computed hash. + * + * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hash` objects as streams: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hash.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * } + * }); + * + * hash.write('some data to hash'); + * hash.end(); + * ``` + * + * Example: Using `Hash` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { createHash } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * const input = createReadStream('test.js'); + * input.pipe(hash).setEncoding('hex').pipe(stdout); + * ``` + * + * Example: Using the `hash.update()` and `hash.digest()` methods: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('some data to hash'); + * console.log(hash.digest('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * ``` + * @since v0.1.92 + */ + class Hash extends stream.Transform { + private constructor(); + /** + * Creates a new `Hash` object that contains a deep copy of the internal state + * of the current `Hash` object. + * + * The optional `options` argument controls stream behavior. For XOF hash + * functions such as `'shake256'`, the `outputLength` option can be used to + * specify the desired output length in bytes. + * + * An error is thrown when an attempt is made to copy the `Hash` object after + * its `hash.digest()` method has been called. + * + * ```js + * // Calculate a rolling hash. + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('one'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('two'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('three'); + * console.log(hash.copy().digest('hex')); + * + * // Etc. + * ``` + * @since v13.1.0 + * @param options `stream.transform` options + */ + copy(options?: HashOptions): Hash; + /** + * Updates the hash content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hash; + update(data: string, inputEncoding: Encoding): Hash; + /** + * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method). + * If `encoding` is provided a string will be returned; otherwise + * a `Buffer` is returned. + * + * The `Hash` object can not be used again after `hash.digest()` method has been + * called. Multiple calls will cause an error to be thrown. + * @since v0.1.92 + * @param encoding The `encoding` of the return value. + */ + digest(): NonSharedBuffer; + digest(encoding: BinaryToTextEncoding): string; + } + /** + * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can + * be used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed HMAC digest on the readable side, or + * * Using the `hmac.update()` and `hmac.digest()` methods to produce the + * computed HMAC digest. + * + * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hmac` objects as streams: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hmac.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * } + * }); + * + * hmac.write('some data to hash'); + * hmac.end(); + * ``` + * + * Example: Using `Hmac` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream('test.js'); + * input.pipe(hmac).pipe(stdout); + * ``` + * + * Example: Using the `hmac.update()` and `hmac.digest()` methods: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + * @deprecated Since v20.13.0 Calling `Hmac` class directly with `Hmac()` or `new Hmac()` is deprecated due to being internals, not intended for public use. Please use the {@link createHmac} method to create Hmac instances. + */ + class Hmac extends stream.Transform { + private constructor(); + /** + * Updates the `Hmac` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hmac; + update(data: string, inputEncoding: Encoding): Hmac; + /** + * Calculates the HMAC digest of all of the data passed using `hmac.update()`. + * If `encoding` is + * provided a string is returned; otherwise a `Buffer` is returned; + * + * The `Hmac` object can not be used again after `hmac.digest()` has been + * called. Multiple calls to `hmac.digest()` will result in an error being thrown. + * @since v0.1.94 + * @param encoding The `encoding` of the return value. + */ + digest(): NonSharedBuffer; + digest(encoding: BinaryToTextEncoding): string; + } + type KeyObjectType = "secret" | "public" | "private"; + interface KeyExportOptions { + type: "pkcs1" | "spki" | "pkcs8" | "sec1"; + format: T; + cipher?: string | undefined; + passphrase?: string | Buffer | undefined; + } + interface JwkKeyExportOptions { + format: "jwk"; + } + interface JsonWebKey { + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + k?: string; + kty?: string; + n?: string; + p?: string; + q?: string; + qi?: string; + x?: string; + y?: string; + [key: string]: unknown; + } + interface AsymmetricKeyDetails { + /** + * Key size in bits (RSA, DSA). + */ + modulusLength?: number; + /** + * Public exponent (RSA). + */ + publicExponent?: bigint; + /** + * Name of the message digest (RSA-PSS). + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 (RSA-PSS). + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes (RSA-PSS). + */ + saltLength?: number; + /** + * Size of q in bits (DSA). + */ + divisorLength?: number; + /** + * Name of the curve (EC). + */ + namedCurve?: string; + } + /** + * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, + * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject` + * objects are not to be created directly using the `new`keyword. + * + * Most applications should consider using the new `KeyObject` API instead of + * passing keys as strings or `Buffer`s due to improved security features. + * + * `KeyObject` instances can be passed to other threads via `postMessage()`. + * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to + * be listed in the `transferList` argument. + * @since v11.6.0 + */ + class KeyObject { + private constructor(); + /** + * Example: Converting a `CryptoKey` instance to a `KeyObject`: + * + * ```js + * const { KeyObject } = await import('node:crypto'); + * const { subtle } = globalThis.crypto; + * + * const key = await subtle.generateKey({ + * name: 'HMAC', + * hash: 'SHA-256', + * length: 256, + * }, true, ['sign', 'verify']); + * + * const keyObject = KeyObject.from(key); + * console.log(keyObject.symmetricKeySize); + * // Prints: 32 (symmetric key size in bytes) + * ``` + * @since v15.0.0 + */ + static from(key: webcrypto.CryptoKey): KeyObject; + /** + * For asymmetric keys, this property represents the type of the key. Supported key + * types are: + * + * * `'rsa'` (OID 1.2.840.113549.1.1.1) + * * `'rsa-pss'` (OID 1.2.840.113549.1.1.10) + * * `'dsa'` (OID 1.2.840.10040.4.1) + * * `'ec'` (OID 1.2.840.10045.2.1) + * * `'x25519'` (OID 1.3.101.110) + * * `'x448'` (OID 1.3.101.111) + * * `'ed25519'` (OID 1.3.101.112) + * * `'ed448'` (OID 1.3.101.113) + * * `'dh'` (OID 1.2.840.113549.1.3.1) + * + * This property is `undefined` for unrecognized `KeyObject` types and symmetric + * keys. + * @since v11.6.0 + */ + asymmetricKeyType?: KeyType; + /** + * This property exists only on asymmetric keys. Depending on the type of the key, + * this object contains information about the key. None of the information obtained + * through this property can be used to uniquely identify a key or to compromise + * the security of the key. + * + * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence, + * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be + * set. + * + * Other key details might be exposed via this API using additional attributes. + * @since v15.7.0 + */ + asymmetricKeyDetails?: AsymmetricKeyDetails; + /** + * For symmetric keys, the following encoding options can be used: + * + * For public keys, the following encoding options can be used: + * + * For private keys, the following encoding options can be used: + * + * The result type depends on the selected encoding format, when PEM the + * result is a string, when DER it will be a buffer containing the data + * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. + * + * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are + * ignored. + * + * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of + * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be + * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for + * encrypted private keys. Since PKCS#8 defines its own + * encryption mechanism, PEM-level encryption is not supported when encrypting + * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for + * PKCS#1 and SEC1 encryption. + * @since v11.6.0 + */ + export(options: KeyExportOptions<"pem">): string | NonSharedBuffer; + export(options?: KeyExportOptions<"der">): NonSharedBuffer; + export(options?: JwkKeyExportOptions): JsonWebKey; + /** + * Returns `true` or `false` depending on whether the keys have exactly the same + * type, value, and parameters. This method is not [constant time](https://en.wikipedia.org/wiki/Timing_attack). + * @since v17.7.0, v16.15.0 + * @param otherKeyObject A `KeyObject` with which to compare `keyObject`. + */ + equals(otherKeyObject: KeyObject): boolean; + /** + * For secret keys, this property represents the size of the key in bytes. This + * property is `undefined` for asymmetric keys. + * @since v11.6.0 + */ + symmetricKeySize?: number; + /** + * Converts a `KeyObject` instance to a `CryptoKey`. + * @since 22.10.0 + */ + toCryptoKey( + algorithm: + | webcrypto.AlgorithmIdentifier + | webcrypto.RsaHashedImportParams + | webcrypto.EcKeyImportParams + | webcrypto.HmacImportParams, + extractable: boolean, + keyUsages: readonly webcrypto.KeyUsage[], + ): webcrypto.CryptoKey; + /** + * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys + * or `'private'` for private (asymmetric) keys. + * @since v11.6.0 + */ + type: KeyObjectType; + } + type CipherCCMTypes = "aes-128-ccm" | "aes-192-ccm" | "aes-256-ccm"; + type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"; + type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb"; + type CipherChaCha20Poly1305Types = "chacha20-poly1305"; + type BinaryLike = string | NodeJS.ArrayBufferView; + type CipherKey = BinaryLike | KeyObject; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number | undefined; + } + interface CipherOCBOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherChaCha20Poly1305Options extends stream.TransformOptions { + /** @default 16 */ + authTagLength?: number | undefined; + } + /** + * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and + * initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a + * given IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createCipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): CipherCCM; + function createCipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): CipherOCB; + function createCipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): CipherGCM; + function createCipheriv( + algorithm: CipherChaCha20Poly1305Types, + key: CipherKey, + iv: BinaryLike, + options?: CipherChaCha20Poly1305Options, + ): CipherChaCha20Poly1305; + function createCipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Cipher; + /** + * Instances of the `Cipher` class are used to encrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain unencrypted + * data is written to produce encrypted data on the readable side, or + * * Using the `cipher.update()` and `cipher.final()` methods to produce + * the encrypted data. + * + * The {@link createCipheriv} method is + * used to create `Cipher` instances. `Cipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipher` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * // Once we have the key and iv, we can create and use the cipher... + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = ''; + * cipher.setEncoding('hex'); + * + * cipher.on('data', (chunk) => encrypted += chunk); + * cipher.on('end', () => console.log(encrypted)); + * + * cipher.write('some clear text data'); + * cipher.end(); + * }); + * }); + * ``` + * + * Example: Using `Cipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * + * import { + * pipeline, + * } from 'node:stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.js'); + * const output = createWriteStream('test.enc'); + * + * pipeline(input, cipher, output, (err) => { + * if (err) throw err; + * }); + * }); + * }); + * ``` + * + * Example: Using the `cipher.update()` and `cipher.final()` methods: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); + * encrypted += cipher.final('hex'); + * console.log(encrypted); + * }); + * }); + * ``` + * @since v0.1.94 + */ + class Cipher extends stream.Transform { + private constructor(); + /** + * Updates the cipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or `DataView`. If `data` is a `Buffer`, + * `TypedArray`, or `DataView`, then `inputEncoding` is ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being + * thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the data. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: BinaryLike): NonSharedBuffer; + update(data: string, inputEncoding: Encoding): NonSharedBuffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `cipher.final()` method has been called, the `Cipher` object can no + * longer be used to encrypt data. Attempts to call `cipher.final()` more than + * once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): NonSharedBuffer; + final(outputEncoding: BufferEncoding): string; + /** + * When using block encryption algorithms, the `Cipher` class will automatically + * add padding to the input data to the appropriate block size. To disable the + * default padding call `cipher.setAutoPadding(false)`. + * + * When `autoPadding` is `false`, the length of the entire input data must be a + * multiple of the cipher's block size or `cipher.final()` will throw an error. + * Disabling automatic padding is useful for non-standard padding, for instance + * using `0x0` instead of PKCS padding. + * + * The `cipher.setAutoPadding()` method must be called before `cipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(autoPadding?: boolean): this; + } + interface CipherCCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): NonSharedBuffer; + } + interface CipherGCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): NonSharedBuffer; + } + interface CipherOCB extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): NonSharedBuffer; + } + interface CipherChaCha20Poly1305 extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): NonSharedBuffer; + } + /** + * Creates and returns a `Decipher` object that uses the given `algorithm`, `key` and initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the `authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength` option is not required but can be used to restrict accepted authentication tags + * to those with the specified length. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a given + * IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createDecipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): DecipherCCM; + function createDecipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): DecipherOCB; + function createDecipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): DecipherGCM; + function createDecipheriv( + algorithm: CipherChaCha20Poly1305Types, + key: CipherKey, + iv: BinaryLike, + options?: CipherChaCha20Poly1305Options, + ): DecipherChaCha20Poly1305; + function createDecipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Decipher; + /** + * Instances of the `Decipher` class are used to decrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain encrypted + * data is written to produce unencrypted data on the readable side, or + * * Using the `decipher.update()` and `decipher.final()` methods to + * produce the unencrypted data. + * + * The {@link createDecipheriv} method is + * used to create `Decipher` instances. `Decipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipher` objects as streams: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Key length is dependent on the algorithm. In this case for aes192, it is + * // 24 bytes (192 bits). + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * let decrypted = ''; + * decipher.on('readable', () => { + * let chunk; + * while (null !== (chunk = decipher.read())) { + * decrypted += chunk.toString('utf8'); + * } + * }); + * decipher.on('end', () => { + * console.log(decrypted); + * // Prints: some clear text data + * }); + * + * // Encrypted with same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * decipher.write(encrypted, 'hex'); + * decipher.end(); + * ``` + * + * Example: Using `Decipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.enc'); + * const output = createWriteStream('test.js'); + * + * input.pipe(decipher).pipe(output); + * ``` + * + * Example: Using the `decipher.update()` and `decipher.final()` methods: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * // Encrypted using same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * let decrypted = decipher.update(encrypted, 'hex', 'utf8'); + * decrypted += decipher.final('utf8'); + * console.log(decrypted); + * // Prints: some clear text data + * ``` + * @since v0.1.94 + */ + class Decipher extends stream.Transform { + private constructor(); + /** + * Updates the decipher with `data`. If the `inputEncoding` argument is given, + * the `data` argument is a string using the specified encoding. If the `inputEncoding` argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is + * ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding` is specified, a string using the specified encoding is returned. If no `outputEncoding` is provided, a `Buffer` is returned. + * + * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error + * being thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: NodeJS.ArrayBufferView): NonSharedBuffer; + update(data: string, inputEncoding: Encoding): NonSharedBuffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `decipher.final()` method has been called, the `Decipher` object can + * no longer be used to decrypt data. Attempts to call `decipher.final()` more + * than once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): NonSharedBuffer; + final(outputEncoding: BufferEncoding): string; + /** + * When data has been encrypted without standard block padding, calling `decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and + * removing padding. + * + * Turning auto padding off will only work if the input data's length is a + * multiple of the ciphers block size. + * + * The `decipher.setAutoPadding()` method must be called before `decipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(auto_padding?: boolean): this; + } + interface DecipherCCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface DecipherGCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherOCB extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherChaCha20Poly1305 extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "pkcs8" | "sec1" | undefined; + passphrase?: string | Buffer | undefined; + encoding?: string | undefined; + } + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "spki" | undefined; + encoding?: string | undefined; + } + /** + * Asynchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKey, + * } = await import('node:crypto'); + * + * generateKey('hmac', { length: 512 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKey( + type: "hmac" | "aes", + options: { + length: number; + }, + callback: (err: Error | null, key: KeyObject) => void, + ): void; + /** + * Synchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKeySync, + * } = await import('node:crypto'); + * + * const key = generateKeySync('hmac', { length: 512 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKeySync( + type: "hmac" | "aes", + options: { + length: number; + }, + ): KeyObject; + interface JsonWebKeyInput { + key: JsonWebKey; + format: "jwk"; + } + /** + * Creates and returns a new key object containing a private key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key` must be an object with the properties described above. + * + * If the private key is encrypted, a `passphrase` must be specified. The length + * of the passphrase is limited to 1024 bytes. + * @since v11.6.0 + */ + function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a public key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject` with type `'private'`, the public key is derived from the given private key; + * otherwise, `key` must be an object with the properties described above. + * + * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. + * + * Because public keys can be derived from private keys, a private key may be + * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the + * returned `KeyObject` will be `'public'` and that the private key cannot be + * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type `'private'` is given, a new `KeyObject` with type `'public'` will be returned + * and it will be impossible to extract the private key from the returned object. + * @since v11.6.0 + */ + function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a secret key for symmetric + * encryption or `Hmac`. + * @since v11.6.0 + * @param encoding The string encoding when `key` is a string. + */ + function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; + function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; + /** + * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms. + * Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Sign` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createSign(algorithm: string, options?: stream.WritableOptions): Sign; + type DSAEncoding = "der" | "ieee-p1363"; + interface SigningOptions { + /** + * @see crypto.constants.RSA_PKCS1_PADDING + */ + padding?: number | undefined; + saltLength?: number | undefined; + dsaEncoding?: DSAEncoding | undefined; + } + interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} + interface SignKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface SignJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} + interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} + interface VerifyKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} + type KeyLike = string | Buffer | KeyObject; + /** + * The `Sign` class is a utility for generating signatures. It can be used in one + * of two ways: + * + * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or + * * Using the `sign.update()` and `sign.sign()` methods to produce the + * signature. + * + * The {@link createSign} method is used to create `Sign` instances. The + * argument is the string name of the hash function to use. `Sign` objects are not + * to be created directly using the `new` keyword. + * + * Example: Using `Sign` and `Verify` objects as streams: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('ec', { + * namedCurve: 'sect239k1', + * }); + * + * const sign = createSign('SHA256'); + * sign.write('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey, 'hex'); + * + * const verify = createVerify('SHA256'); + * verify.write('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature, 'hex')); + * // Prints: true + * ``` + * + * Example: Using the `sign.update()` and `verify.update()` methods: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('rsa', { + * modulusLength: 2048, + * }); + * + * const sign = createSign('SHA256'); + * sign.update('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey); + * + * const verify = createVerify('SHA256'); + * verify.update('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature)); + * // Prints: true + * ``` + * @since v0.1.92 + */ + class Sign extends stream.Writable { + private constructor(); + /** + * Updates the `Sign` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): this; + update(data: string, inputEncoding: Encoding): this; + /** + * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the following additional properties can be passed: + * + * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * The `Sign` object can not be again used after `sign.sign()` method has been + * called. Multiple calls to `sign.sign()` will result in an error being thrown. + * @since v0.1.92 + */ + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput): NonSharedBuffer; + sign( + privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + outputFormat: BinaryToTextEncoding, + ): string; + } + /** + * Creates and returns a `Verify` object that uses the given algorithm. + * Use {@link getHashes} to obtain an array of names of the available + * signing algorithms. Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Verify` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; + /** + * The `Verify` class is a utility for verifying signatures. It can be used in one + * of two ways: + * + * * As a writable `stream` where written data is used to validate against the + * supplied signature, or + * * Using the `verify.update()` and `verify.verify()` methods to verify + * the signature. + * + * The {@link createVerify} method is used to create `Verify` instances. `Verify` objects are not to be created directly using the `new` keyword. + * + * See `Sign` for examples. + * @since v0.1.92 + */ + class Verify extends stream.Writable { + private constructor(); + /** + * Updates the `Verify` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `inputEncoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or `DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Verify; + update(data: string, inputEncoding: Encoding): Verify; + /** + * Verifies the provided data using the given `object` and `signature`. + * + * If `object` is not a `KeyObject`, this function behaves as if `object` had been passed to {@link createPublicKey}. If it is an + * object, the following additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the data, in + * the `signatureEncoding`. + * If a `signatureEncoding` is specified, the `signature` is expected to be a + * string; otherwise `signature` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * The `verify` object can not be used again after `verify.verify()` has been + * called. Multiple calls to `verify.verify()` will result in an error being + * thrown. + * + * Because public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.1.92 + */ + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: string, + signature_format?: BinaryToTextEncoding, + ): boolean; + } + /** + * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an + * optional specific `generator`. + * + * The `generator` argument can be a number, string, or `Buffer`. If `generator` is not specified, the value `2` is used. + * + * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise + * a `Buffer`, `TypedArray`, or `DataView` is expected. + * + * If `generatorEncoding` is specified, `generator` is expected to be a string; + * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected. + * @since v0.11.12 + * @param primeEncoding The `encoding` of the `prime` string. + * @param [generator=2] + * @param generatorEncoding The `encoding` of the `generator` string. + */ + function createDiffieHellman(primeLength: number, generator?: number): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + /** + * The `DiffieHellman` class is a utility for creating Diffie-Hellman key + * exchanges. + * + * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createDiffieHellman, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createDiffieHellman(2048); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * // OK + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * ``` + * @since v0.5.0 + */ + class DiffieHellman { + private constructor(); + /** + * Generates private and public Diffie-Hellman key values unless they have been + * generated or computed already, and returns + * the public key in the specified `encoding`. This key should be + * transferred to the other party. + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * This function is a thin wrapper around [`DH_generate_key()`](https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html). In particular, + * once a private key has been generated or set, calling this function only updates + * the public key but does not generate a new private key. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + generateKeys(): NonSharedBuffer; + generateKeys(encoding: BinaryToTextEncoding): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using the specified `inputEncoding`, and secret is + * encoded using specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. + * @since v0.5.0 + * @param inputEncoding The `encoding` of an `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret( + otherPublicKey: NodeJS.ArrayBufferView, + inputEncoding?: null, + outputEncoding?: null, + ): NonSharedBuffer; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding?: null, + ): NonSharedBuffer; + computeSecret( + otherPublicKey: NodeJS.ArrayBufferView, + inputEncoding: null, + outputEncoding: BinaryToTextEncoding, + ): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * Returns the Diffie-Hellman prime in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrime(): NonSharedBuffer; + getPrime(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman generator in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getGenerator(): NonSharedBuffer; + getGenerator(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman public key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPublicKey(): NonSharedBuffer; + getPublicKey(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman private key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrivateKey(): NonSharedBuffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * Sets the Diffie-Hellman public key. If the `encoding` argument is provided, `publicKey` is expected + * to be a string. If no `encoding` is provided, `publicKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `publicKey` string. + */ + setPublicKey(publicKey: NodeJS.ArrayBufferView): void; + setPublicKey(publicKey: string, encoding: BufferEncoding): void; + /** + * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected + * to be a string. If no `encoding` is provided, `privateKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * + * This function does not automatically compute the associated public key. Either `diffieHellman.setPublicKey()` or `diffieHellman.generateKeys()` can be + * used to manually provide the public key or to automatically derive it. + * @since v0.5.0 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BufferEncoding): void; + /** + * A bit field containing any warnings and/or errors resulting from a check + * performed during initialization of the `DiffieHellman` object. + * + * The following values are valid for this property (as defined in `node:constants` module): + * + * * `DH_CHECK_P_NOT_SAFE_PRIME` + * * `DH_CHECK_P_NOT_PRIME` + * * `DH_UNABLE_TO_CHECK_GENERATOR` + * * `DH_NOT_SUITABLE_GENERATOR` + * @since v0.11.12 + */ + verifyError: number; + } + /** + * The `DiffieHellmanGroup` class takes a well-known modp group as its argument. + * It works the same as `DiffieHellman`, except that it does not allow changing its keys after creation. + * In other words, it does not implement `setPublicKey()` or `setPrivateKey()` methods. + * + * ```js + * const { createDiffieHellmanGroup } = await import('node:crypto'); + * const dh = createDiffieHellmanGroup('modp1'); + * ``` + * The name (e.g. `'modp1'`) is taken from [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt) (modp1 and 2) and [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt): + * ```bash + * $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h + * modp1 # 768 bits + * modp2 # 1024 bits + * modp5 # 1536 bits + * modp14 # 2048 bits + * modp15 # etc. + * modp16 + * modp17 + * modp18 + * ``` + * @since v0.7.5 + */ + const DiffieHellmanGroup: DiffieHellmanGroupConstructor; + interface DiffieHellmanGroupConstructor { + new(name: string): DiffieHellmanGroup; + (name: string): DiffieHellmanGroup; + readonly prototype: DiffieHellmanGroup; + } + type DiffieHellmanGroup = Omit; + /** + * Creates a predefined `DiffieHellmanGroup` key exchange object. The + * supported groups are listed in the documentation for `DiffieHellmanGroup`. + * + * The returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * the keys (with `diffieHellman.setPublicKey()`, for example). The + * advantage of using this method is that the parties do not have to + * generate nor exchange a group modulus beforehand, saving both processor + * and communication time. + * + * Example (obtaining a shared secret): + * + * ```js + * const { + * getDiffieHellman, + * } = await import('node:crypto'); + * const alice = getDiffieHellman('modp14'); + * const bob = getDiffieHellman('modp14'); + * + * alice.generateKeys(); + * bob.generateKeys(); + * + * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); + * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); + * + * // aliceSecret and bobSecret should be the same + * console.log(aliceSecret === bobSecret); + * ``` + * @since v0.7.5 + */ + function getDiffieHellman(groupName: string): DiffieHellmanGroup; + /** + * An alias for {@link getDiffieHellman} + * @since v0.9.3 + */ + function createDiffieHellmanGroup(name: string): DiffieHellmanGroup; + /** + * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. + * + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated `derivedKey` will be passed to the callback as a `Buffer`. An error will be + * thrown if any of the input arguments specify invalid values or types. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2, + * } = await import('node:crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * @since v0.5.5 + */ + function pbkdf2( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + callback: (err: Error | null, derivedKey: NonSharedBuffer) => void, + ): void; + /** + * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. + * + * If an error occurs an `Error` will be thrown, otherwise the derived key will be + * returned as a `Buffer`. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2Sync, + * } = await import('node:crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * @since v0.9.3 + */ + function pbkdf2Sync( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + ): NonSharedBuffer; + /** + * Generates cryptographically strong pseudorandom data. The `size` argument + * is a number indicating the number of bytes to generate. + * + * If a `callback` function is provided, the bytes are generated asynchronously + * and the `callback` function is invoked with two arguments: `err` and `buf`. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The `buf` argument is a `Buffer` containing the generated bytes. + * + * ```js + * // Asynchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * randomBytes(256, (err, buf) => { + * if (err) throw err; + * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); + * }); + * ``` + * + * If the `callback` function is not provided, the random bytes are generated + * synchronously and returned as a `Buffer`. An error will be thrown if + * there is a problem generating the bytes. + * + * ```js + * // Synchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * const buf = randomBytes(256); + * console.log( + * `${buf.length} bytes of random data: ${buf.toString('hex')}`); + * ``` + * + * The `crypto.randomBytes()` method will not complete until there is + * sufficient entropy available. + * This should normally never take longer than a few milliseconds. The only time + * when generating the random bytes may conceivably block for a longer period of + * time is right after boot, when the whole system is still low on entropy. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomBytes()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomBytes` requests when doing so as part of fulfilling a client + * request. + * @since v0.5.8 + * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. + * @return if the `callback` function is not provided. + */ + function randomBytes(size: number): NonSharedBuffer; + function randomBytes(size: number, callback: (err: Error | null, buf: NonSharedBuffer) => void): void; + function pseudoRandomBytes(size: number): NonSharedBuffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: NonSharedBuffer) => void): void; + /** + * Return a random integer `n` such that `min <= n < max`. This + * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). + * + * The range (`max - min`) must be less than 2**48. `min` and `max` must + * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + * + * If the `callback` function is not provided, the random integer is + * generated synchronously. + * + * ```js + * // Asynchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * randomInt(3, (err, n) => { + * if (err) throw err; + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * }); + * ``` + * + * ```js + * // Synchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(1, 7); + * console.log(`The dice rolled: ${n}`); + * ``` + * @since v14.10.0, v12.19.0 + * @param [min=0] Start of random range (inclusive). + * @param max End of random range (exclusive). + * @param callback `function(err, n) {}`. + */ + function randomInt(max: number): number; + function randomInt(min: number, max: number): number; + function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; + function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; + /** + * Synchronous version of {@link randomFill}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * console.log(randomFillSync(buf).toString('hex')); + * + * randomFillSync(buf, 5); + * console.log(buf.toString('hex')); + * + * // The above is equivalent to the following: + * randomFillSync(buf, 5, 5); + * console.log(buf.toString('hex')); + * ``` + * + * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * console.log(Buffer.from(randomFillSync(a).buffer, + * a.byteOffset, a.byteLength).toString('hex')); + * + * const b = new DataView(new ArrayBuffer(10)); + * console.log(Buffer.from(randomFillSync(b).buffer, + * b.byteOffset, b.byteLength).toString('hex')); + * + * const c = new ArrayBuffer(10); + * console.log(Buffer.from(randomFillSync(c)).toString('hex')); + * ``` + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @return The object passed as `buffer` argument. + */ + function randomFillSync(buffer: T, offset?: number, size?: number): T; + /** + * This function is similar to {@link randomBytes} but requires the first + * argument to be a `Buffer` that will be filled. It also + * requires that a callback is passed in. + * + * If the `callback` function is not provided, an error will be thrown. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * randomFill(buf, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * randomFill(buf, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * // The above is equivalent to the following: + * randomFill(buf, 5, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * ``` + * + * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as `buffer`. + * + * While this includes instances of `Float32Array` and `Float64Array`, this + * function should not be used to generate random floating-point numbers. The + * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array + * contains finite numbers only, they are not drawn from a uniform random + * distribution and have no meaningful lower or upper bounds. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * randomFill(a, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const b = new DataView(new ArrayBuffer(10)); + * randomFill(b, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const c = new ArrayBuffer(10); + * randomFill(c, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf).toString('hex')); + * }); + * ``` + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomFill()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomFill` requests when doing so as part of fulfilling a client + * request. + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @param callback `function(err, buf) {}`. + */ + function randomFill( + buffer: T, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + size: number, + callback: (err: Error | null, buf: T) => void, + ): void; + interface ScryptOptions { + cost?: number | undefined; + blockSize?: number | undefined; + parallelization?: number | undefined; + N?: number | undefined; + r?: number | undefined; + p?: number | undefined; + maxmem?: number | undefined; + } + /** + * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * The `callback` function is called with two arguments: `err` and `derivedKey`. `err` is an exception object when key derivation fails, otherwise `err` is `null`. `derivedKey` is passed to the + * callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scrypt, + * } = await import('node:crypto'); + * + * // Using the factory defaults. + * scrypt('password', 'salt', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * // Using a custom N parameter. Must be a power of two. + * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' + * }); + * ``` + * @since v10.5.0 + */ + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: NonSharedBuffer) => void, + ): void; + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options: ScryptOptions, + callback: (err: Error | null, derivedKey: NonSharedBuffer) => void, + ): void; + /** + * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scryptSync, + * } = await import('node:crypto'); + * // Using the factory defaults. + * + * const key1 = scryptSync('password', 'salt', 64); + * console.log(key1.toString('hex')); // '3745e48...08d59ae' + * // Using a custom N parameter. Must be a power of two. + * const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); + * console.log(key2.toString('hex')); // '3745e48...aa39b34' + * ``` + * @since v10.5.0 + */ + function scryptSync( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options?: ScryptOptions, + ): NonSharedBuffer; + interface RsaPublicKey { + key: KeyLike; + padding?: number | undefined; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string | undefined; + /** + * @default 'sha1' + */ + oaepHash?: string | undefined; + oaepLabel?: NodeJS.TypedArray | undefined; + padding?: number | undefined; + } + /** + * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using + * the corresponding private key, for example using {@link privateDecrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.11.14 + */ + function publicEncrypt( + key: RsaPublicKey | RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): NonSharedBuffer; + /** + * Decrypts `buffer` with `key`.`buffer` was previously encrypted using + * the corresponding private key, for example using {@link privateEncrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v1.1.0 + */ + function publicDecrypt( + key: RsaPublicKey | RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): NonSharedBuffer; + /** + * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using + * the corresponding public key, for example using {@link publicEncrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. + * @since v0.11.14 + */ + function privateDecrypt( + privateKey: RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): NonSharedBuffer; + /** + * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using + * the corresponding public key, for example using {@link publicDecrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. + * @since v1.1.0 + */ + function privateEncrypt( + privateKey: RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): NonSharedBuffer; + /** + * ```js + * const { + * getCiphers, + * } = await import('node:crypto'); + * + * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] + * ``` + * @since v0.9.3 + * @return An array with the names of the supported cipher algorithms. + */ + function getCiphers(): string[]; + /** + * ```js + * const { + * getCurves, + * } = await import('node:crypto'); + * + * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] + * ``` + * @since v2.3.0 + * @return An array with the names of the supported elliptic curves. + */ + function getCurves(): string[]; + /** + * @since v10.0.0 + * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}. + */ + function getFips(): 1 | 0; + /** + * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. + * Throws an error if FIPS mode is not available. + * @since v10.0.0 + * @param bool `true` to enable FIPS mode. + */ + function setFips(bool: boolean): void; + /** + * ```js + * const { + * getHashes, + * } = await import('node:crypto'); + * + * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] + * ``` + * @since v0.9.3 + * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. + */ + function getHashes(): string[]; + /** + * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) + * key exchanges. + * + * Instances of the `ECDH` class can be created using the {@link createECDH} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createECDH, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createECDH('secp521r1'); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createECDH('secp521r1'); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * // OK + * ``` + * @since v0.11.14 + */ + class ECDH { + private constructor(); + /** + * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the + * format specified by `format`. The `format` argument specifies point encoding + * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is + * interpreted using the specified `inputEncoding`, and the returned key is encoded + * using the specified `outputEncoding`. + * + * Use {@link getCurves} to obtain a list of available curve names. + * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display + * the name and description of each available elliptic curve. + * + * If `format` is not specified the point will be returned in `'uncompressed'` format. + * + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * Example (uncompressing a key): + * + * ```js + * const { + * createECDH, + * ECDH, + * } = await import('node:crypto'); + * + * const ecdh = createECDH('secp256k1'); + * ecdh.generateKeys(); + * + * const compressedKey = ecdh.getPublicKey('hex', 'compressed'); + * + * const uncompressedKey = ECDH.convertKey(compressedKey, + * 'secp256k1', + * 'hex', + * 'hex', + * 'uncompressed'); + * + * // The converted key and the uncompressed public key should be the same + * console.log(uncompressedKey === ecdh.getPublicKey('hex')); + * ``` + * @since v10.0.0 + * @param inputEncoding The `encoding` of the `key` string. + * @param outputEncoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: BinaryToTextEncoding, + outputEncoding?: "latin1" | "hex" | "base64" | "base64url", + format?: "uncompressed" | "compressed" | "hybrid", + ): NonSharedBuffer | string; + /** + * Generates private and public EC Diffie-Hellman key values, and returns + * the public key in the specified `format` and `encoding`. This key should be + * transferred to the other party. + * + * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. + * + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + generateKeys(): NonSharedBuffer; + generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using specified `inputEncoding`, and the returned secret + * is encoded using the specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. + * + * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey` lies outside of the elliptic curve. Since `otherPublicKey` is + * usually supplied from a remote user over an insecure network, + * be sure to handle this exception accordingly. + * @since v0.11.14 + * @param inputEncoding The `encoding` of the `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): NonSharedBuffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): NonSharedBuffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @return The EC Diffie-Hellman in the specified `encoding`. + */ + getPrivateKey(): NonSharedBuffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. + * + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. + */ + getPublicKey(encoding?: null, format?: ECDHKeyFormat): NonSharedBuffer; + getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Sets the EC Diffie-Hellman private key. + * If `encoding` is provided, `privateKey` is expected + * to be a string; otherwise `privateKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `privateKey` is not valid for the curve specified when the `ECDH` object was + * created, an error is thrown. Upon setting the private key, the associated + * public point (key) is also generated and set in the `ECDH` object. + * @since v0.11.14 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; + } + /** + * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a + * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent + * OpenSSL releases, `openssl ecparam -list_curves` will also display the name + * and description of each available elliptic curve. + * @since v0.11.14 + */ + function createECDH(curveName: string): ECDH; + /** + * This function compares the underlying bytes that represent the given `ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time + * algorithm. + * + * This function does not leak timing information that + * would allow an attacker to guess one of the values. This is suitable for + * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/). + * + * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they + * must have the same byte length. An error is thrown if `a` and `b` have + * different byte lengths. + * + * If at least one of `a` and `b` is a `TypedArray` with more than one byte per + * entry, such as `Uint16Array`, the result will be computed using the platform + * byte order. + * + * **When both of the inputs are `Float32Array`s or `Float64Array`s, this function might return unexpected results due to IEEE 754** + * **encoding of floating-point numbers. In particular, neither `x === y` nor `Object.is(x, y)` implies that the byte representations of two floating-point** + * **numbers `x` and `y` are equal.** + * + * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code + * is timing-safe. Care should be taken to ensure that the surrounding code does + * not introduce timing vulnerabilities. + * @since v6.6.0 + */ + function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; + type KeyType = "rsa" | "rsa-pss" | "dsa" | "ec" | "ed25519" | "ed448" | "x25519" | "x448"; + type KeyFormat = "pem" | "der" | "jwk"; + interface BasePrivateKeyEncodingOptions { + format: T; + cipher?: string | undefined; + passphrase?: string | undefined; + } + interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + interface ED25519KeyPairKeyObjectOptions {} + interface ED448KeyPairKeyObjectOptions {} + interface X25519KeyPairKeyObjectOptions {} + interface X448KeyPairKeyObjectOptions {} + interface ECKeyPairKeyObjectOptions { + /** + * Name of the curve to use + */ + namedCurve: string; + /** + * Must be `'named'` or `'explicit'`. Default: `'named'`. + */ + paramEncoding?: "explicit" | "named" | undefined; + } + interface RSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + } + interface RSAPSSKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes + */ + saltLength?: string | undefined; + } + interface DSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + } + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs1" | "pkcs8"; + }; + } + interface RSAPSSKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes + */ + saltLength?: string | undefined; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface ECKeyPairOptions extends ECKeyPairKeyObjectOptions { + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "sec1" | "pkcs8"; + }; + } + interface ED25519KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface ED448KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface X25519KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface X448KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * When encoding public keys, it is recommended to use `'spki'`. When encoding + * private keys, it is recommended to use `'pkcs8'` with a strong passphrase, + * and to keep the passphrase confidential. + * + * ```js + * const { + * generateKeyPairSync, + * } = await import('node:crypto'); + * + * const { + * publicKey, + * privateKey, + * } = generateKeyPairSync('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }); + * ``` + * + * The return value `{ publicKey, privateKey }` represents the generated key pair. + * When PEM encoding was selected, the respective key will be a string, otherwise + * it will be a buffer containing the data encoded as DER. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "rsa", options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "rsa-pss", options: RSAPSSKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "dsa", options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ec", options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ed25519", options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ed448", options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "x25519", options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "x448", options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * It is recommended to encode public keys as `'spki'` and private keys as `'pkcs8'` with encryption for long-term storage: + * + * ```js + * const { + * generateKeyPair, + * } = await import('node:crypto'); + * + * generateKeyPair('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }, (err, publicKey, privateKey) => { + * // Handle errors and use the generated key pair. + * }); + * ``` + * + * On completion, `callback` will be called with `err` set to `undefined` and `publicKey` / `privateKey` representing the generated key pair. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + namespace generateKeyPair { + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "ed25519", + options?: ED25519KeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__(type: "ed448", options?: ED448KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "x25519", + options?: X25519KeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__(type: "x448", options?: X448KeyPairKeyObjectOptions): Promise; + } + /** + * Calculates and returns the signature for `data` using the given private key and + * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is + * dependent upon the key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPrivateKey}. If it is an object, the following + * additional properties can be passed: + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + ): NonSharedBuffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + callback: (error: Error | null, data: NonSharedBuffer) => void, + ): void; + /** + * Verifies the given signature for `data` using the given key and algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPublicKey}. If it is an object, the following + * additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the `data`. + * + * Because public keys can be derived from private keys, a private key or a public + * key may be passed for `key`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + callback: (error: Error | null, result: boolean) => void, + ): void; + /** + * Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. + * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'` (for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). + * @since v13.9.0, v12.17.0 + */ + function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): NonSharedBuffer; + /** + * A utility for creating one-shot hash digests of data. It can be faster than the object-based `crypto.createHash()` when hashing a smaller amount of data + * (<= 5MB) that's readily available. If the data can be big or if it is streamed, it's still recommended to use `crypto.createHash()` instead. The `algorithm` + * is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. On recent releases + * of OpenSSL, `openssl list -digest-algorithms` will display the available digest algorithms. + * + * Example: + * + * ```js + * import crypto from 'node:crypto'; + * import { Buffer } from 'node:buffer'; + * + * // Hashing a string and return the result as a hex-encoded string. + * const string = 'Node.js'; + * // 10b3493287f831e81a438811a1ffba01f8cec4b7 + * console.log(crypto.hash('sha1', string)); + * + * // Encode a base64-encoded string into a Buffer, hash it and return + * // the result as a buffer. + * const base64 = 'Tm9kZS5qcw=='; + * // + * console.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer')); + * ``` + * @since v21.7.0, v20.12.0 + * @param data When `data` is a string, it will be encoded as UTF-8 before being hashed. If a different input encoding is desired for a string input, user + * could encode the string into a `TypedArray` using either `TextEncoder` or `Buffer.from()` and passing the encoded `TypedArray` into this API instead. + * @param [outputEncoding='hex'] [Encoding](https://nodejs.org/docs/latest-v22.x/api/buffer.html#buffers-and-character-encodings) used to encode the returned digest. + */ + function hash(algorithm: string, data: BinaryLike, outputEncoding?: BinaryToTextEncoding): string; + function hash(algorithm: string, data: BinaryLike, outputEncoding: "buffer"): NonSharedBuffer; + function hash( + algorithm: string, + data: BinaryLike, + outputEncoding?: BinaryToTextEncoding | "buffer", + ): string | NonSharedBuffer; + type CipherMode = "cbc" | "ccm" | "cfb" | "ctr" | "ecb" | "gcm" | "ocb" | "ofb" | "stream" | "wrap" | "xts"; + interface CipherInfoOptions { + /** + * A test key length. + */ + keyLength?: number | undefined; + /** + * A test IV length. + */ + ivLength?: number | undefined; + } + interface CipherInfo { + /** + * The name of the cipher. + */ + name: string; + /** + * The nid of the cipher. + */ + nid: number; + /** + * The block size of the cipher in bytes. + * This property is omitted when mode is 'stream'. + */ + blockSize?: number | undefined; + /** + * The expected or default initialization vector length in bytes. + * This property is omitted if the cipher does not use an initialization vector. + */ + ivLength?: number | undefined; + /** + * The expected or default key length in bytes. + */ + keyLength: number; + /** + * The cipher mode. + */ + mode: CipherMode; + } + /** + * Returns information about a given cipher. + * + * Some ciphers accept variable length keys and initialization vectors. By default, + * the `crypto.getCipherInfo()` method will return the default values for these + * ciphers. To test if a given key length or iv length is acceptable for given + * cipher, use the `keyLength` and `ivLength` options. If the given values are + * unacceptable, `undefined` will be returned. + * @since v15.0.0 + * @param nameOrNid The name or nid of the cipher to query. + */ + function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; + /** + * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an errors occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. The successfully generated `derivedKey` will + * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any + * of the input arguments specify invalid values or types. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdf, + * } = await import('node:crypto'); + * + * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * }); + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdf( + digest: string, + irm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: ArrayBuffer) => void, + ): void; + /** + * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The + * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + * + * An error will be thrown if any of the input arguments specify invalid values or + * types, or if the derived key cannot be generated. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdfSync, + * } = await import('node:crypto'); + * + * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdfSync( + digest: string, + ikm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + ): ArrayBuffer; + interface SecureHeapUsage { + /** + * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. + */ + total: number; + /** + * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. + */ + min: number; + /** + * The total number of bytes currently allocated from the secure heap. + */ + used: number; + /** + * The calculated ratio of `used` to `total` allocated bytes. + */ + utilization: number; + } + /** + * @since v15.6.0 + */ + function secureHeapUsed(): SecureHeapUsage; + interface RandomUUIDOptions { + /** + * By default, to improve performance, + * Node.js will pre-emptively generate and persistently cache enough + * random data to generate up to 128 random UUIDs. To generate a UUID + * without using the cache, set `disableEntropyCache` to `true`. + * + * @default `false` + */ + disableEntropyCache?: boolean | undefined; + } + type UUID = `${string}-${string}-${string}-${string}-${string}`; + /** + * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a + * cryptographic pseudorandom number generator. + * @since v15.6.0, v14.17.0 + */ + function randomUUID(options?: RandomUUIDOptions): UUID; + interface X509CheckOptions { + /** + * @default 'always' + */ + subject?: "always" | "default" | "never" | undefined; + /** + * @default true + */ + wildcards?: boolean | undefined; + /** + * @default true + */ + partialWildcards?: boolean | undefined; + /** + * @default false + */ + multiLabelWildcards?: boolean | undefined; + /** + * @default false + */ + singleLabelSubdomains?: boolean | undefined; + } + /** + * Encapsulates an X509 certificate and provides read-only access to + * its information. + * + * ```js + * const { X509Certificate } = await import('node:crypto'); + * + * const x509 = new X509Certificate('{... pem encoded cert ...}'); + * + * console.log(x509.subject); + * ``` + * @since v15.6.0 + */ + class X509Certificate { + /** + * Will be \`true\` if this is a Certificate Authority (CA) certificate. + * @since v15.6.0 + */ + readonly ca: boolean; + /** + * The SHA-1 fingerprint of this certificate. + * + * Because SHA-1 is cryptographically broken and because the security of SHA-1 is + * significantly worse than that of algorithms that are commonly used to sign + * certificates, consider using `x509.fingerprint256` instead. + * @since v15.6.0 + */ + readonly fingerprint: string; + /** + * The SHA-256 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint256: string; + /** + * The SHA-512 fingerprint of this certificate. + * + * Because computing the SHA-256 fingerprint is usually faster and because it is + * only half the size of the SHA-512 fingerprint, `x509.fingerprint256` may be + * a better choice. While SHA-512 presumably provides a higher level of security in + * general, the security of SHA-256 matches that of most algorithms that are + * commonly used to sign certificates. + * @since v17.2.0, v16.14.0 + */ + readonly fingerprint512: string; + /** + * The complete subject of this certificate. + * @since v15.6.0 + */ + readonly subject: string; + /** + * The subject alternative name specified for this certificate. + * + * This is a comma-separated list of subject alternative names. Each entry begins + * with a string identifying the kind of the subject alternative name followed by + * a colon and the value associated with the entry. + * + * Earlier versions of Node.js incorrectly assumed that it is safe to split this + * property at the two-character sequence `', '` (see [CVE-2021-44532](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44532)). However, + * both malicious and legitimate certificates can contain subject alternative names + * that include this sequence when represented as a string. + * + * After the prefix denoting the type of the entry, the remainder of each entry + * might be enclosed in quotes to indicate that the value is a JSON string literal. + * For backward compatibility, Node.js only uses JSON string literals within this + * property when necessary to avoid ambiguity. Third-party code should be prepared + * to handle both possible entry formats. + * @since v15.6.0 + */ + readonly subjectAltName: string | undefined; + /** + * A textual representation of the certificate's authority information access + * extension. + * + * This is a line feed separated list of access descriptions. Each line begins with + * the access method and the kind of the access location, followed by a colon and + * the value associated with the access location. + * + * After the prefix denoting the access method and the kind of the access location, + * the remainder of each line might be enclosed in quotes to indicate that the + * value is a JSON string literal. For backward compatibility, Node.js only uses + * JSON string literals within this property when necessary to avoid ambiguity. + * Third-party code should be prepared to handle both possible entry formats. + * @since v15.6.0 + */ + readonly infoAccess: string | undefined; + /** + * An array detailing the key usages for this certificate. + * @since v15.6.0 + */ + readonly keyUsage: string[]; + /** + * The issuer identification included in this certificate. + * @since v15.6.0 + */ + readonly issuer: string; + /** + * The issuer certificate or `undefined` if the issuer certificate is not + * available. + * @since v15.9.0 + */ + readonly issuerCertificate: X509Certificate | undefined; + /** + * The public key `KeyObject` for this certificate. + * @since v15.6.0 + */ + readonly publicKey: KeyObject; + /** + * A `Buffer` containing the DER encoding of this certificate. + * @since v15.6.0 + */ + readonly raw: NonSharedBuffer; + /** + * The serial number of this certificate. + * + * Serial numbers are assigned by certificate authorities and do not uniquely + * identify certificates. Consider using `x509.fingerprint256` as a unique + * identifier instead. + * @since v15.6.0 + */ + readonly serialNumber: string; + /** + * The date/time from which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validFrom: string; + /** + * The date/time from which this certificate is valid, encapsulated in a `Date` object. + * @since v22.10.0 + */ + readonly validFromDate: Date; + /** + * The date/time until which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validTo: string; + /** + * The date/time until which this certificate is valid, encapsulated in a `Date` object. + * @since v22.10.0 + */ + readonly validToDate: Date; + constructor(buffer: BinaryLike); + /** + * Checks whether the certificate matches the given email address. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any email addresses. + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching email + * address, the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns `email` if the certificate matches, `undefined` if it does not. + */ + checkEmail(email: string, options?: Pick): string | undefined; + /** + * Checks whether the certificate matches the given host name. + * + * If the certificate matches the given host name, the matching subject name is + * returned. The returned name might be an exact match (e.g., `foo.example.com`) + * or it might contain wildcards (e.g., `*.example.com`). Because host name + * comparisons are case-insensitive, the returned subject name might also differ + * from the given `name` in capitalization. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any DNS names. This behavior is consistent with [RFC 2818](https://www.rfc-editor.org/rfc/rfc2818.txt) ("HTTP Over TLS"). + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching DNS name, + * the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns a subject name that matches `name`, or `undefined` if no subject name matches `name`. + */ + checkHost(name: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given IP address (IPv4 or IPv6). + * + * Only [RFC 5280](https://www.rfc-editor.org/rfc/rfc5280.txt) `iPAddress` subject alternative names are considered, and they + * must match the given `ip` address exactly. Other subject alternative names as + * well as the subject field of the certificate are ignored. + * @since v15.6.0 + * @return Returns `ip` if the certificate matches, `undefined` if it does not. + */ + checkIP(ip: string): string | undefined; + /** + * Checks whether this certificate was potentially issued by the given `otherCert` + * by comparing the certificate metadata. + * + * This is useful for pruning a list of possible issuer certificates which have been + * selected using a more rudimentary filtering routine, i.e. just based on subject + * and issuer names. + * + * Finally, to verify that this certificate's signature was produced by a private key + * corresponding to `otherCert`'s public key use `x509.verify(publicKey)` + * with `otherCert`'s public key represented as a `KeyObject` + * like so + * + * ```js + * if (!x509.verify(otherCert.publicKey)) { + * throw new Error('otherCert did not issue x509'); + * } + * ``` + * @since v15.6.0 + */ + checkIssued(otherCert: X509Certificate): boolean; + /** + * Checks whether the public key for this certificate is consistent with + * the given private key. + * @since v15.6.0 + * @param privateKey A private key. + */ + checkPrivateKey(privateKey: KeyObject): boolean; + /** + * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded + * certificate. + * @since v15.6.0 + */ + toJSON(): string; + /** + * Returns information about this certificate using the legacy `certificate object` encoding. + * @since v15.6.0 + */ + toLegacyObject(): PeerCertificate; + /** + * Returns the PEM-encoded certificate. + * @since v15.6.0 + */ + toString(): string; + /** + * Verifies that this certificate was signed by the given public key. + * Does not perform any other validation checks on the certificate. + * @since v15.6.0 + * @param publicKey A public key. + */ + verify(publicKey: KeyObject): boolean; + } + type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; + interface GeneratePrimeOptions { + add?: LargeNumberLike | undefined; + rem?: LargeNumberLike | undefined; + /** + * @default false + */ + safe?: boolean | undefined; + bigint?: boolean | undefined; + } + interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false | undefined; + } + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsBigInt, + callback: (err: Error | null, prime: bigint) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsArrayBuffer, + callback: (err: Error | null, prime: ArrayBuffer) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptions, + callback: (err: Error | null, prime: ArrayBuffer | bigint) => void, + ): void; + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrimeSync(size: number): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint; + interface CheckPrimeOptions { + /** + * The number of Miller-Rabin probabilistic primality iterations to perform. + * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most `2**-64` for random input. + * Care must be used when selecting a number of checks. + * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. + * + * @default 0 + */ + checks?: number | undefined; + } + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + */ + function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void; + function checkPrime( + value: LargeNumberLike, + options: CheckPrimeOptions, + callback: (err: Error | null, result: boolean) => void, + ): void; + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`. + */ + function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean; + /** + * Load and set the `engine` for some or all OpenSSL functions (selected by flags). + * + * `engine` could be either an id or a path to the engine's shared library. + * + * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags` is a bit field taking one of or a mix of the following flags (defined in `crypto.constants`): + * + * * `crypto.constants.ENGINE_METHOD_RSA` + * * `crypto.constants.ENGINE_METHOD_DSA` + * * `crypto.constants.ENGINE_METHOD_DH` + * * `crypto.constants.ENGINE_METHOD_RAND` + * * `crypto.constants.ENGINE_METHOD_EC` + * * `crypto.constants.ENGINE_METHOD_CIPHERS` + * * `crypto.constants.ENGINE_METHOD_DIGESTS` + * * `crypto.constants.ENGINE_METHOD_PKEY_METHS` + * * `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` + * * `crypto.constants.ENGINE_METHOD_ALL` + * * `crypto.constants.ENGINE_METHOD_NONE` + * @since v0.11.11 + * @param flags + */ + function setEngine(engine: string, flags?: number): void; + /** + * A convenient alias for {@link webcrypto.getRandomValues}. This + * implementation is not compliant with the Web Crypto spec, to write + * web-compatible code use {@link webcrypto.getRandomValues} instead. + * @since v17.4.0 + * @return Returns `typedArray`. + */ + function getRandomValues(typedArray: T): T; + /** + * A convenient alias for `crypto.webcrypto.subtle`. + * @since v17.4.0 + */ + const subtle: webcrypto.SubtleCrypto; + /** + * An implementation of the Web Crypto API standard. + * + * See the {@link https://nodejs.org/docs/latest/api/webcrypto.html Web Crypto API documentation} for details. + * @since v15.0.0 + */ + const webcrypto: webcrypto.Crypto; + namespace webcrypto { + type BufferSource = ArrayBufferView | ArrayBuffer; + type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki"; + type KeyType = "private" | "public" | "secret"; + type KeyUsage = + | "decrypt" + | "deriveBits" + | "deriveKey" + | "encrypt" + | "sign" + | "unwrapKey" + | "verify" + | "wrapKey"; + type AlgorithmIdentifier = Algorithm | string; + type HashAlgorithmIdentifier = AlgorithmIdentifier; + type NamedCurve = string; + type BigInteger = Uint8Array; + interface AesCbcParams extends Algorithm { + iv: BufferSource; + } + interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; + } + interface AesDerivedKeyParams extends Algorithm { + length: number; + } + interface AesGcmParams extends Algorithm { + additionalData?: BufferSource; + iv: BufferSource; + tagLength?: number; + } + interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; + } + interface AesKeyGenParams extends Algorithm { + length: number; + } + interface Algorithm { + name: string; + } + interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: NamedCurve; + } + interface EcKeyGenParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcKeyImportParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; + } + interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface Ed448Params extends Algorithm { + context?: BufferSource; + } + interface HkdfParams extends Algorithm { + hash: HashAlgorithmIdentifier; + info: BufferSource; + salt: BufferSource; + } + interface HmacImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; + } + interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; + } + interface KeyAlgorithm { + name: string; + } + interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: BufferSource; + } + interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; + } + interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: HashAlgorithmIdentifier; + } + interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaOaepParams extends Algorithm { + label?: BufferSource; + } + interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; + } + interface RsaPssParams extends Algorithm { + saltLength: number; + } + /** + * Importing the `webcrypto` object (`import { webcrypto } from 'node:crypto'`) gives an instance of the `Crypto` class. + * `Crypto` is a singleton that provides access to the remainder of the crypto API. + * @since v15.0.0 + */ + interface Crypto { + /** + * Provides access to the `SubtleCrypto` API. + * @since v15.0.0 + */ + readonly subtle: SubtleCrypto; + /** + * Generates cryptographically strong random values. + * The given `typedArray` is filled with random values, and a reference to `typedArray` is returned. + * + * The given `typedArray` must be an integer-based instance of {@link NodeJS.TypedArray}, i.e. `Float32Array` and `Float64Array` are not accepted. + * + * An error will be thrown if the given `typedArray` is larger than 65,536 bytes. + * @since v15.0.0 + */ + getRandomValues>(typedArray: T): T; + /** + * Generates a random {@link https://www.rfc-editor.org/rfc/rfc4122.txt RFC 4122} version 4 UUID. + * The UUID is generated using a cryptographic pseudorandom number generator. + * @since v16.7.0 + */ + randomUUID(): UUID; + CryptoKey: CryptoKeyConstructor; + } + // This constructor throws ILLEGAL_CONSTRUCTOR so it should not be newable. + interface CryptoKeyConstructor { + /** Illegal constructor */ + (_: { readonly _: unique symbol }): never; // Allows instanceof to work but not be callable by the user. + readonly length: 0; + readonly name: "CryptoKey"; + readonly prototype: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface CryptoKey { + /** + * An object detailing the algorithm for which the key can be used along with additional algorithm-specific parameters. + * @since v15.0.0 + */ + readonly algorithm: KeyAlgorithm; + /** + * When `true`, the {@link CryptoKey} can be extracted using either `subtleCrypto.exportKey()` or `subtleCrypto.wrapKey()`. + * @since v15.0.0 + */ + readonly extractable: boolean; + /** + * A string identifying whether the key is a symmetric (`'secret'`) or asymmetric (`'private'` or `'public'`) key. + * @since v15.0.0 + */ + readonly type: KeyType; + /** + * An array of strings identifying the operations for which the key may be used. + * + * The possible usages are: + * - `'encrypt'` - The key may be used to encrypt data. + * - `'decrypt'` - The key may be used to decrypt data. + * - `'sign'` - The key may be used to generate digital signatures. + * - `'verify'` - The key may be used to verify digital signatures. + * - `'deriveKey'` - The key may be used to derive a new key. + * - `'deriveBits'` - The key may be used to derive bits. + * - `'wrapKey'` - The key may be used to wrap another key. + * - `'unwrapKey'` - The key may be used to unwrap another key. + * + * Valid key usages depend on the key algorithm (identified by `cryptokey.algorithm.name`). + * @since v15.0.0 + */ + readonly usages: KeyUsage[]; + } + /** + * The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair. + * @since v15.0.0 + */ + interface CryptoKeyPair { + /** + * A {@link CryptoKey} whose type will be `'private'`. + * @since v15.0.0 + */ + privateKey: CryptoKey; + /** + * A {@link CryptoKey} whose type will be `'public'`. + * @since v15.0.0 + */ + publicKey: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface SubtleCrypto { + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `key`, + * `subtle.decrypt()` attempts to decipher the provided `data`. If successful, + * the returned promise will be resolved with an `` containing the plaintext result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + decrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `baseKey`, + * `subtle.deriveBits()` attempts to generate `length` bits. + * The Node.js implementation requires that when `length` is a number it must be multiple of `8`. + * When `length` is `null` the maximum number of bits for a given algorithm is generated. This is allowed + * for the `'ECDH'`, `'X25519'`, and `'X448'` algorithms. + * If successful, the returned promise will be resolved with an `` containing the generated data. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @since v15.0.0 + */ + deriveBits( + algorithm: EcdhKeyDeriveParams, + baseKey: CryptoKey, + length?: number | null, + ): Promise; + deriveBits( + algorithm: EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + length: number, + ): Promise; + /** + * Using the method and parameters specified in `algorithm`, and the keying material provided by `baseKey`, + * `subtle.deriveKey()` attempts to generate a new ` based on the method and parameters in `derivedKeyAlgorithm`. + * + * Calling `subtle.deriveKey()` is equivalent to calling `subtle.deriveBits()` to generate raw keying material, + * then passing the result into the `subtle.importKey()` method using the `deriveKeyAlgorithm`, `extractable`, and `keyUsages` parameters as input. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + deriveKey( + algorithm: EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + derivedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | AesDerivedKeyParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + /** + * Using the method identified by `algorithm`, `subtle.digest()` attempts to generate a digest of `data`. + * If successful, the returned promise is resolved with an `` containing the computed digest. + * + * If `algorithm` is provided as a ``, it must be one of: + * + * - `'SHA-1'` + * - `'SHA-256'` + * - `'SHA-384'` + * - `'SHA-512'` + * + * If `algorithm` is provided as an ``, it must have a `name` property whose value is one of the above. + * @since v15.0.0 + */ + digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise; + /** + * Using the method and parameters specified by `algorithm` and the keying material provided by `key`, + * `subtle.encrypt()` attempts to encipher `data`. If successful, + * the returned promise is resolved with an `` containing the encrypted result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + encrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * Exports the given key into the specified format, if supported. + * + * If the `` is not extractable, the returned promise will reject. + * + * When `format` is either `'pkcs8'` or `'spki'` and the export is successful, + * the returned promise will be resolved with an `` containing the exported key data. + * + * When `format` is `'jwk'` and the export is successful, the returned promise will be resolved with a + * JavaScript object conforming to the {@link https://tools.ietf.org/html/rfc7517 JSON Web Key} specification. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @returns `` containing ``. + * @since v15.0.0 + */ + exportKey(format: "jwk", key: CryptoKey): Promise; + exportKey(format: Exclude, key: CryptoKey): Promise; + /** + * Using the method and parameters provided in `algorithm`, + * `subtle.generateKey()` attempts to generate new keying material. + * Depending the method used, the method may generate either a single `` or a ``. + * + * The `` (public and private key) generating algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * The `` (secret key) generating algorithms supported include: + * + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + generateKey( + algorithm: RsaHashedKeyGenParams | EcKeyGenParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AlgorithmIdentifier, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * The `subtle.importKey()` method attempts to interpret the provided `keyData` as the given `format` + * to create a `` instance using the provided `algorithm`, `extractable`, and `keyUsages` arguments. + * If the import is successful, the returned promise will be resolved with the created ``. + * + * If importing a `'PBKDF2'` key, `extractable` must be `false`. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + importKey( + format: "jwk", + keyData: JsonWebKey, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + importKey( + format: Exclude, + keyData: BufferSource, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters given by `algorithm` and the keying material provided by `key`, + * `subtle.sign()` attempts to generate a cryptographic signature of `data`. If successful, + * the returned promise is resolved with an `` containing the generated signature. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + sign( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.unwrapKey()` method attempts to decrypt a wrapped key and create a `` instance. + * It is equivalent to calling `subtle.decrypt()` first on the encrypted key data (using the `wrappedKey`, `unwrapAlgo`, and `unwrappingKey` arguments as input) + * then passing the results in to the `subtle.importKey()` method using the `unwrappedKeyAlgo`, `extractable`, and `keyUsages` arguments as inputs. + * If successful, the returned promise is resolved with a `` object. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * + * The unwrapped key algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + unwrapKey( + format: KeyFormat, + wrappedKey: BufferSource, + unwrappingKey: CryptoKey, + unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + unwrappedKeyAlgorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters given in `algorithm` and the keying material provided by `key`, + * `subtle.verify()` attempts to verify that `signature` is a valid cryptographic signature of `data`. + * The returned promise is resolved with either `true` or `false`. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + verify( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, + key: CryptoKey, + signature: BufferSource, + data: BufferSource, + ): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.wrapKey()` method exports the keying material into the format identified by `format`, + * then encrypts it using the method and parameters specified by `wrapAlgo` and the keying material provided by `wrappingKey`. + * It is the equivalent to calling `subtle.exportKey()` using `format` and `key` as the arguments, + * then passing the result to the `subtle.encrypt()` method using `wrappingKey` and `wrapAlgo` as inputs. + * If successful, the returned promise will be resolved with an `` containing the encrypted key data. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @since v15.0.0 + */ + wrapKey( + format: KeyFormat, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + ): Promise; + } + } + + global { + var crypto: typeof globalThis extends { + crypto: infer T; + onmessage: any; + } ? T + : webcrypto.Crypto; + } +} +declare module "node:crypto" { + export * from "crypto"; +} diff --git a/node_modules/@types/node/dgram.d.ts b/node_modules/@types/node/dgram.d.ts new file mode 100644 index 0000000..9776de0 --- /dev/null +++ b/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,600 @@ +/** + * The `node:dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/dgram.js) + */ +declare module "dgram" { + import { NonSharedBuffer } from "node:buffer"; + import { AddressInfo, BlockList } from "node:net"; + import * as dns from "node:dns"; + import { Abortable, EventEmitter } from "node:events"; + interface RemoteInfo { + address: string; + family: "IPv4" | "IPv6"; + port: number; + size: number; + } + interface BindOptions { + port?: number | undefined; + address?: string | undefined; + exclusive?: boolean | undefined; + fd?: number | undefined; + } + type SocketType = "udp4" | "udp6"; + interface SocketOptions extends Abortable { + type: SocketType; + reuseAddr?: boolean | undefined; + reusePort?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + recvBufferSize?: number | undefined; + sendBufferSize?: number | undefined; + lookup?: + | (( + hostname: string, + options: dns.LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ) => void) + | undefined; + receiveBlockList?: BlockList | undefined; + sendBlockList?: BlockList | undefined; + } + /** + * Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram + * messages. When `address` and `port` are not passed to `socket.bind()` the + * method will bind the socket to the "all interfaces" address on a random port + * (it does the right thing for both `udp4` and `udp6` sockets). The bound address + * and port can be retrieved using `socket.address().address` and `socket.address().port`. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.close()` on the socket: + * + * ```js + * const controller = new AbortController(); + * const { signal } = controller; + * const server = dgram.createSocket({ type: 'udp4', signal }); + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * // Later, when you want to close the server. + * controller.abort(); + * ``` + * @since v0.11.13 + * @param options Available options are: + * @param callback Attached as a listener for `'message'` events. Optional. + */ + function createSocket(type: SocketType, callback?: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): Socket; + /** + * Encapsulates the datagram functionality. + * + * New instances of `dgram.Socket` are created using {@link createSocket}. + * The `new` keyword is not to be used to create `dgram.Socket` instances. + * @since v0.1.99 + */ + class Socket extends EventEmitter { + /** + * Tells the kernel to join a multicast group at the given `multicastAddress` and `multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the `multicastInterface` argument is not + * specified, the operating system will choose + * one interface and will add membership to it. To add membership to every + * available interface, call `addMembership` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * + * When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur: + * + * ```js + * import cluster from 'node:cluster'; + * import dgram from 'node:dgram'; + * + * if (cluster.isPrimary) { + * cluster.fork(); // Works ok. + * cluster.fork(); // Fails with EADDRINUSE. + * } else { + * const s = dgram.createSocket('udp4'); + * s.bind(1234, () => { + * s.addMembership('224.0.0.114'); + * }); + * } + * ``` + * @since v0.6.9 + */ + addMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * Returns an object containing the address information for a socket. + * For UDP sockets, this object will contain `address`, `family`, and `port` properties. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.99 + */ + address(): AddressInfo; + /** + * For UDP sockets, causes the `dgram.Socket` to listen for datagram + * messages on a named `port` and optional `address`. If `port` is not + * specified or is `0`, the operating system will attempt to bind to a + * random port. If `address` is not specified, the operating system will + * attempt to listen on all addresses. Once binding is complete, a `'listening'` event is emitted and the optional `callback` function is + * called. + * + * Specifying both a `'listening'` event listener and passing a `callback` to the `socket.bind()` method is not harmful but not very + * useful. + * + * A bound datagram socket keeps the Node.js process running to receive + * datagram messages. + * + * If binding fails, an `'error'` event is generated. In rare case (e.g. + * attempting to bind with a closed socket), an `Error` may be thrown. + * + * Example of a UDP server listening on port 41234: + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @since v0.1.99 + * @param callback with no parameters. Called when binding is complete. + */ + bind(port?: number, address?: string, callback?: () => void): this; + bind(port?: number, callback?: () => void): this; + bind(callback?: () => void): this; + bind(options: BindOptions, callback?: () => void): this; + /** + * Close the underlying socket and stop listening for data on it. If a callback is + * provided, it is added as a listener for the `'close'` event. + * @since v0.1.99 + * @param callback Called when the socket has been closed. + */ + close(callback?: () => void): this; + /** + * Associates the `dgram.Socket` to a remote address and port. Every + * message sent by this handle is automatically sent to that destination. Also, + * the socket will only receive messages from that remote peer. + * Trying to call `connect()` on an already connected socket will result + * in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not + * provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) + * will be used by default. Once the connection is complete, a `'connect'` event + * is emitted and the optional `callback` function is called. In case of failure, + * the `callback` is called or, failing this, an `'error'` event is emitted. + * @since v12.0.0 + * @param callback Called when the connection is completed or on error. + */ + connect(port: number, address?: string, callback?: () => void): void; + connect(port: number, callback: () => void): void; + /** + * A synchronous function that disassociates a connected `dgram.Socket` from + * its remote address. Trying to call `disconnect()` on an unbound or already + * disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception. + * @since v12.0.0 + */ + disconnect(): void; + /** + * Instructs the kernel to leave a multicast group at `multicastAddress` using the `IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the + * kernel when the socket is closed or the process terminates, so most apps will + * never have reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v0.6.9 + */ + dropMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_RCVBUF` socket receive buffer size in bytes. + */ + getRecvBufferSize(): number; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_SNDBUF` socket send buffer size in bytes. + */ + getSendBufferSize(): number; + /** + * @since v18.8.0, v16.19.0 + * @return Number of bytes queued for sending. + */ + getSendQueueSize(): number; + /** + * @since v18.8.0, v16.19.0 + * @return Number of send requests currently in the queue awaiting to be processed. + */ + getSendQueueCount(): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active. The `socket.ref()` method adds the socket back to the reference + * counting and restores the default behavior. + * + * Calling `socket.ref()` multiples times will have no additional effect. + * + * The `socket.ref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + ref(): this; + /** + * Returns an object containing the `address`, `family`, and `port` of the remote + * endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception + * if the socket is not connected. + * @since v12.0.0 + */ + remoteAddress(): AddressInfo; + /** + * Broadcasts a datagram on the socket. + * For connectionless sockets, the destination `port` and `address` must be + * specified. Connected sockets, on the other hand, will use their associated + * remote endpoint, so the `port` and `address` arguments must not be set. + * + * The `msg` argument contains the message to be sent. + * Depending on its type, different behavior can apply. If `msg` is a `Buffer`, + * any `TypedArray` or a `DataView`, + * the `offset` and `length` specify the offset within the `Buffer` where the + * message begins and the number of bytes in the message, respectively. + * If `msg` is a `String`, then it is automatically converted to a `Buffer` with `'utf8'` encoding. With messages that + * contain multi-byte characters, `offset` and `length` will be calculated with + * respect to `byte length` and not the character position. + * If `msg` is an array, `offset` and `length` must not be specified. + * + * The `address` argument is a string. If the value of `address` is a host name, + * DNS will be used to resolve the address of the host. If `address` is not + * provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) will be used by default. + * + * If the socket has not been previously bound with a call to `bind`, the socket + * is assigned a random port number and is bound to the "all interfaces" address + * (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) + * + * An optional `callback` function may be specified to as a way of reporting + * DNS errors or for determining when it is safe to reuse the `buf` object. + * DNS lookups delay the time to send for at least one tick of the + * Node.js event loop. + * + * The only way to know for sure that the datagram has been sent is by using a `callback`. If an error occurs and a `callback` is given, the error will be + * passed as the first argument to the `callback`. If a `callback` is not given, + * the error is emitted as an `'error'` event on the `socket` object. + * + * Offset and length are optional but both _must_ be set if either are used. + * They are supported only when the first argument is a `Buffer`, a `TypedArray`, + * or a `DataView`. + * + * This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket. + * + * Example of sending a UDP packet to a port on `localhost`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.send(message, 41234, 'localhost', (err) => { + * client.close(); + * }); + * ``` + * + * Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('Some '); + * const buf2 = Buffer.from('bytes'); + * const client = dgram.createSocket('udp4'); + * client.send([buf1, buf2], 41234, (err) => { + * client.close(); + * }); + * ``` + * + * Sending multiple buffers might be faster or slower depending on the + * application and operating system. Run benchmarks to + * determine the optimal strategy on a case-by-case basis. Generally speaking, + * however, sending multiple buffers is faster. + * + * Example of sending a UDP packet using a socket connected to a port on `localhost`: + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.connect(41234, 'localhost', (err) => { + * client.send(message, (err) => { + * client.close(); + * }); + * }); + * ``` + * @since v0.1.99 + * @param msg Message to be sent. + * @param offset Offset in the buffer where the message starts. + * @param length Number of bytes in the message. + * @param port Destination port. + * @param address Destination host name or IP address. + * @param callback Called when the message has been sent. + */ + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + /** + * Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP + * packets may be sent to a local interface's broadcast address. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.6.9 + */ + setBroadcast(flag: boolean): void; + /** + * _All references to scope in this section are referring to [IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC + * 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_ + * _with a scope index is written as `'IP%scope'` where scope is an interface name_ + * _or interface number._ + * + * Sets the default outgoing multicast interface of the socket to a chosen + * interface or back to system interface selection. The `multicastInterface` must + * be a valid string representation of an IP from the socket's family. + * + * For IPv4 sockets, this should be the IP configured for the desired physical + * interface. All packets sent to multicast on the socket will be sent on the + * interface determined by the most recent successful use of this call. + * + * For IPv6 sockets, `multicastInterface` should include a scope to indicate the + * interface as in the examples that follow. In IPv6, individual `send` calls can + * also use explicit scope in addresses, so only packets sent to a multicast + * address without specifying an explicit scope are affected by the most recent + * successful use of this call. + * + * This method throws `EBADF` if called on an unbound socket. + * + * #### Example: IPv6 outgoing multicast interface + * + * On most systems, where scope format uses the interface name: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%eth1'); + * }); + * ``` + * + * On Windows, where scope format uses an interface number: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%2'); + * }); + * ``` + * + * #### Example: IPv4 outgoing multicast interface + * + * All systems use an IP of the host on the desired physical interface: + * + * ```js + * const socket = dgram.createSocket('udp4'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('10.0.0.2'); + * }); + * ``` + * @since v8.6.0 + */ + setMulticastInterface(multicastInterface: string): void; + /** + * Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`, + * multicast packets will also be received on the local interface. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastLoopback(flag: boolean): boolean; + /** + * Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for + * "Time to Live", in this context it specifies the number of IP hops that a + * packet is allowed to travel through, specifically for multicast traffic. Each + * router or gateway that forwards a packet decrements the TTL. If the TTL is + * decremented to 0 by a router, it will not be forwarded. + * + * The `ttl` argument may be between 0 and 255\. The default on most systems is `1`. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastTTL(ttl: number): number; + /** + * Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setRecvBufferSize(size: number): void; + /** + * Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setSendBufferSize(size: number): void; + /** + * Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live", + * in this context it specifies the number of IP hops that a packet is allowed to + * travel through. Each router or gateway that forwards a packet decrements the + * TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. + * Changing TTL values is typically done for network probes or when multicasting. + * + * The `ttl` argument may be between 1 and 255\. The default on most systems + * is 64. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.101 + */ + setTTL(ttl: number): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active, allowing the process to exit even if the socket is still + * listening. + * + * Calling `socket.unref()` multiple times will have no additional effect. + * + * The `socket.unref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + unref(): this; + /** + * Tells the kernel to join a source-specific multicast channel at the given `sourceAddress` and `groupAddress`, using the `multicastInterface` with the `IP_ADD_SOURCE_MEMBERSHIP` socket + * option. If the `multicastInterface` argument + * is not specified, the operating system will choose one interface and will add + * membership to it. To add membership to every available interface, call `socket.addSourceSpecificMembership()` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * @since v13.1.0, v12.16.0 + */ + addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * Instructs the kernel to leave a source-specific multicast channel at the given `sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP` socket option. This method is + * automatically called by the kernel when the + * socket is closed or the process terminates, so most apps will never have + * reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v13.1.0, v12.16.0 + */ + dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. error + * 4. listening + * 5. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: NonSharedBuffer, rinfo: RemoteInfo): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this; + /** + * Calls `socket.close()` and returns a promise that fulfills when the socket has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } +} +declare module "node:dgram" { + export * from "dgram"; +} diff --git a/node_modules/@types/node/diagnostics_channel.d.ts b/node_modules/@types/node/diagnostics_channel.d.ts new file mode 100644 index 0000000..f3bac52 --- /dev/null +++ b/node_modules/@types/node/diagnostics_channel.d.ts @@ -0,0 +1,578 @@ +/** + * The `node:diagnostics_channel` module provides an API to create named channels + * to report arbitrary message data for diagnostics purposes. + * + * It can be accessed using: + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * ``` + * + * It is intended that a module writer wanting to report diagnostics messages + * will create one or many top-level channels to report messages through. + * Channels may also be acquired at runtime but it is not encouraged + * due to the additional overhead of doing so. Channels may be exported for + * convenience, but as long as the name is known it can be acquired anywhere. + * + * If you intend for your module to produce diagnostics data for others to + * consume it is recommended that you include documentation of what named + * channels are used along with the shape of the message data. Channel names + * should generally include the module name to avoid collisions with data from + * other modules. + * @since v15.1.0, v14.17.0 + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/diagnostics_channel.js) + */ +declare module "diagnostics_channel" { + import { AsyncLocalStorage } from "node:async_hooks"; + /** + * Check if there are active subscribers to the named channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * if (diagnostics_channel.hasSubscribers('my-channel')) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return If there are active subscribers + */ + function hasSubscribers(name: string | symbol): boolean; + /** + * This is the primary entry-point for anyone wanting to publish to a named + * channel. It produces a channel object which is optimized to reduce overhead at + * publish time as much as possible. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return The named channel object + */ + function channel(name: string | symbol): Channel; + type ChannelListener = (message: unknown, name: string | symbol) => void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * diagnostics_channel.subscribe('my-channel', (message, name) => { + * // Received data + * }); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The handler to receive channel messages + */ + function subscribe(name: string | symbol, onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with {@link subscribe}. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * function onMessage(message, name) { + * // Received data + * } + * + * diagnostics_channel.subscribe('my-channel', onMessage); + * + * diagnostics_channel.unsubscribe('my-channel', onMessage); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean; + /** + * Creates a `TracingChannel` wrapper for the given `TracingChannel Channels`. If a name is given, the corresponding tracing + * channels will be created in the form of `tracing:${name}:${eventType}` where `eventType` corresponds to the types of `TracingChannel Channels`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channelsByName = diagnostics_channel.tracingChannel('my-channel'); + * + * // or... + * + * const channelsByCollection = diagnostics_channel.tracingChannel({ + * start: diagnostics_channel.channel('tracing:my-channel:start'), + * end: diagnostics_channel.channel('tracing:my-channel:end'), + * asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'), + * asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'), + * error: diagnostics_channel.channel('tracing:my-channel:error'), + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param nameOrChannels Channel name or object containing all the `TracingChannel Channels` + * @return Collection of channels to trace with + */ + function tracingChannel< + StoreType = unknown, + ContextType extends object = StoreType extends object ? StoreType : object, + >( + nameOrChannels: string | TracingChannelCollection, + ): TracingChannel; + /** + * The class `Channel` represents an individual named channel within the data + * pipeline. It is used to track subscribers and to publish messages when there + * are subscribers present. It exists as a separate object to avoid channel + * lookups at publish time, enabling very fast publish speeds and allowing + * for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly + * with `new Channel(name)` is not supported. + * @since v15.1.0, v14.17.0 + */ + class Channel { + readonly name: string | symbol; + /** + * Check if there are active subscribers to this channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * if (channel.hasSubscribers) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + */ + readonly hasSubscribers: boolean; + private constructor(name: string | symbol); + /** + * Publish a message to any subscribers to the channel. This will trigger + * message handlers synchronously so they will execute within the same context. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.publish({ + * some: 'message', + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param message The message to send to the channel subscribers + */ + publish(message: unknown): void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link subscribe(name, onMessage)} + * @param onMessage The handler to receive channel messages + */ + subscribe(onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * function onMessage(message, name) { + * // Received data + * } + * + * channel.subscribe(onMessage); + * + * channel.unsubscribe(onMessage); + * ``` + * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link unsubscribe(name, onMessage)} + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + unsubscribe(onMessage: ChannelListener): void; + /** + * When `channel.runStores(context, ...)` is called, the given context data + * will be applied to any store bound to the channel. If the store has already been + * bound the previous `transform` function will be replaced with the new one. + * The `transform` function may be omitted to set the given context data as the + * context directly. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store, (data) => { + * return { data }; + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param store The store to which to bind the context data + * @param transform Transform context data before setting the store context + */ + bindStore(store: AsyncLocalStorage, transform?: (context: ContextType) => StoreType): void; + /** + * Remove a message handler previously registered to this channel with `channel.bindStore(store)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store); + * channel.unbindStore(store); + * ``` + * @since v19.9.0 + * @experimental + * @param store The store to unbind from the channel. + * @return `true` if the store was found, `false` otherwise. + */ + unbindStore(store: AsyncLocalStorage): boolean; + /** + * Applies the given data to any AsyncLocalStorage instances bound to the channel + * for the duration of the given function, then publishes to the channel within + * the scope of that data is applied to the stores. + * + * If a transform function was given to `channel.bindStore(store)` it will be + * applied to transform the message data before it becomes the context value for + * the store. The prior storage context is accessible from within the transform + * function in cases where context linking is required. + * + * The context applied to the store should be accessible in any async code which + * continues from execution which began during the given function, however + * there are some situations in which `context loss` may occur. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store, (message) => { + * const parent = store.getStore(); + * return new Span(message, parent); + * }); + * channel.runStores({ some: 'message' }, () => { + * store.getStore(); // Span({ some: 'message' }) + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param context Message to send to subscribers and bind to stores + * @param fn Handler to run within the entered storage context + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runStores( + context: ContextType, + fn: (this: ThisArg, ...args: Args) => Result, + thisArg?: ThisArg, + ...args: Args + ): Result; + } + interface TracingChannelSubscribers { + start: (message: ContextType) => void; + end: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + asyncStart: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + asyncEnd: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + error: ( + message: ContextType & { + error: unknown; + }, + ) => void; + } + interface TracingChannelCollection { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + } + /** + * The class `TracingChannel` is a collection of `TracingChannel Channels` which + * together express a single traceable action. It is used to formalize and + * simplify the process of producing events for tracing application flow. {@link tracingChannel} is used to construct a `TracingChannel`. As with `Channel` it is recommended to create and reuse a + * single `TracingChannel` at the top-level of the file rather than creating them + * dynamically. + * @since v19.9.0 + * @experimental + */ + class TracingChannel implements TracingChannelCollection { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + /** + * Helper to subscribe a collection of functions to the corresponding channels. + * This is the same as calling `channel.subscribe(onMessage)` on each channel + * individually. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.subscribe({ + * start(message) { + * // Handle start message + * }, + * end(message) { + * // Handle end message + * }, + * asyncStart(message) { + * // Handle asyncStart message + * }, + * asyncEnd(message) { + * // Handle asyncEnd message + * }, + * error(message) { + * // Handle error message + * }, + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param subscribers Set of `TracingChannel Channels` subscribers + */ + subscribe(subscribers: TracingChannelSubscribers): void; + /** + * Helper to unsubscribe a collection of functions from the corresponding channels. + * This is the same as calling `channel.unsubscribe(onMessage)` on each channel + * individually. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.unsubscribe({ + * start(message) { + * // Handle start message + * }, + * end(message) { + * // Handle end message + * }, + * asyncStart(message) { + * // Handle asyncStart message + * }, + * asyncEnd(message) { + * // Handle asyncEnd message + * }, + * error(message) { + * // Handle error message + * }, + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param subscribers Set of `TracingChannel Channels` subscribers + * @return `true` if all handlers were successfully unsubscribed, and `false` otherwise. + */ + unsubscribe(subscribers: TracingChannelSubscribers): void; + /** + * Trace a synchronous function call. This will always produce a `start event` and `end event` around the execution and may produce an `error event` if the given function throws an error. + * This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceSync(() => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn Function to wrap a trace around + * @param context Shared object to correlate events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return The return value of the given function + */ + traceSync( + fn: (this: ThisArg, ...args: Args) => Result, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Result; + /** + * Trace a promise-returning function call. This will always produce a `start event` and `end event` around the synchronous portion of the + * function execution, and will produce an `asyncStart event` and `asyncEnd event` when a promise continuation is reached. It may also + * produce an `error event` if the given function throws an error or the + * returned promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.tracePromise(async () => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn Promise-returning function to wrap a trace around + * @param context Shared object to correlate trace events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return Chained from promise returned by the given function + */ + tracePromise( + fn: (this: ThisArg, ...args: Args) => Promise, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Promise; + /** + * Trace a callback-receiving function call. This will always produce a `start event` and `end event` around the synchronous portion of the + * function execution, and will produce a `asyncStart event` and `asyncEnd event` around the callback execution. It may also produce an `error event` if the given function throws an error or + * the returned + * promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * The `position` will be -1 by default to indicate the final argument should + * be used as the callback. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceCallback((arg1, callback) => { + * // Do something + * callback(null, 'result'); + * }, 1, { + * some: 'thing', + * }, thisArg, arg1, callback); + * ``` + * + * The callback will also be run with `channel.runStores(context, ...)` which + * enables context loss recovery in some cases. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * const myStore = new AsyncLocalStorage(); + * + * // The start channel sets the initial store data to something + * // and stores that store data value on the trace context object + * channels.start.bindStore(myStore, (data) => { + * const span = new Span(data); + * data.span = span; + * return span; + * }); + * + * // Then asyncStart can restore from that data it stored previously + * channels.asyncStart.bindStore(myStore, (data) => { + * return data.span; + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn callback using function to wrap a trace around + * @param position Zero-indexed argument position of expected callback + * @param context Shared object to correlate trace events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return The return value of the given function + */ + traceCallback( + fn: (this: ThisArg, ...args: Args) => Result, + position?: number, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Result; + /** + * `true` if any of the individual channels has a subscriber, `false` if not. + * + * This is a helper method available on a {@link TracingChannel} instance to check + * if any of the [TracingChannel Channels](https://nodejs.org/api/diagnostics_channel.html#tracingchannel-channels) have subscribers. + * A `true` is returned if any of them have at least one subscriber, a `false` is returned otherwise. + * + * ```js + * const diagnostics_channel = require('node:diagnostics_channel'); + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * if (channels.hasSubscribers) { + * // Do something + * } + * ``` + * @since v22.0.0, v20.13.0 + */ + readonly hasSubscribers: boolean; + } +} +declare module "node:diagnostics_channel" { + export * from "diagnostics_channel"; +} diff --git a/node_modules/@types/node/dns.d.ts b/node_modules/@types/node/dns.d.ts new file mode 100644 index 0000000..9cb2055 --- /dev/null +++ b/node_modules/@types/node/dns.d.ts @@ -0,0 +1,923 @@ +/** + * The `node:dns` module enables name resolution. For example, use it to look up IP + * addresses of host names. + * + * Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the + * DNS protocol for lookups. {@link lookup} uses the operating system + * facilities to perform name resolution. It may not need to perform any network + * communication. To perform name resolution the way other applications on the same + * system do, use {@link lookup}. + * + * ```js + * import dns from 'node:dns'; + * + * dns.lookup('example.org', (err, address, family) => { + * console.log('address: %j family: IPv%s', address, family); + * }); + * // address: "93.184.216.34" family: IPv4 + * ``` + * + * All other functions in the `node:dns` module connect to an actual DNS server to + * perform name resolution. They will always use the network to perform DNS + * queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform + * DNS queries, bypassing other name-resolution facilities. + * + * ```js + * import dns from 'node:dns'; + * + * dns.resolve4('archive.org', (err, addresses) => { + * if (err) throw err; + * + * console.log(`addresses: ${JSON.stringify(addresses)}`); + * + * addresses.forEach((a) => { + * dns.reverse(a, (err, hostnames) => { + * if (err) { + * throw err; + * } + * console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); + * }); + * }); + * }); + * ``` + * + * See the [Implementation considerations section](https://nodejs.org/docs/latest-v22.x/api/dns.html#implementation-considerations) for more information. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/dns.js) + */ +declare module "dns" { + import * as dnsPromises from "node:dns/promises"; + // Supported getaddrinfo flags. + /** + * Limits returned address types to the types of non-loopback addresses configured on the system. For example, IPv4 addresses are + * only returned if the current system has at least one IPv4 address configured. + */ + export const ADDRCONFIG: number; + /** + * If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses. It is not supported + * on some operating systems (e.g. FreeBSD 10.1). + */ + export const V4MAPPED: number; + /** + * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as + * well as IPv4 mapped IPv6 addresses. + */ + export const ALL: number; + export interface LookupOptions { + /** + * The record family. Must be `4`, `6`, or `0`. For backward compatibility reasons, `'IPv4'` and `'IPv6'` are interpreted + * as `4` and `6` respectively. The value 0 indicates that either an IPv4 or IPv6 address is returned. If the value `0` is used + * with `{ all: true } (see below)`, both IPv4 and IPv6 addresses are returned. + * @default 0 + */ + family?: number | "IPv4" | "IPv6" | undefined; + /** + * One or more [supported `getaddrinfo`](https://nodejs.org/docs/latest-v22.x/api/dns.html#supported-getaddrinfo-flags) flags. Multiple flags may be + * passed by bitwise `OR`ing their values. + */ + hints?: number | undefined; + /** + * When `true`, the callback returns all resolved addresses in an array. Otherwise, returns a single address. + * @default false + */ + all?: boolean | undefined; + /** + * When `verbatim`, the resolved addresses are return unsorted. When `ipv4first`, the resolved addresses are sorted + * by placing IPv4 addresses before IPv6 addresses. When `ipv6first`, the resolved addresses are sorted by placing IPv6 + * addresses before IPv4 addresses. Default value is configurable using + * {@link setDefaultResultOrder} or [`--dns-result-order`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--dns-result-orderorder). + * @default `verbatim` (addresses are not reordered) + * @since v22.1.0 + */ + order?: "ipv4first" | "ipv6first" | "verbatim" | undefined; + /** + * When `true`, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 + * addresses are placed before IPv6 addresses. This option will be deprecated in favor of `order`. When both are specified, + * `order` has higher precedence. New code should only use `order`. Default value is configurable using {@link setDefaultResultOrder} + * @default true (addresses are not reordered) + * @deprecated Please use `order` option + */ + verbatim?: boolean | undefined; + } + export interface LookupOneOptions extends LookupOptions { + all?: false | undefined; + } + export interface LookupAllOptions extends LookupOptions { + all: true; + } + export interface LookupAddress { + /** + * A string representation of an IPv4 or IPv6 address. + */ + address: string; + /** + * `4` or `6`, denoting the family of `address`, or `0` if the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a + * bug in the name resolution service used by the operating system. + */ + family: number; + } + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is `0` or not provided, then + * IPv4 and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the arguments for `callback` change to `(err, addresses)`, with `addresses` being an array of objects with the + * properties `address` and `family`. + * + * On error, `err` is an `Error` object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dns.lookup()` does not necessarily have anything to do with the DNS protocol. + * The implementation uses an operating system facility that can associate names + * with addresses and vice versa. This implementation can have subtle but + * important consequences on the behavior of any Node.js program. Please take some + * time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v22.x/api/dns.html#implementation-considerations) + * before using `dns.lookup()`. + * + * Example usage: + * + * ```js + * import dns from 'node:dns'; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * dns.lookup('example.com', options, (err, address, family) => + * console.log('address: %j family: IPv%s', address, family)); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dns.lookup('example.com', options, (err, addresses) => + * console.log('addresses: %j', addresses)); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * ``` + * + * If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v22.x/api/util.html#utilpromisifyoriginal) ed + * version, and `all` is not set to `true`, it returns a `Promise` for an `Object` with `address` and `family` properties. + * @since v0.1.90 + */ + export function lookup( + hostname: string, + family: number, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export function lookup( + hostname: string, + options: LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export function lookup( + hostname: string, + options: LookupAllOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void, + ): void; + export function lookup( + hostname: string, + options: LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void, + ): void; + export function lookup( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise; + function __promisify__(hostname: string, options: LookupOptions): Promise; + } + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown. + * + * On an error, `err` is an [`Error`](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-error) object, + * where `err.code` is the error code. + * + * ```js + * import dns from 'node:dns'; + * dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { + * console.log(hostname, service); + * // Prints: localhost ssh + * }); + * ``` + * + * If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v22.x/api/util.html#utilpromisifyoriginal) ed + * version, it returns a `Promise` for an `Object` with `hostname` and `service` properties. + * @since v0.11.14 + */ + export function lookupService( + address: string, + port: number, + callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void, + ): void; + export namespace lookupService { + function __promisify__( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + } + export interface ResolveOptions { + ttl: boolean; + } + export interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + export interface RecordWithTtl { + address: string; + ttl: number; + } + /** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ + export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + export interface AnyARecord extends RecordWithTtl { + type: "A"; + } + export interface AnyAaaaRecord extends RecordWithTtl { + type: "AAAA"; + } + export interface CaaRecord { + critical: number; + issue?: string | undefined; + issuewild?: string | undefined; + iodef?: string | undefined; + contactemail?: string | undefined; + contactphone?: string | undefined; + } + export interface AnyCaaRecord extends CaaRecord { + type: "CAA"; + } + export interface MxRecord { + priority: number; + exchange: string; + } + export interface AnyMxRecord extends MxRecord { + type: "MX"; + } + export interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + export interface AnyNaptrRecord extends NaptrRecord { + type: "NAPTR"; + } + export interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + export interface AnySoaRecord extends SoaRecord { + type: "SOA"; + } + export interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + export interface AnySrvRecord extends SrvRecord { + type: "SRV"; + } + export interface TlsaRecord { + certUsage: number; + selector: number; + match: number; + data: ArrayBuffer; + } + export interface AnyTlsaRecord extends TlsaRecord { + type: "TLSA"; + } + export interface AnyTxtRecord { + type: "TXT"; + entries: string[]; + } + export interface AnyNsRecord { + type: "NS"; + value: string; + } + export interface AnyPtrRecord { + type: "PTR"; + value: string; + } + export interface AnyCnameRecord { + type: "CNAME"; + value: string; + } + export type AnyRecord = + | AnyARecord + | AnyAaaaRecord + | AnyCaaRecord + | AnyCnameRecord + | AnyMxRecord + | AnyNaptrRecord + | AnyNsRecord + | AnyPtrRecord + | AnySoaRecord + | AnySrvRecord + | AnyTlsaRecord + | AnyTxtRecord; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. The `callback` function has arguments `(err, records)`. When successful, `records` will be an array of resource + * records. The type and structure of individual results varies based on `rrtype`: + * + * + * + * On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-error) object, + * where `err.code` is one of the `DNS error codes`. + * @since v0.1.27 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + export function resolve( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "ANY", + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "CAA", + callback: (err: NodeJS.ErrnoException | null, address: CaaRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "MX", + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "NAPTR", + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "SOA", + callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "SRV", + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "TLSA", + callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "TXT", + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: string, + callback: ( + err: NodeJS.ErrnoException | null, + addresses: + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[], + ) => void, + ): void; + export namespace resolve { + function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function __promisify__(hostname: string, rrtype: "ANY"): Promise; + function __promisify__(hostname: string, rrtype: "CAA"): Promise; + function __promisify__(hostname: string, rrtype: "MX"): Promise; + function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; + function __promisify__(hostname: string, rrtype: "SOA"): Promise; + function __promisify__(hostname: string, rrtype: "SRV"): Promise; + function __promisify__(hostname: string, rrtype: "TLSA"): Promise; + function __promisify__(hostname: string, rrtype: "TXT"): Promise; + function __promisify__( + hostname: string, + rrtype: string, + ): Promise< + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[] + >; + } + /** + * Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve4( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve4( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + export function resolve4( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + export namespace resolve4 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv6 addresses. + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve6( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve6( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + export function resolve6( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + export namespace resolve6 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of canonical name records available for the `hostname` (e.g. `['bar.example.com']`). + * @since v0.3.2 + */ + export function resolveCname( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of certification authority authorization records + * available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + export function resolveCaa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void, + ): void; + export namespace resolveCaa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of objects containing both a `priority` and `exchange` property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v0.1.27 + */ + export function resolveMx( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + export namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will contain an array of + * objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v0.9.12 + */ + export function resolveNaptr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + export namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of name server records available for `hostname` (e.g. `['ns1.example.com', 'ns2.example.com']`). + * @since v0.1.90 + */ + export function resolveNs( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * be an array of strings containing the reply records. + * @since v6.0.0 + */ + export function resolvePtr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. The `address` argument passed to the `callback` function will + * be an object with the following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v0.11.10 + */ + export function resolveSoa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void, + ): void; + export namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * be an array of objects with the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v0.1.27 + */ + export function resolveSrv( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + export namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve certificate associations (`TLSA` records) for + * the `hostname`. The `records` argument passed to the `callback` function is an + * array of objects with these properties: + * + * * `certUsage` + * * `selector` + * * `match` + * * `data` + * + * ```js + * { + * certUsage: 3, + * selector: 1, + * match: 1, + * data: [ArrayBuffer] + * } + * ``` + * @since v22.15.0 + */ + export function resolveTlsa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void, + ): void; + export namespace resolveTlsa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. The `records` argument passed to the `callback` function is a + * two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v0.1.27 + */ + export function resolveTxt( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + export namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * The `ret` argument passed to the `callback` function will be an array containing + * various types of records. Each object has a property `type` that indicates the + * type of the current record. And depending on the `type`, additional properties + * will be present on the object: + * + * + * + * Here is an example of the `ret` object passed to the callback: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * + * DNS server operators may choose not to respond to `ANY` queries. It may be better to call individual methods like {@link resolve4}, {@link resolveMx}, and so on. For more details, see + * [RFC 8482](https://tools.ietf.org/html/rfc8482). + */ + export function resolveAny( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + export namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-error) object, where `err.code` is + * one of the [DNS error codes](https://nodejs.org/docs/latest-v22.x/api/dns.html#error-codes). + * @since v0.1.16 + */ + export function reverse( + ip: string, + callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void, + ): void; + /** + * Get the default value for `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v22.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: for `order` defaulting to `ipv4first`. + * * `ipv6first`: for `order` defaulting to `ipv6first`. + * * `verbatim`: for `order` defaulting to `verbatim`. + * @since v18.17.0 + */ + export function getDefaultResultOrder(): "ipv4first" | "ipv6first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dns.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dns.setServers()` method must not be called while a DNS query is in + * progress. + * + * The {@link setServers} method affects only {@link resolve}, `dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}). + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v0.11.3 + * @param servers array of [RFC 5952](https://datatracker.ietf.org/doc/html/rfc5952#section-6) formatted addresses + */ + export function setServers(servers: readonly string[]): void; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v0.11.3 + */ + export function getServers(): string[]; + /** + * Set the default value of `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v22.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: sets default `order` to `ipv4first`. + * * `ipv6first`: sets default `order` to `ipv6first`. + * * `verbatim`: sets default `order` to `verbatim`. + * + * The default is `verbatim` and {@link setDefaultResultOrder} have higher + * priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--dns-result-orderorder). When using + * [worker threads](https://nodejs.org/docs/latest-v22.x/api/worker_threads.html), {@link setDefaultResultOrder} from the main + * thread won't affect the default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`. + */ + export function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void; + // Error codes + export const NODATA: "ENODATA"; + export const FORMERR: "EFORMERR"; + export const SERVFAIL: "ESERVFAIL"; + export const NOTFOUND: "ENOTFOUND"; + export const NOTIMP: "ENOTIMP"; + export const REFUSED: "EREFUSED"; + export const BADQUERY: "EBADQUERY"; + export const BADNAME: "EBADNAME"; + export const BADFAMILY: "EBADFAMILY"; + export const BADRESP: "EBADRESP"; + export const CONNREFUSED: "ECONNREFUSED"; + export const TIMEOUT: "ETIMEOUT"; + export const EOF: "EOF"; + export const FILE: "EFILE"; + export const NOMEM: "ENOMEM"; + export const DESTRUCTION: "EDESTRUCTION"; + export const BADSTR: "EBADSTR"; + export const BADFLAGS: "EBADFLAGS"; + export const NONAME: "ENONAME"; + export const BADHINTS: "EBADHINTS"; + export const NOTINITIALIZED: "ENOTINITIALIZED"; + export const LOADIPHLPAPI: "ELOADIPHLPAPI"; + export const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS"; + export const CANCELLED: "ECANCELLED"; + export interface ResolverOptions { + /** + * Query timeout in milliseconds, or `-1` to use the default timeout. + */ + timeout?: number | undefined; + /** + * The number of tries the resolver will try contacting each name server before giving up. + * @default 4 + */ + tries?: number | undefined; + /** + * The max retry timeout, in milliseconds. + * @default 0 + */ + maxTimeout?: number | undefined; + } + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v22.x/api/dns.html#dnssetserversservers) does not affect + * other resolvers: + * + * ```js + * import { Resolver } from 'node:dns'; + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org', (err, addresses) => { + * // ... + * }); + * ``` + * + * The following methods from the `node:dns` module are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v8.3.0 + */ + export class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTlsa: typeof resolveTlsa; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } + export { dnsPromises as promises }; +} +declare module "node:dns" { + export * from "dns"; +} diff --git a/node_modules/@types/node/dns/promises.d.ts b/node_modules/@types/node/dns/promises.d.ts new file mode 100644 index 0000000..a7ba9bb --- /dev/null +++ b/node_modules/@types/node/dns/promises.d.ts @@ -0,0 +1,503 @@ +/** + * The `dns.promises` API provides an alternative set of asynchronous DNS methods + * that return `Promise` objects rather than using callbacks. The API is accessible + * via `import { promises as dnsPromises } from 'node:dns'` or `import dnsPromises from 'node:dns/promises'`. + * @since v10.6.0 + */ +declare module "dns/promises" { + import { + AnyRecord, + CaaRecord, + LookupAddress, + LookupAllOptions, + LookupOneOptions, + LookupOptions, + MxRecord, + NaptrRecord, + RecordWithTtl, + ResolveOptions, + ResolverOptions, + ResolveWithTtlOptions, + SoaRecord, + SrvRecord, + TlsaRecord, + } from "node:dns"; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v10.6.0 + */ + function getServers(): string[]; + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the `Promise` is resolved with `addresses` being an array of objects with the properties `address` and `family`. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options) does not necessarily have anything to do with the DNS + * protocol. The implementation uses an operating system facility that can + * associate names with addresses and vice versa. This implementation can have + * subtle but important consequences on the behavior of any Node.js program. Please + * take some time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v20.x/api/dns.html#implementation-considerations) before + * using `dnsPromises.lookup()`. + * + * Example usage: + * + * ```js + * import dns from 'node:dns'; + * const dnsPromises = dns.promises; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('address: %j family: IPv%s', result.address, result.family); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * }); + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('addresses: %j', result); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * }); + * ``` + * @since v10.6.0 + */ + function lookup(hostname: string, family: number): Promise; + function lookup(hostname: string, options: LookupOneOptions): Promise; + function lookup(hostname: string, options: LookupAllOptions): Promise; + function lookup(hostname: string, options: LookupOptions): Promise; + function lookup(hostname: string): Promise; + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code. + * + * ```js + * import dnsPromises from 'node:dns'; + * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { + * console.log(result.hostname, result.service); + * // Prints: localhost ssh + * }); + * ``` + * @since v10.6.0 + */ + function lookupService( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. When successful, the `Promise` is resolved with an + * array of resource records. The type and structure of individual results vary + * based on `rrtype`: + * + * + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes). + * @since v10.6.0 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + function resolve(hostname: string): Promise; + function resolve(hostname: string, rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function resolve(hostname: string, rrtype: "ANY"): Promise; + function resolve(hostname: string, rrtype: "CAA"): Promise; + function resolve(hostname: string, rrtype: "MX"): Promise; + function resolve(hostname: string, rrtype: "NAPTR"): Promise; + function resolve(hostname: string, rrtype: "SOA"): Promise; + function resolve(hostname: string, rrtype: "SRV"): Promise; + function resolve(hostname: string, rrtype: "TLSA"): Promise; + function resolve(hostname: string, rrtype: "TXT"): Promise; + function resolve(hostname: string, rrtype: string): Promise< + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[] + >; + /** + * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv4 + * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve4(hostname: string): Promise; + function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve4(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv6 + * addresses. + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve6(hostname: string): Promise; + function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve6(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * On success, the `Promise` is resolved with an array containing various types of + * records. Each object has a property `type` that indicates the type of the + * current record. And depending on the `type`, additional properties will be + * present on the object: + * + * + * + * Here is an example of the result object: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * @since v10.6.0 + */ + function resolveAny(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success, + * the `Promise` is resolved with an array of objects containing available + * certification authority authorization records available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + function resolveCaa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success, + * the `Promise` is resolved with an array of canonical name records available for + * the `hostname` (e.g. `['bar.example.com']`). + * @since v10.6.0 + */ + function resolveCname(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects + * containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v10.6.0 + */ + function resolveMx(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. On success, the `Promise` is resolved with an array + * of objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v10.6.0 + */ + function resolveNaptr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. On success, the `Promise` is resolved with an array of name server + * records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`). + * @since v10.6.0 + */ + function resolveNs(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. On success, the `Promise` is resolved with an array of strings + * containing the reply records. + * @since v10.6.0 + */ + function resolvePtr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. On success, the `Promise` is resolved with an object with the + * following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v10.6.0 + */ + function resolveSoa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects with + * the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v10.6.0 + */ + function resolveSrv(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve certificate associations (`TLSA` records) for + * the `hostname`. On success, the `Promise` is resolved with an array of objectsAdd commentMore actions + * with these properties: + * + * * `certUsage` + * * `selector` + * * `match` + * * `data` + * + * ```js + * { + * certUsage: 3, + * selector: 1, + * match: 1, + * data: [ArrayBuffer] + * } + * ``` + * @since v22.15.0 + */ + function resolveTlsa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. On success, the `Promise` is resolved with a two-dimensional array + * of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v10.6.0 + */ + function resolveTxt(hostname: string): Promise; + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes). + * @since v10.6.0 + */ + function reverse(ip: string): Promise; + /** + * Get the default value for `verbatim` in {@link lookup} and [dnsPromises.lookup()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v20.1.0 + */ + function getDefaultResultOrder(): "ipv4first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dnsPromises.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dnsPromises.setServers()` method must not be called while a DNS query is in + * progress. + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v10.6.0 + * @param servers array of `RFC 5952` formatted addresses + */ + function setServers(servers: readonly string[]): void; + /** + * Set the default value of `order` in `dns.lookup()` and `{@link lookup}`. The value could be: + * + * * `ipv4first`: sets default `order` to `ipv4first`. + * * `ipv6first`: sets default `order` to `ipv6first`. + * * `verbatim`: sets default `order` to `verbatim`. + * + * The default is `verbatim` and [dnsPromises.setDefaultResultOrder()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * have higher priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder). + * When using [worker threads](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html), [`dnsPromises.setDefaultResultOrder()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * from the main thread won't affect the default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`. + */ + function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void; + // Error codes + const NODATA: "ENODATA"; + const FORMERR: "EFORMERR"; + const SERVFAIL: "ESERVFAIL"; + const NOTFOUND: "ENOTFOUND"; + const NOTIMP: "ENOTIMP"; + const REFUSED: "EREFUSED"; + const BADQUERY: "EBADQUERY"; + const BADNAME: "EBADNAME"; + const BADFAMILY: "EBADFAMILY"; + const BADRESP: "EBADRESP"; + const CONNREFUSED: "ECONNREFUSED"; + const TIMEOUT: "ETIMEOUT"; + const EOF: "EOF"; + const FILE: "EFILE"; + const NOMEM: "ENOMEM"; + const DESTRUCTION: "EDESTRUCTION"; + const BADSTR: "EBADSTR"; + const BADFLAGS: "EBADFLAGS"; + const NONAME: "ENONAME"; + const BADHINTS: "EBADHINTS"; + const NOTINITIALIZED: "ENOTINITIALIZED"; + const LOADIPHLPAPI: "ELOADIPHLPAPI"; + const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS"; + const CANCELLED: "ECANCELLED"; + + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetserversservers) does not affect + * other resolvers: + * + * ```js + * import { promises } from 'node:dns'; + * const resolver = new promises.Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org').then((addresses) => { + * // ... + * }); + * + * // Alternatively, the same code can be written using async-await style. + * (async function() { + * const addresses = await resolver.resolve4('example.org'); + * })(); + * ``` + * + * The following methods from the `dnsPromises` API are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v10.6.0 + */ + class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTlsa: typeof resolveTlsa; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} +declare module "node:dns/promises" { + export * from "dns/promises"; +} diff --git a/node_modules/@types/node/domain.d.ts b/node_modules/@types/node/domain.d.ts new file mode 100644 index 0000000..ba8a02c --- /dev/null +++ b/node_modules/@types/node/domain.d.ts @@ -0,0 +1,170 @@ +/** + * **This module is pending deprecation.** Once a replacement API has been + * finalized, this module will be fully deprecated. Most developers should + * **not** have cause to use this module. Users who absolutely must have + * the functionality that domains provide may rely on it for the time being + * but should expect to have to migrate to a different solution + * in the future. + * + * Domains provide a way to handle multiple different IO operations as a + * single group. If any of the event emitters or callbacks registered to a + * domain emit an `'error'` event, or throw an error, then the domain object + * will be notified, rather than losing the context of the error in the `process.on('uncaughtException')` handler, or causing the program to + * exit immediately with an error code. + * @deprecated Since v1.4.2 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/domain.js) + */ +declare module "domain" { + import EventEmitter = require("node:events"); + /** + * The `Domain` class encapsulates the functionality of routing errors and + * uncaught exceptions to the active `Domain` object. + * + * To handle the errors that it catches, listen to its `'error'` event. + */ + class Domain extends EventEmitter { + /** + * An array of timers and event emitters that have been explicitly added + * to the domain. + */ + members: Array; + /** + * The `enter()` method is plumbing used by the `run()`, `bind()`, and `intercept()` methods to set the active domain. It sets `domain.active` and `process.domain` to the domain, and implicitly + * pushes the domain onto the domain + * stack managed by the domain module (see {@link exit} for details on the + * domain stack). The call to `enter()` delimits the beginning of a chain of + * asynchronous calls and I/O operations bound to a domain. + * + * Calling `enter()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + enter(): void; + /** + * The `exit()` method exits the current domain, popping it off the domain stack. + * Any time execution is going to switch to the context of a different chain of + * asynchronous calls, it's important to ensure that the current domain is exited. + * The call to `exit()` delimits either the end of or an interruption to the chain + * of asynchronous calls and I/O operations bound to a domain. + * + * If there are multiple, nested domains bound to the current execution context, `exit()` will exit any domains nested within this domain. + * + * Calling `exit()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + exit(): void; + /** + * Run the supplied function in the context of the domain, implicitly + * binding all event emitters, timers, and low-level requests that are + * created in that context. Optionally, arguments can be passed to + * the function. + * + * This is the most basic way to use a domain. + * + * ```js + * import domain from 'node:domain'; + * import fs from 'node:fs'; + * const d = domain.create(); + * d.on('error', (er) => { + * console.error('Caught error!', er); + * }); + * d.run(() => { + * process.nextTick(() => { + * setTimeout(() => { // Simulating some various async stuff + * fs.open('non-existent file', 'r', (er, fd) => { + * if (er) throw er; + * // proceed... + * }); + * }, 100); + * }); + * }); + * ``` + * + * In this example, the `d.on('error')` handler will be triggered, rather + * than crashing the program. + */ + run(fn: (...args: any[]) => T, ...args: any[]): T; + /** + * Explicitly adds an emitter to the domain. If any event handlers called by + * the emitter throw an error, or if the emitter emits an `'error'` event, it + * will be routed to the domain's `'error'` event, just like with implicit + * binding. + * + * This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by + * the domain `'error'` handler. + * + * If the Timer or `EventEmitter` was already bound to a domain, it is removed + * from that one, and bound to this one instead. + * @param emitter emitter or timer to be added to the domain + */ + add(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The opposite of {@link add}. Removes domain handling from the + * specified emitter. + * @param emitter emitter or timer to be removed from the domain + */ + remove(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The returned function will be a wrapper around the supplied callback + * function. When the returned function is called, any errors that are + * thrown will be routed to the domain's `'error'` event. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.bind((er, data) => { + * // If this throws, it will also be passed to the domain. + * return cb(er, data ? JSON.parse(data) : null); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The bound function + */ + bind(callback: T): T; + /** + * This method is almost identical to {@link bind}. However, in + * addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function. + * + * In this way, the common `if (err) return callback(err);` pattern can be replaced + * with a single error handler in a single place. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.intercept((data) => { + * // Note, the first argument is never passed to the + * // callback since it is assumed to be the 'Error' argument + * // and thus intercepted by the domain. + * + * // If this throws, it will also be passed to the domain + * // so the error-handling logic can be moved to the 'error' + * // event on the domain instead of being repeated throughout + * // the program. + * return cb(null, JSON.parse(data)); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The intercepted function + */ + intercept(callback: T): T; + } + function create(): Domain; +} +declare module "node:domain" { + export * from "domain"; +} diff --git a/node_modules/@types/node/events.d.ts b/node_modules/@types/node/events.d.ts new file mode 100644 index 0000000..c336a28 --- /dev/null +++ b/node_modules/@types/node/events.d.ts @@ -0,0 +1,976 @@ +/** + * Much of the Node.js core API is built around an idiomatic asynchronous + * event-driven architecture in which certain kinds of objects (called "emitters") + * emit named events that cause `Function` objects ("listeners") to be called. + * + * For instance: a `net.Server` object emits an event each time a peer + * connects to it; a `fs.ReadStream` emits an event when the file is opened; + * a `stream` emits an event whenever data is available to be read. + * + * All objects that emit events are instances of the `EventEmitter` class. These + * objects expose an `eventEmitter.on()` function that allows one or more + * functions to be attached to named events emitted by the object. Typically, + * event names are camel-cased strings but any valid JavaScript property key + * can be used. + * + * When the `EventEmitter` object emits an event, all of the functions attached + * to that specific event are called _synchronously_. Any values returned by the + * called listeners are _ignored_ and discarded. + * + * The following example shows a simple `EventEmitter` instance with a single + * listener. The `eventEmitter.on()` method is used to register listeners, while + * the `eventEmitter.emit()` method is used to trigger the event. + * + * ```js + * import { EventEmitter } from 'node:events'; + * + * class MyEmitter extends EventEmitter {} + * + * const myEmitter = new MyEmitter(); + * myEmitter.on('event', () => { + * console.log('an event occurred!'); + * }); + * myEmitter.emit('event'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/events.js) + */ +declare module "events" { + import { AsyncResource, AsyncResourceOptions } from "node:async_hooks"; + interface EventEmitterOptions { + /** + * Enables automatic capturing of promise rejection. + */ + captureRejections?: boolean | undefined; + } + interface StaticEventEmitterOptions { + /** + * Can be used to cancel awaiting events. + */ + signal?: AbortSignal | undefined; + } + interface StaticEventEmitterIteratorOptions extends StaticEventEmitterOptions { + /** + * Names of events that will end the iteration. + */ + close?: string[] | undefined; + /** + * The high watermark. The emitter is paused every time the size of events being buffered is higher than it. + * Supported only on emitters implementing `pause()` and `resume()` methods. + * @default Number.MAX_SAFE_INTEGER + */ + highWaterMark?: number | undefined; + /** + * The low watermark. The emitter is resumed every time the size of events being buffered is lower than it. + * Supported only on emitters implementing `pause()` and `resume()` methods. + * @default 1 + */ + lowWaterMark?: number | undefined; + } + interface EventEmitter = DefaultEventMap> extends NodeJS.EventEmitter {} + type EventMap = Record | DefaultEventMap; + type DefaultEventMap = [never]; + type AnyRest = [...args: any[]]; + type Args = T extends DefaultEventMap ? AnyRest : ( + K extends keyof T ? T[K] : never + ); + type Key = T extends DefaultEventMap ? string | symbol : K | keyof T; + type Key2 = T extends DefaultEventMap ? string | symbol : K & keyof T; + type Listener = T extends DefaultEventMap ? F : ( + K extends keyof T ? ( + T[K] extends unknown[] ? (...args: T[K]) => void : never + ) + : never + ); + type Listener1 = Listener void>; + type Listener2 = Listener; + + /** + * The `EventEmitter` class is defined and exposed by the `node:events` module: + * + * ```js + * import { EventEmitter } from 'node:events'; + * ``` + * + * All `EventEmitter`s emit the event `'newListener'` when new listeners are + * added and `'removeListener'` when existing listeners are removed. + * + * It supports the following option: + * @since v0.1.26 + */ + class EventEmitter = DefaultEventMap> { + constructor(options?: EventEmitterOptions); + + [EventEmitter.captureRejectionSymbol]?(error: Error, event: Key, ...args: Args): void; + + /** + * Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given + * event or that is rejected if the `EventEmitter` emits `'error'` while waiting. + * The `Promise` will resolve with an array of all the arguments emitted to the + * given event. + * + * This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event + * semantics and does not listen to the `'error'` event. + * + * ```js + * import { once, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * process.nextTick(() => { + * ee.emit('myevent', 42); + * }); + * + * const [value] = await once(ee, 'myevent'); + * console.log(value); + * + * const err = new Error('kaboom'); + * process.nextTick(() => { + * ee.emit('error', err); + * }); + * + * try { + * await once(ee, 'myevent'); + * } catch (err) { + * console.error('error happened', err); + * } + * ``` + * + * The special handling of the `'error'` event is only used when `events.once()` is used to wait for another event. If `events.once()` is used to wait for the + * '`error'` event itself, then it is treated as any other kind of event without + * special handling: + * + * ```js + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.error('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * const ac = new AbortController(); + * + * async function foo(emitter, event, signal) { + * try { + * await once(emitter, event, { signal }); + * console.log('event emitted!'); + * } catch (error) { + * if (error.name === 'AbortError') { + * console.error('Waiting for the event was canceled!'); + * } else { + * console.error('There was an error', error.message); + * } + * } + * } + * + * foo(ee, 'foo', ac.signal); + * ac.abort(); // Abort waiting for the event + * ee.emit('foo'); // Prints: Waiting for the event was canceled! + * ``` + * @since v11.13.0, v10.16.0 + */ + static once( + emitter: NodeJS.EventEmitter, + eventName: string | symbol, + options?: StaticEventEmitterOptions, + ): Promise; + static once(emitter: EventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + /** + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo')) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * ``` + * + * Returns an `AsyncIterator` that iterates `eventName` events. It will throw + * if the `EventEmitter` emits `'error'`. It removes all listeners when + * exiting the loop. The `value` returned by each iteration is an array + * composed of the emitted event arguments. + * + * An `AbortSignal` can be used to cancel waiting on events: + * + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ac = new AbortController(); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo', { signal: ac.signal })) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * + * process.nextTick(() => ac.abort()); + * ``` + * + * Use the `close` option to specify an array of event names that will end the iteration: + * + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * ee.emit('close'); + * }); + * + * for await (const event of on(ee, 'foo', { close: ['close'] })) { + * console.log(event); // prints ['bar'] [42] + * } + * // the loop will exit after 'close' is emitted + * console.log('done'); // prints 'done' + * ``` + * @since v13.6.0, v12.16.0 + * @return An `AsyncIterator` that iterates `eventName` events emitted by the `emitter` + */ + static on( + emitter: NodeJS.EventEmitter, + eventName: string | symbol, + options?: StaticEventEmitterIteratorOptions, + ): NodeJS.AsyncIterator; + static on( + emitter: EventTarget, + eventName: string, + options?: StaticEventEmitterIteratorOptions, + ): NodeJS.AsyncIterator; + /** + * A class method that returns the number of listeners for the given `eventName` registered on the given `emitter`. + * + * ```js + * import { EventEmitter, listenerCount } from 'node:events'; + * + * const myEmitter = new EventEmitter(); + * myEmitter.on('event', () => {}); + * myEmitter.on('event', () => {}); + * console.log(listenerCount(myEmitter, 'event')); + * // Prints: 2 + * ``` + * @since v0.9.12 + * @deprecated Since v3.2.0 - Use `listenerCount` instead. + * @param emitter The emitter to query + * @param eventName The event name + */ + static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * For `EventEmitter`s this behaves exactly the same as calling `.listeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the event listeners for the + * event target. This is useful for debugging and diagnostic purposes. + * + * ```js + * import { getEventListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] + * } + * ``` + * @since v15.2.0, v14.17.0 + */ + static getEventListeners(emitter: EventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; + /** + * Returns the currently set max amount of listeners. + * + * For `EventEmitter`s this behaves exactly the same as calling `.getMaxListeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the max event listeners for the + * event target. If the number of event handlers on a single EventTarget exceeds + * the max set, the EventTarget will print a warning. + * + * ```js + * import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * console.log(getMaxListeners(ee)); // 10 + * setMaxListeners(11, ee); + * console.log(getMaxListeners(ee)); // 11 + * } + * { + * const et = new EventTarget(); + * console.log(getMaxListeners(et)); // 10 + * setMaxListeners(11, et); + * console.log(getMaxListeners(et)); // 11 + * } + * ``` + * @since v19.9.0 + */ + static getMaxListeners(emitter: EventTarget | NodeJS.EventEmitter): number; + /** + * ```js + * import { setMaxListeners, EventEmitter } from 'node:events'; + * + * const target = new EventTarget(); + * const emitter = new EventEmitter(); + * + * setMaxListeners(5, target, emitter); + * ``` + * @since v15.4.0 + * @param n A non-negative number. The maximum number of listeners per `EventTarget` event. + * @param eventTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter} + * objects. + */ + static setMaxListeners(n?: number, ...eventTargets: Array): void; + /** + * Listens once to the `abort` event on the provided `signal`. + * + * Listening to the `abort` event on abort signals is unsafe and may + * lead to resource leaks since another third party with the signal can + * call `e.stopImmediatePropagation()`. Unfortunately Node.js cannot change + * this since it would violate the web standard. Additionally, the original + * API makes it easy to forget to remove listeners. + * + * This API allows safely using `AbortSignal`s in Node.js APIs by solving these + * two issues by listening to the event such that `stopImmediatePropagation` does + * not prevent the listener from running. + * + * Returns a disposable so that it may be unsubscribed from more easily. + * + * ```js + * import { addAbortListener } from 'node:events'; + * + * function example(signal) { + * let disposable; + * try { + * signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); + * disposable = addAbortListener(signal, (e) => { + * // Do something when signal is aborted. + * }); + * } finally { + * disposable?.[Symbol.dispose](); + * } + * } + * ``` + * @since v20.5.0 + * @return Disposable that removes the `abort` listener. + */ + static addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable; + /** + * This symbol shall be used to install a listener for only monitoring `'error'` events. Listeners installed using this symbol are called before the regular `'error'` listeners are called. + * + * Installing a listener using this symbol does not change the behavior once an `'error'` event is emitted. Therefore, the process will still crash if no + * regular `'error'` listener is installed. + * @since v13.6.0, v12.17.0 + */ + static readonly errorMonitor: unique symbol; + /** + * Value: `Symbol.for('nodejs.rejection')` + * + * See how to write a custom `rejection handler`. + * @since v13.4.0, v12.16.0 + */ + static readonly captureRejectionSymbol: unique symbol; + /** + * Value: [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) + * + * Change the default `captureRejections` option on all new `EventEmitter` objects. + * @since v13.4.0, v12.16.0 + */ + static captureRejections: boolean; + /** + * By default, a maximum of `10` listeners can be registered for any single + * event. This limit can be changed for individual `EventEmitter` instances + * using the `emitter.setMaxListeners(n)` method. To change the default + * for _all_`EventEmitter` instances, the `events.defaultMaxListeners` property + * can be used. If this value is not a positive number, a `RangeError` is thrown. + * + * Take caution when setting the `events.defaultMaxListeners` because the + * change affects _all_ `EventEmitter` instances, including those created before + * the change is made. However, calling `emitter.setMaxListeners(n)` still has + * precedence over `events.defaultMaxListeners`. + * + * This is not a hard limit. The `EventEmitter` instance will allow + * more listeners to be added but will output a trace warning to stderr indicating + * that a "possible EventEmitter memory leak" has been detected. For any single + * `EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()` methods can be used to + * temporarily avoid this warning: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.setMaxListeners(emitter.getMaxListeners() + 1); + * emitter.once('event', () => { + * // do stuff + * emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); + * }); + * ``` + * + * The `--trace-warnings` command-line flag can be used to display the + * stack trace for such warnings. + * + * The emitted warning can be inspected with `process.on('warning')` and will + * have the additional `emitter`, `type`, and `count` properties, referring to + * the event emitter instance, the event's name and the number of attached + * listeners, respectively. + * Its `name` property is set to `'MaxListenersExceededWarning'`. + * @since v0.11.2 + */ + static defaultMaxListeners: number; + } + import internal = require("node:events"); + namespace EventEmitter { + // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4 + export { internal as EventEmitter }; + export interface Abortable { + /** + * When provided the corresponding `AbortController` can be used to cancel an asynchronous action. + */ + signal?: AbortSignal | undefined; + } + + export interface EventEmitterReferencingAsyncResource extends AsyncResource { + readonly eventEmitter: EventEmitterAsyncResource; + } + + export interface EventEmitterAsyncResourceOptions extends AsyncResourceOptions, EventEmitterOptions { + /** + * The type of async event, this is required when instantiating `EventEmitterAsyncResource` + * directly rather than as a child class. + * @default new.target.name if instantiated as a child class. + */ + name?: string | undefined; + } + + /** + * Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that + * require manual async tracking. Specifically, all events emitted by instances + * of `events.EventEmitterAsyncResource` will run within its `async context`. + * + * ```js + * import { EventEmitterAsyncResource, EventEmitter } from 'node:events'; + * import { notStrictEqual, strictEqual } from 'node:assert'; + * import { executionAsyncId, triggerAsyncId } from 'node:async_hooks'; + * + * // Async tracking tooling will identify this as 'Q'. + * const ee1 = new EventEmitterAsyncResource({ name: 'Q' }); + * + * // 'foo' listeners will run in the EventEmitters async context. + * ee1.on('foo', () => { + * strictEqual(executionAsyncId(), ee1.asyncId); + * strictEqual(triggerAsyncId(), ee1.triggerAsyncId); + * }); + * + * const ee2 = new EventEmitter(); + * + * // 'foo' listeners on ordinary EventEmitters that do not track async + * // context, however, run in the same async context as the emit(). + * ee2.on('foo', () => { + * notStrictEqual(executionAsyncId(), ee2.asyncId); + * notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId); + * }); + * + * Promise.resolve().then(() => { + * ee1.emit('foo'); + * ee2.emit('foo'); + * }); + * ``` + * + * The `EventEmitterAsyncResource` class has the same methods and takes the + * same options as `EventEmitter` and `AsyncResource` themselves. + * @since v17.4.0, v16.14.0 + */ + export class EventEmitterAsyncResource extends EventEmitter { + /** + * @param options Only optional in child class. + */ + constructor(options?: EventEmitterAsyncResourceOptions); + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + */ + emitDestroy(): void; + /** + * The unique `asyncId` assigned to the resource. + */ + readonly asyncId: number; + /** + * The same triggerAsyncId that is passed to the AsyncResource constructor. + */ + readonly triggerAsyncId: number; + /** + * The returned `AsyncResource` object has an additional `eventEmitter` property + * that provides a reference to this `EventEmitterAsyncResource`. + */ + readonly asyncResource: EventEmitterReferencingAsyncResource; + } + /** + * The `NodeEventTarget` is a Node.js-specific extension to `EventTarget` + * that emulates a subset of the `EventEmitter` API. + * @since v14.5.0 + */ + export interface NodeEventTarget extends EventTarget { + /** + * Node.js-specific extension to the `EventTarget` class that emulates the + * equivalent `EventEmitter` API. The only difference between `addListener()` and + * `addEventListener()` is that `addListener()` will return a reference to the + * `EventTarget`. + * @since v14.5.0 + */ + addListener(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class that dispatches the + * `arg` to the list of handlers for `type`. + * @since v15.2.0 + * @returns `true` if event listeners registered for the `type` exist, + * otherwise `false`. + */ + emit(type: string, arg: any): boolean; + /** + * Node.js-specific extension to the `EventTarget` class that returns an array + * of event `type` names for which event listeners are registered. + * @since 14.5.0 + */ + eventNames(): string[]; + /** + * Node.js-specific extension to the `EventTarget` class that returns the number + * of event listeners registered for the `type`. + * @since v14.5.0 + */ + listenerCount(type: string): number; + /** + * Node.js-specific extension to the `EventTarget` class that sets the number + * of max event listeners as `n`. + * @since v14.5.0 + */ + setMaxListeners(n: number): void; + /** + * Node.js-specific extension to the `EventTarget` class that returns the number + * of max event listeners. + * @since v14.5.0 + */ + getMaxListeners(): number; + /** + * Node.js-specific alias for `eventTarget.removeEventListener()`. + * @since v14.5.0 + */ + off(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + /** + * Node.js-specific alias for `eventTarget.addEventListener()`. + * @since v14.5.0 + */ + on(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class that adds a `once` + * listener for the given event `type`. This is equivalent to calling `on` + * with the `once` option set to `true`. + * @since v14.5.0 + */ + once(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class. If `type` is specified, + * removes all registered listeners for `type`, otherwise removes all registered + * listeners. + * @since v14.5.0 + */ + removeAllListeners(type?: string): this; + /** + * Node.js-specific extension to the `EventTarget` class that removes the + * `listener` for the given `type`. The only difference between `removeListener()` + * and `removeEventListener()` is that `removeListener()` will return a reference + * to the `EventTarget`. + * @since v14.5.0 + */ + removeListener(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + } + } + global { + namespace NodeJS { + interface EventEmitter = DefaultEventMap> { + [EventEmitter.captureRejectionSymbol]?(error: Error, event: Key, ...args: Args): void; + /** + * Alias for `emitter.on(eventName, listener)`. + * @since v0.1.26 + */ + addListener(eventName: Key, listener: Listener1): this; + /** + * Adds the `listener` function to the end of the listeners array for the event + * named `eventName`. No checks are made to see if the `listener` has already + * been added. Multiple calls passing the same combination of `eventName` and + * `listener` will result in the `listener` being added, and called, multiple times. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The `emitter.prependListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEE = new EventEmitter(); + * myEE.on('foo', () => console.log('a')); + * myEE.prependListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.1.101 + * @param eventName The name of the event. + * @param listener The callback function + */ + on(eventName: Key, listener: Listener1): this; + /** + * Adds a **one-time** `listener` function for the event named `eventName`. The + * next time `eventName` is triggered, this listener is removed and then invoked. + * + * ```js + * server.once('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The `emitter.prependOnceListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEE = new EventEmitter(); + * myEE.once('foo', () => console.log('a')); + * myEE.prependOnceListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.3.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + once(eventName: Key, listener: Listener1): this; + /** + * Removes the specified `listener` from the listener array for the event named `eventName`. + * + * ```js + * const callback = (stream) => { + * console.log('someone connected!'); + * }; + * server.on('connection', callback); + * // ... + * server.removeListener('connection', callback); + * ``` + * + * `removeListener()` will remove, at most, one instance of a listener from the + * listener array. If any single listener has been added multiple times to the + * listener array for the specified `eventName`, then `removeListener()` must be + * called multiple times to remove each instance. + * + * Once an event is emitted, all listeners attached to it at the + * time of emitting are called in order. This implies that any `removeListener()` or `removeAllListeners()` calls _after_ emitting and _before_ the last listener finishes execution + * will not remove them from`emit()` in progress. Subsequent events behave as expected. + * + * ```js + * import { EventEmitter } from 'node:events'; + * class MyEmitter extends EventEmitter {} + * const myEmitter = new MyEmitter(); + * + * const callbackA = () => { + * console.log('A'); + * myEmitter.removeListener('event', callbackB); + * }; + * + * const callbackB = () => { + * console.log('B'); + * }; + * + * myEmitter.on('event', callbackA); + * + * myEmitter.on('event', callbackB); + * + * // callbackA removes listener callbackB but it will still be called. + * // Internal listener array at time of emit [callbackA, callbackB] + * myEmitter.emit('event'); + * // Prints: + * // A + * // B + * + * // callbackB is now removed. + * // Internal listener array [callbackA] + * myEmitter.emit('event'); + * // Prints: + * // A + * ``` + * + * Because listeners are managed using an internal array, calling this will + * change the position indices of any listener registered _after_ the listener + * being removed. This will not impact the order in which listeners are called, + * but it means that any copies of the listener array as returned by + * the `emitter.listeners()` method will need to be recreated. + * + * When a single function has been added as a handler multiple times for a single + * event (as in the example below), `removeListener()` will remove the most + * recently added instance. In the example the `once('ping')` listener is removed: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const ee = new EventEmitter(); + * + * function pong() { + * console.log('pong'); + * } + * + * ee.on('ping', pong); + * ee.once('ping', pong); + * ee.removeListener('ping', pong); + * + * ee.emit('ping'); + * ee.emit('ping'); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeListener(eventName: Key, listener: Listener1): this; + /** + * Alias for `emitter.removeListener()`. + * @since v10.0.0 + */ + off(eventName: Key, listener: Listener1): this; + /** + * Removes all listeners, or those of the specified `eventName`. + * + * It is bad practice to remove listeners added elsewhere in the code, + * particularly when the `EventEmitter` instance was created by some other + * component or module (e.g. sockets or file streams). + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeAllListeners(eventName?: Key): this; + /** + * By default `EventEmitter`s will print a warning if more than `10` listeners are + * added for a particular event. This is a useful default that helps finding + * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be + * modified for this specific `EventEmitter` instance. The value can be set to `Infinity` (or `0`) to indicate an unlimited number of listeners. + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.3.5 + */ + setMaxListeners(n: number): this; + /** + * Returns the current max listener value for the `EventEmitter` which is either + * set by `emitter.setMaxListeners(n)` or defaults to {@link EventEmitter.defaultMaxListeners}. + * @since v1.0.0 + */ + getMaxListeners(): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * console.log(util.inspect(server.listeners('connection'))); + * // Prints: [ [Function] ] + * ``` + * @since v0.1.26 + */ + listeners(eventName: Key): Array>; + /** + * Returns a copy of the array of listeners for the event named `eventName`, + * including any wrappers (such as those created by `.once()`). + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.once('log', () => console.log('log once')); + * + * // Returns a new Array with a function `onceWrapper` which has a property + * // `listener` which contains the original listener bound above + * const listeners = emitter.rawListeners('log'); + * const logFnWrapper = listeners[0]; + * + * // Logs "log once" to the console and does not unbind the `once` event + * logFnWrapper.listener(); + * + * // Logs "log once" to the console and removes the listener + * logFnWrapper(); + * + * emitter.on('log', () => console.log('log persistently')); + * // Will return a new Array with a single function bound by `.on()` above + * const newListeners = emitter.rawListeners('log'); + * + * // Logs "log persistently" twice + * newListeners[0](); + * emitter.emit('log'); + * ``` + * @since v9.4.0 + */ + rawListeners(eventName: Key): Array>; + /** + * Synchronously calls each of the listeners registered for the event named `eventName`, in the order they were registered, passing the supplied arguments + * to each. + * + * Returns `true` if the event had listeners, `false` otherwise. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEmitter = new EventEmitter(); + * + * // First listener + * myEmitter.on('event', function firstListener() { + * console.log('Helloooo! first listener'); + * }); + * // Second listener + * myEmitter.on('event', function secondListener(arg1, arg2) { + * console.log(`event with parameters ${arg1}, ${arg2} in second listener`); + * }); + * // Third listener + * myEmitter.on('event', function thirdListener(...args) { + * const parameters = args.join(', '); + * console.log(`event with parameters ${parameters} in third listener`); + * }); + * + * console.log(myEmitter.listeners('event')); + * + * myEmitter.emit('event', 1, 2, 3, 4, 5); + * + * // Prints: + * // [ + * // [Function: firstListener], + * // [Function: secondListener], + * // [Function: thirdListener] + * // ] + * // Helloooo! first listener + * // event with parameters 1, 2 in second listener + * // event with parameters 1, 2, 3, 4, 5 in third listener + * ``` + * @since v0.1.26 + */ + emit(eventName: Key, ...args: Args): boolean; + /** + * Returns the number of listeners listening for the event named `eventName`. + * If `listener` is provided, it will return how many times the listener is found + * in the list of the listeners of the event. + * @since v3.2.0 + * @param eventName The name of the event being listened for + * @param listener The event handler function + */ + listenerCount(eventName: Key, listener?: Listener2): number; + /** + * Adds the `listener` function to the _beginning_ of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName` + * and `listener` will result in the `listener` being added, and called, multiple times. + * + * ```js + * server.prependListener('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependListener(eventName: Key, listener: Listener1): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName` to the _beginning_ of the listeners array. The next time `eventName` is triggered, this + * listener is removed, and then invoked. + * + * ```js + * server.prependOnceListener('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependOnceListener(eventName: Key, listener: Listener1): this; + /** + * Returns an array listing the events for which the emitter has registered + * listeners. The values in the array are strings or `Symbol`s. + * + * ```js + * import { EventEmitter } from 'node:events'; + * + * const myEE = new EventEmitter(); + * myEE.on('foo', () => {}); + * myEE.on('bar', () => {}); + * + * const sym = Symbol('symbol'); + * myEE.on(sym, () => {}); + * + * console.log(myEE.eventNames()); + * // Prints: [ 'foo', 'bar', Symbol(symbol) ] + * ``` + * @since v6.0.0 + */ + eventNames(): Array<(string | symbol) & Key2>; + } + } + } + export = EventEmitter; +} +declare module "node:events" { + import events = require("events"); + export = events; +} diff --git a/node_modules/@types/node/fs.d.ts b/node_modules/@types/node/fs.d.ts new file mode 100644 index 0000000..d40515b --- /dev/null +++ b/node_modules/@types/node/fs.d.ts @@ -0,0 +1,4461 @@ +/** + * The `node:fs` module enables interacting with the file system in a + * way modeled on standard POSIX functions. + * + * To use the promise-based APIs: + * + * ```js + * import * as fs from 'node:fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from 'node:fs'; + * ``` + * + * All file system operations have synchronous, callback, and promise-based + * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/fs.js) + */ +declare module "fs" { + import { NonSharedBuffer } from "node:buffer"; + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import { URL } from "node:url"; + import * as promises from "node:fs/promises"; + export { promises }; + /** + * Valid types for path values in "fs". + */ + export type PathLike = string | Buffer | URL; + export type PathOrFileDescriptor = PathLike | number; + export type TimeLike = string | number | Date; + export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + export type BufferEncodingOption = + | "buffer" + | { + encoding: "buffer"; + }; + export interface ObjectEncodingOptions { + encoding?: BufferEncoding | null | undefined; + } + export type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; + export type OpenMode = number | string; + export type Mode = number | string; + export interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + export interface Stats extends StatsBase {} + /** + * A `fs.Stats` object provides information about a file. + * + * Objects returned from {@link stat}, {@link lstat}, {@link fstat}, and + * their synchronous counterparts are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`, and the object will contain additional + * nanosecond-precision properties suffixed with `Ns`. `Stat` objects are not to be created directly using the `new` keyword. + * + * ```console + * Stats { + * dev: 2114, + * ino: 48064969, + * mode: 33188, + * nlink: 1, + * uid: 85, + * gid: 100, + * rdev: 0, + * size: 527, + * blksize: 4096, + * blocks: 8, + * atimeMs: 1318289051000.1, + * mtimeMs: 1318289051000.1, + * ctimeMs: 1318289051000.1, + * birthtimeMs: 1318289051000.1, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * + * `bigint` version: + * + * ```console + * BigIntStats { + * dev: 2114n, + * ino: 48064969n, + * mode: 33188n, + * nlink: 1n, + * uid: 85n, + * gid: 100n, + * rdev: 0n, + * size: 527n, + * blksize: 4096n, + * blocks: 8n, + * atimeMs: 1318289051000n, + * mtimeMs: 1318289051000n, + * ctimeMs: 1318289051000n, + * birthtimeMs: 1318289051000n, + * atimeNs: 1318289051000000000n, + * mtimeNs: 1318289051000000000n, + * ctimeNs: 1318289051000000000n, + * birthtimeNs: 1318289051000000000n, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * @since v0.1.21 + */ + export class Stats { + private constructor(); + } + export interface StatsFsBase { + /** Type of file system. */ + type: T; + /** Optimal transfer block size. */ + bsize: T; + /** Total data blocks in file system. */ + blocks: T; + /** Free blocks in file system. */ + bfree: T; + /** Available blocks for unprivileged users */ + bavail: T; + /** Total file nodes in file system. */ + files: T; + /** Free file nodes in file system. */ + ffree: T; + } + export interface StatsFs extends StatsFsBase {} + /** + * Provides information about a mounted file system. + * + * Objects returned from {@link statfs} and its synchronous counterpart are of + * this type. If `bigint` in the `options` passed to those methods is `true`, the + * numeric values will be `bigint` instead of `number`. + * + * ```console + * StatFs { + * type: 1397114950, + * bsize: 4096, + * blocks: 121938943, + * bfree: 61058895, + * bavail: 61058895, + * files: 999, + * ffree: 1000000 + * } + * ``` + * + * `bigint` version: + * + * ```console + * StatFs { + * type: 1397114950n, + * bsize: 4096n, + * blocks: 121938943n, + * bfree: 61058895n, + * bavail: 61058895n, + * files: 999n, + * ffree: 1000000n + * } + * ``` + * @since v19.6.0, v18.15.0 + */ + export class StatsFs {} + export interface BigIntStatsFs extends StatsFsBase {} + export interface StatFsOptions { + bigint?: boolean | undefined; + } + /** + * A representation of a directory entry, which can be a file or a subdirectory + * within the directory, as returned by reading from an `fs.Dir`. The + * directory entry is a combination of the file name and file type pairs. + * + * Additionally, when {@link readdir} or {@link readdirSync} is called with + * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s. + * @since v10.10.0 + */ + export class Dirent { + /** + * Returns `true` if the `fs.Dirent` object describes a regular file. + * @since v10.10.0 + */ + isFile(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a file system + * directory. + * @since v10.10.0 + */ + isDirectory(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a block device. + * @since v10.10.0 + */ + isBlockDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a character device. + * @since v10.10.0 + */ + isCharacterDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a symbolic link. + * @since v10.10.0 + */ + isSymbolicLink(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a first-in-first-out + * (FIFO) pipe. + * @since v10.10.0 + */ + isFIFO(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a socket. + * @since v10.10.0 + */ + isSocket(): boolean; + /** + * The file name that this `fs.Dirent` object refers to. The type of this + * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. + * @since v10.10.0 + */ + name: Name; + /** + * The path to the parent directory of the file this `fs.Dirent` object refers to. + * @since v20.12.0, v18.20.0 + */ + parentPath: string; + /** + * Alias for `dirent.parentPath`. + * @since v20.1.0 + * @deprecated Since v20.12.0 + */ + path: string; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + */ + export class Dir implements AsyncIterable { + /** + * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or `fsPromises.opendir()`. + * @since v12.12.0 + */ + readonly path: string; + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * + * A promise is returned that will be fulfilled after the resource has been + * closed. + * @since v12.12.0 + */ + close(): Promise; + close(cb: NoParamCallback): void; + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * @since v12.12.0 + */ + closeSync(): void; + /** + * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. + * + * A promise is returned that will be fulfilled with an `fs.Dirent`, or `null` if there are no more directory entries to read. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + * @return containing {fs.Dirent|null} + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + /** + * Synchronously read the next directory entry as an `fs.Dirent`. See the + * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail. + * + * If there are no more directory entries to read, `null` will be returned. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + */ + readSync(): Dirent | null; + /** + * Calls `dir.close()` if the directory handle is open, and returns a promise that + * fulfills when disposal is complete. + * @since v22.17.0 + * @experimental + */ + [Symbol.asyncDispose](): Promise; + /** + * Calls `dir.closeSync()` if the directory handle is open, and returns + * `undefined`. + * @since v22.17.0 + * @experimental + */ + [Symbol.dispose](): void; + } + /** + * Class: fs.StatWatcher + * @since v14.3.0, v12.20.0 + * Extends `EventEmitter` + * A successful call to {@link watchFile} method will return a new fs.StatWatcher object. + */ + export interface StatWatcher extends EventEmitter { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.StatWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.StatWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.StatWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.StatWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + } + export interface FSWatcher extends EventEmitter { + /** + * Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the `fs.FSWatcher` object is no longer usable. + * @since v0.5.8 + */ + close(): void; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.FSWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.FSWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.FSWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.FSWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + /** + * events.EventEmitter + * 1. change + * 2. close + * 3. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "change", listener: (eventType: string, filename: string | NonSharedBuffer) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "change", listener: (eventType: string, filename: string | NonSharedBuffer) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "change", listener: (eventType: string, filename: string | NonSharedBuffer) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener( + event: "change", + listener: (eventType: string, filename: string | NonSharedBuffer) => void, + ): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "change", + listener: (eventType: string, filename: string | NonSharedBuffer) => void, + ): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + } + /** + * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. + * @since v0.1.93 + */ + export class ReadStream extends stream.Readable { + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes that have been read so far. + * @since v6.4.0 + */ + bytesRead: number; + /** + * The path to the file the stream is reading from as specified in the first + * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a + * `Buffer`. If `fd` is specified, then`readStream.path` will be `undefined`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0, v10.16.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: K, listener: ReadStreamEvents[K]): this; + on(event: K, listener: ReadStreamEvents[K]): this; + once(event: K, listener: ReadStreamEvents[K]): this; + prependListener(event: K, listener: ReadStreamEvents[K]): this; + prependOnceListener(event: K, listener: ReadStreamEvents[K]): this; + } + + /** + * The Keys are events of the ReadStream and the values are the functions that are called when the event is emitted. + */ + type ReadStreamEvents = { + close: () => void; + data: (chunk: Buffer | string) => void; + end: () => void; + error: (err: Error) => void; + open: (fd: number) => void; + pause: () => void; + readable: () => void; + ready: () => void; + resume: () => void; + } & CustomEvents; + + /** + * string & {} allows to allow any kind of strings for the event + * but still allows to have auto completion for the normal events. + */ + type CustomEvents = { [Key in string & {} | symbol]: (...args: any[]) => void }; + + /** + * The Keys are events of the WriteStream and the values are the functions that are called when the event is emitted. + */ + type WriteStreamEvents = { + close: () => void; + drain: () => void; + error: (err: Error) => void; + finish: () => void; + open: (fd: number) => void; + pipe: (src: stream.Readable) => void; + ready: () => void; + unpipe: (src: stream.Readable) => void; + } & CustomEvents; + /** + * * Extends `stream.Writable` + * + * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. + * @since v0.1.93 + */ + export class WriteStream extends stream.Writable { + /** + * Closes `writeStream`. Optionally accepts a + * callback that will be executed once the `writeStream`is closed. + * @since v0.9.4 + */ + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes written so far. Does not include data that is still queued + * for writing. + * @since v0.4.7 + */ + bytesWritten: number; + /** + * The path to the file the stream is writing to as specified in the first + * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a + * `Buffer`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: K, listener: WriteStreamEvents[K]): this; + on(event: K, listener: WriteStreamEvents[K]): this; + once(event: K, listener: WriteStreamEvents[K]): this; + prependListener(event: K, listener: WriteStreamEvents[K]): this; + prependOnceListener(event: K, listener: WriteStreamEvents[K]): this; + } + /** + * Asynchronously rename file at `oldPath` to the pathname provided + * as `newPath`. In the case that `newPath` already exists, it will + * be overwritten. If there is a directory at `newPath`, an error will + * be raised instead. No arguments other than a possible exception are + * given to the completion callback. + * + * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). + * + * ```js + * import { rename } from 'node:fs'; + * + * rename('oldFile.txt', 'newFile.txt', (err) => { + * if (err) throw err; + * console.log('Rename complete!'); + * }); + * ``` + * @since v0.0.2 + */ + export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + /** + * Renames the file from `oldPath` to `newPath`. Returns `undefined`. + * + * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. + * @since v0.1.21 + */ + export function renameSync(oldPath: PathLike, newPath: PathLike): void; + /** + * Truncates the file. No arguments other than a possible exception are + * given to the completion callback. A file descriptor can also be passed as the + * first argument. In this case, `fs.ftruncate()` is called. + * + * ```js + * import { truncate } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * truncate('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was truncated'); + * }); + * ``` + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * + * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. + * @since v0.8.6 + * @param [len=0] + */ + export function truncate(path: PathLike, len: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function truncate(path: PathLike, callback: NoParamCallback): void; + export namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number): Promise; + } + /** + * Truncates the file. Returns `undefined`. A file descriptor can also be + * passed as the first argument. In this case, `fs.ftruncateSync()` is called. + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * @since v0.8.6 + * @param [len=0] + */ + export function truncateSync(path: PathLike, len?: number): void; + /** + * Truncates the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. + * + * If the file referred to by the file descriptor was larger than `len` bytes, only + * the first `len` bytes will be retained in the file. + * + * For example, the following program retains only the first four bytes of the + * file: + * + * ```js + * import { open, close, ftruncate } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('temp.txt', 'r+', (err, fd) => { + * if (err) throw err; + * + * try { + * ftruncate(fd, 4, (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * if (err) throw err; + * } + * }); + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncate(fd: number, len: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + export function ftruncate(fd: number, callback: NoParamCallback): void; + export namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number): Promise; + } + /** + * Truncates the file descriptor. Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link ftruncate}. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncateSync(fd: number, len?: number): void; + /** + * Asynchronously changes owner and group of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Synchronously changes owner and group of a file. Returns `undefined`. + * This is the synchronous version of {@link chown}. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chownSync(path: PathLike, uid: number, gid: number): void; + /** + * Sets the owner of the file. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + export namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + /** + * Sets the owner of the file. Returns `undefined`. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function fchownSync(fd: number, uid: number, gid: number): void; + /** + * Set the owner of the symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. + */ + export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Set the owner for the path. Returns `undefined`. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function lchownSync(path: PathLike, uid: number, gid: number): void; + /** + * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic + * link, then the link is not dereferenced: instead, the timestamps of the + * symbolic link itself are changed. + * + * No arguments other than a possible exception are given to the completion + * callback. + * @since v14.5.0, v12.19.0 + */ + export function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace lutimes { + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, + * with the difference that if the path refers to a symbolic link, then the link is not + * dereferenced: instead, the timestamps of the symbolic link itself are changed. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Change the file system timestamps of the symbolic link referenced by `path`. + * Returns `undefined`, or throws an exception when parameters are incorrect or + * the operation fails. This is the synchronous version of {@link lutimes}. + * @since v14.5.0, v12.19.0 + */ + export function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Asynchronously changes the permissions of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * + * ```js + * import { chmod } from 'node:fs'; + * + * chmod('my_file.txt', 0o775, (err) => { + * if (err) throw err; + * console.log('The permissions for file "my_file.txt" have been changed!'); + * }); + * ``` + * @since v0.1.30 + */ + export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + export namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link chmod}. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * @since v0.6.7 + */ + export function chmodSync(path: PathLike, mode: Mode): void; + /** + * Sets the permissions on the file. No arguments other than a possible exception + * are given to the completion callback. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; + export namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: Mode): Promise; + } + /** + * Sets the permissions on the file. Returns `undefined`. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmodSync(fd: number, mode: Mode): void; + /** + * Changes the permissions on a symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + /** @deprecated */ + export namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * Changes the permissions on a symbolic link. Returns `undefined`. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmodSync(path: PathLike, mode: Mode): void; + /** + * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * + * {@link stat} follows symbolic links. Use {@link lstat} to look at the + * links themselves. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. + * Instead, user code should open/read/write the file directly and handle the + * error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, {@link access} is recommended. + * + * For example, given the following directory structure: + * + * ```text + * - txtDir + * -- file.txt + * - app.js + * ``` + * + * The next program will check for the stats of the given paths: + * + * ```js + * import { stat } from 'node:fs'; + * + * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; + * + * for (let i = 0; i < pathsToCheck.length; i++) { + * stat(pathsToCheck[i], (err, stats) => { + * console.log(stats.isDirectory()); + * console.log(stats); + * }); + * } + * ``` + * + * The resulting output will resemble: + * + * ```console + * true + * Stats { + * dev: 16777220, + * mode: 16877, + * nlink: 3, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214262, + * size: 96, + * blocks: 0, + * atimeMs: 1561174653071.963, + * mtimeMs: 1561174614583.3518, + * ctimeMs: 1561174626623.5366, + * birthtimeMs: 1561174126937.2893, + * atime: 2019-06-22T03:37:33.072Z, + * mtime: 2019-06-22T03:36:54.583Z, + * ctime: 2019-06-22T03:37:06.624Z, + * birthtime: 2019-06-22T03:28:46.937Z + * } + * false + * Stats { + * dev: 16777220, + * mode: 33188, + * nlink: 1, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214074, + * size: 8, + * blocks: 8, + * atimeMs: 1561174616618.8555, + * mtimeMs: 1561174614584, + * ctimeMs: 1561174614583.8145, + * birthtimeMs: 1561174007710.7478, + * atime: 2019-06-22T03:36:56.619Z, + * mtime: 2019-06-22T03:36:54.584Z, + * ctime: 2019-06-22T03:36:54.584Z, + * birthtime: 2019-06-22T03:26:47.711Z + * } + * ``` + * @since v0.0.2 + */ + export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function stat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + export interface StatSyncFn extends Function { + (path: PathLike, options?: undefined): Stats; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + }, + ): Stats | undefined; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry: false; + }, + ): BigIntStats | undefined; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + }, + ): Stats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + }, + ): BigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: boolean; + throwIfNoEntry?: false | undefined; + }, + ): Stats | BigIntStats; + (path: PathLike, options?: StatSyncOptions): Stats | BigIntStats | undefined; + } + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const statSync: StatSyncFn; + /** + * Invokes the callback with the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function fstat( + fd: number, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function fstat( + fd: number, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function fstat( + fd: number, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(fd: number, options?: StatOptions): Promise; + } + /** + * Retrieves the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstatSync( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Stats; + export function fstatSync( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): BigIntStats; + export function fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats; + /** + * Retrieves the `fs.Stats` for the symbolic link referred to by the path. + * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic + * link, then the link itself is stat-ed, not the file that it refers to. + * + * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. + * @since v0.1.30 + */ + export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function lstat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function lstat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function lstat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + /** + * Asynchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. The callback gets two arguments `(err, stats)` where `stats`is an `fs.StatFs` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfs(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void): void; + export function statfs( + path: PathLike, + options: + | (StatFsOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void, + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStatsFs) => void, + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs | BigIntStatsFs) => void, + ): void; + export namespace statfs { + /** + * Asynchronous statfs(2) - Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. + * @param path A path to an existing file or directory on the file system to be queried. + */ + function __promisify__( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatFsOptions): Promise; + } + /** + * Synchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfsSync( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): StatsFs; + export function statfsSync( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): BigIntStatsFs; + export function statfsSync(path: PathLike, options?: StatFsOptions): StatsFs | BigIntStatsFs; + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const lstatSync: StatSyncFn; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than + * a possible + * exception are given to the completion callback. + * @since v0.1.31 + */ + export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.31 + */ + export function linkSync(existingPath: PathLike, newPath: PathLike): void; + /** + * Creates the link called `path` pointing to `target`. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. + * + * The `type` argument is only available on Windows and ignored on other platforms. + * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is + * not a string, Node.js will autodetect `target` type and use `'file'` or `'dir'`. + * If the `target` does not exist, `'file'` will be used. Windows junction points + * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. Junction + * points on NTFS volumes can only point to directories. + * + * Relative targets are relative to the link's parent directory. + * + * ```js + * import { symlink } from 'node:fs'; + * + * symlink('./mew', './mewtwo', callback); + * ``` + * + * The above example creates a symbolic link `mewtwo` which points to `mew` in the + * same directory: + * + * ```bash + * $ tree . + * . + * ├── mew + * └── mewtwo -> ./mew + * ``` + * @since v0.1.31 + * @param [type='null'] + */ + export function symlink( + target: PathLike, + path: PathLike, + type: symlink.Type | undefined | null, + callback: NoParamCallback, + ): void; + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + export namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + type Type = "dir" | "file" | "junction"; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link symlink}. + * @since v0.1.31 + * @param [type='null'] + */ + export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + /** + * Reads the contents of the symbolic link referred to by `path`. The callback gets + * two arguments `(err, linkString)`. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path passed to the callback. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: NonSharedBuffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readlink( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + export namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + } + /** + * Returns the symbolic link's string value. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options: BufferEncodingOption): NonSharedBuffer; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string | NonSharedBuffer; + /** + * Asynchronously computes the canonical pathname by resolving `.`, `..`, and + * symbolic links. + * + * A canonical pathname is not necessarily unique. Hard links and bind mounts can + * expose a file system entity through many pathnames. + * + * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: + * + * 1. No case conversion is performed on case-insensitive file systems. + * 2. The maximum number of symbolic links is platform-independent and generally + * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. + * + * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd` to resolve relative paths. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * If `path` resolves to a socket or a pipe, the function will return a system + * dependent name for that object. + * @since v0.1.31 + */ + export function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: NonSharedBuffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function realpath( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + export namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). + * + * The `callback` gets two arguments `(err, resolvedPath)`. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v9.2.0 + */ + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + function native( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: NonSharedBuffer) => void, + ): void; + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | NonSharedBuffer) => void, + ): void; + function native( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + } + /** + * Returns the resolved pathname. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link realpath}. + * @since v0.1.31 + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options: BufferEncodingOption): NonSharedBuffer; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string | NonSharedBuffer; + export namespace realpathSync { + function native(path: PathLike, options?: EncodingOption): string; + function native(path: PathLike, options: BufferEncodingOption): NonSharedBuffer; + function native(path: PathLike, options?: EncodingOption): string | NonSharedBuffer; + } + /** + * Asynchronously removes a file or symbolic link. No arguments other than a + * possible exception are given to the completion callback. + * + * ```js + * import { unlink } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * unlink('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was deleted'); + * }); + * ``` + * + * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a + * directory, use {@link rmdir}. + * + * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. + * @since v0.0.2 + */ + export function unlink(path: PathLike, callback: NoParamCallback): void; + export namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. + * @since v0.1.21 + */ + export function unlinkSync(path: PathLike): void; + export interface RmDirOptions { + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning + * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file. + * Use `fs.rm(path, { recursive: true, force: true })` instead. + * + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given + * to the completion callback. + * + * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on + * Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. + * @since v0.0.2 + */ + export function rmdir(path: PathLike, callback: NoParamCallback): void; + export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void; + export namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: RmDirOptions): Promise; + } + /** + * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. + * + * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error + * on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. + * @since v0.1.21 + */ + export function rmdirSync(path: PathLike, options?: RmDirOptions): void; + export interface RmOptions { + /** + * When `true`, exceptions will be ignored if `path` does not exist. + * @default false + */ + force?: boolean | undefined; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). No arguments other than a possible exception are given to the + * completion callback. + * @since v14.14.0 + */ + export function rm(path: PathLike, callback: NoParamCallback): void; + export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; + export namespace rm { + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + function __promisify__(path: PathLike, options?: RmOptions): Promise; + } + /** + * Synchronously removes files and directories (modeled on the standard POSIX `rm` utility). Returns `undefined`. + * @since v14.14.0 + */ + export function rmSync(path: PathLike, options?: RmOptions): void; + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean | undefined; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode | undefined; + } + /** + * Asynchronously creates a directory. + * + * The callback is given a possible exception and, if `recursive` is `true`, the + * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was + * created (for instance, if it was previously created). + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fs.mkdir()` when `path` is a directory that + * exists results in an error only + * when `recursive` is false. If `recursive` is false and the directory exists, + * an `EEXIST` error occurs. + * + * ```js + * import { mkdir } from 'node:fs'; + * + * // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist. + * mkdir('./tmp/a/apple', { recursive: true }, (err) => { + * if (err) throw err; + * }); + * ``` + * + * On Windows, using `fs.mkdir()` on the root directory even with recursion will + * result in an error: + * + * ```js + * import { mkdir } from 'node:fs'; + * + * mkdir('/', { recursive: true }, (err) => { + * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] + * }); + * ``` + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.8 + */ + export function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + | undefined, + callback: NoParamCallback, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: Mode | MakeDirectoryOptions | null | undefined, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function mkdir(path: PathLike, callback: NoParamCallback): void; + export namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: Mode | MakeDirectoryOptions | null, + ): Promise; + } + /** + * Synchronously creates a directory. Returns `undefined`, or if `recursive` is `true`, the first directory path created. + * This is the synchronous version of {@link mkdir}. + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.21 + */ + export function mkdirSync( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): string | undefined; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): void; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. Due to platform + * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, + * notably the BSDs, can return more than six random characters, and replace + * trailing `X` characters in `prefix` with random characters. + * + * The created directory path is passed as a string to the callback's second + * parameter. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 + * }); + * ``` + * + * The `fs.mkdtemp()` method will append the six randomly selected characters + * directly to the `prefix` string. For instance, given a directory `/tmp`, if the + * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator + * (`import { sep } from 'node:path'`). + * + * ```js + * import { tmpdir } from 'node:os'; + * import { mkdtemp } from 'node:fs'; + * + * // The parent directory for the new temporary directory + * const tmpDir = tmpdir(); + * + * // This method is *INCORRECT*: + * mkdtemp(tmpDir, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmpabc123`. + * // A new temporary directory is created at the file system root + * // rather than *within* the /tmp directory. + * }); + * + * // This method is *CORRECT*: + * import { sep } from 'node:path'; + * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmp/abc123`. + * // A new temporary directory is created within + * // the /tmp directory. + * }); + * ``` + * @since v5.10.0 + */ + export function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: NonSharedBuffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + export function mkdtemp( + prefix: string, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + export namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + } + /** + * Returns the created directory path. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link mkdtemp}. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v5.10.0 + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options: BufferEncodingOption): NonSharedBuffer; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string | NonSharedBuffer; + /** + * Reads the contents of a directory. The callback gets two arguments `(err, files)` where `files` is an array of the names of the files in the directory excluding `'.'` and `'..'`. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames passed to the callback. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects. + * @since v0.1.8 + */ + export function readdir( + path: PathLike, + options: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + callback: (err: NodeJS.ErrnoException | null, files: NonSharedBuffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | NonSharedBuffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readdir( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + export function readdir( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, + ): void; + export namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options: + | "buffer" + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + function __promisify__( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise[]>; + } + /** + * Reads the contents of the directory. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames returned. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects. + * @since v0.1.21 + */ + export function readdirSync( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): string[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): NonSharedBuffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): string[] | NonSharedBuffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdirSync( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + export function readdirSync( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + /** + * Closes the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.0.2 + */ + export function close(fd: number, callback?: NoParamCallback): void; + export namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Closes the file descriptor. Returns `undefined`. + * + * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.1.21 + */ + export function closeSync(fd: number): void; + /** + * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was + * created. On Windows, only the write permission can be manipulated; see {@link chmod}. + * + * The callback gets two arguments `(err, fd)`. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * + * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. + * @since v0.0.2 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] + */ + export function open( + path: PathLike, + flags: OpenMode | undefined, + mode: Mode | undefined | null, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param [flags='r'] See `support of file system `flags``. + */ + export function open( + path: PathLike, + flags: OpenMode | undefined, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + export namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; + } + /** + * Returns an integer representing the file descriptor. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link open}. + * @since v0.1.21 + * @param [flags='r'] + * @param [mode=0o666] + */ + export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time in seconds, `Date`s, or a numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. + * @since v0.4.2 + */ + export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link utimes}. + * @since v0.4.2 + */ + export function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Change the file system timestamps of the object referenced by the supplied file + * descriptor. See {@link utimes}. + * @since v0.4.2 + */ + export function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Synchronous version of {@link futimes}. Returns `undefined`. + * @since v0.4.2 + */ + export function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other + * than a possible exception are given to the completion callback. + * @since v0.1.96 + */ + export function fsync(fd: number, callback: NoParamCallback): void; + export namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.96 + */ + export function fsyncSync(fd: number): void; + export interface WriteOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `buffer.byteLength - offset` + */ + length?: number | undefined; + /** + * @default null + */ + position?: number | null | undefined; + } + /** + * Write `buffer` to the file specified by `fd`. + * + * `offset` determines the part of the buffer to be written, and `length` is + * an integer specifying the number of bytes to write. + * + * `position` refers to the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + * + * The callback will be given three arguments `(err, bytesWritten, buffer)` where `bytesWritten` specifies how many _bytes_ were written from `buffer`. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesWritten` and `buffer` properties. + * + * It is unsafe to use `fs.write()` multiple times on the same file without waiting + * for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v0.0.2 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + export function write( + fd: number, + buffer: TBuffer, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param options An object with the following properties: + * * `offset` The part of the buffer to be written. If not supplied, defaults to `0`. + * * `length` The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * * `position` The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write( + fd: number, + buffer: TBuffer, + options: WriteOptions, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + encoding: BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + */ + export function write( + fd: number, + string: string, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + export namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param options An object with the following properties: + * * `offset` The part of the buffer to be written. If not supplied, defaults to `0`. + * * `length` The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * * `position` The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + options?: WriteOptions, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link write}. + * @since v0.1.21 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + * @return The number of bytes written. + */ + export function writeSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset?: number | null, + length?: number | null, + position?: number | null, + ): number; + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function writeSync( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): number; + export type ReadPosition = number | bigint; + export interface ReadOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `length of buffer` + */ + length?: number | undefined; + /** + * @default null + */ + position?: ReadPosition | null | undefined; + } + export interface ReadOptionsWithBuffer extends ReadOptions { + buffer?: T | undefined; + } + /** @deprecated Use `ReadOptions` instead. */ + // TODO: remove in future major + export interface ReadSyncOptions extends ReadOptions {} + /** @deprecated Use `ReadOptionsWithBuffer` instead. */ + // TODO: remove in future major + export interface ReadAsyncOptions extends ReadOptionsWithBuffer {} + /** + * Read data from the file specified by `fd`. + * + * The callback is given the three arguments, `(err, bytesRead, buffer)`. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffer` properties. + * @since v0.0.2 + * @param buffer The buffer that the data will be written to. + * @param offset The position in `buffer` to write the data to. + * @param length The number of bytes to read. + * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If + * `position` is an integer, the file position will be unchanged. + */ + export function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + /** + * Similar to the above `fs.read` function, this version takes an optional `options` object. + * If not otherwise specified in an `options` object, + * `buffer` defaults to `Buffer.alloc(16384)`, + * `offset` defaults to `0`, + * `length` defaults to `buffer.byteLength`, `- offset` as of Node 17.6.0 + * `position` defaults to `null` + * @since v12.17.0, 13.11.0 + */ + export function read( + fd: number, + options: ReadOptionsWithBuffer, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + buffer: TBuffer, + options: ReadOptions, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + buffer: TBuffer, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NonSharedBuffer) => void, + ): void; + export namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__( + fd: number, + options: ReadOptionsWithBuffer, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__(fd: number): Promise<{ + bytesRead: number; + buffer: NonSharedBuffer; + }>; + } + /** + * Returns the number of `bytesRead`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link read}. + * @since v0.1.21 + * @param [position='null'] + */ + export function readSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset: number, + length: number, + position: ReadPosition | null, + ): number; + /** + * Similar to the above `fs.readSync` function, this version takes an optional `options` object. + * If no `options` object is specified, it will default with the above values. + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadOptions): number; + /** + * Asynchronously reads the entire contents of a file. + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', (err, data) => { + * if (err) throw err; + * console.log(data); + * }); + * ``` + * + * The callback is passed two arguments `(err, data)`, where `data` is the + * contents of the file. + * + * If no encoding is specified, then the raw buffer is returned. + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', 'utf8', callback); + * ``` + * + * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an + * error will be returned. On FreeBSD, a representation of the directory's contents + * will be returned. + * + * ```js + * import { readFile } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFile('', (err, data) => { + * // => [Error: EISDIR: illegal operation on a directory, read ] + * }); + * + * // FreeBSD + * readFile('', (err, data) => { + * // => null, + * }); + * ``` + * + * It is possible to abort an ongoing request using an `AbortSignal`. If a + * request is aborted the callback is called with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs'; + * + * const controller = new AbortController(); + * const signal = controller.signal; + * readFile(fileInfo[0].name, { signal }, (err, buf) => { + * // ... + * }); + * // When you want to abort the request + * controller.abort(); + * ``` + * + * The `fs.readFile()` function buffers the entire file. To minimize memory costs, + * when possible prefer streaming via `fs.createReadStream()`. + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * @since v0.1.29 + * @param path filename or file descriptor + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: string | undefined; + } & Abortable) + | BufferEncoding, + callback: (err: NodeJS.ErrnoException | null, data: string) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | (ObjectEncodingOptions & { + flag?: string | undefined; + } & Abortable) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + export function readFile( + path: PathOrFileDescriptor, + callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void, + ): void; + export namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): Promise; + } + /** + * Returns the contents of the `path`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readFile}. + * + * If the `encoding` option is specified then this function returns a + * string. Otherwise it returns a buffer. + * + * Similar to {@link readFile}, when the path is a directory, the behavior of `fs.readFileSync()` is platform-specific. + * + * ```js + * import { readFileSync } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFileSync(''); + * // => [Error: EISDIR: illegal operation on a directory, read ] + * + * // FreeBSD + * readFileSync(''); // => + * ``` + * @since v0.1.8 + * @param path filename or file descriptor + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): NonSharedBuffer; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): string; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): string | NonSharedBuffer; + export type WriteFileOptions = + | ( + & ObjectEncodingOptions + & Abortable + & { + mode?: Mode | undefined; + flag?: string | undefined; + flush?: boolean | undefined; + } + ) + | BufferEncoding + | null; + /** + * When `file` is a filename, asynchronously writes data to the file, replacing the + * file if it already exists. `data` can be a string or a buffer. + * + * When `file` is a file descriptor, the behavior is similar to calling `fs.write()` directly (which is recommended). See the notes below on using + * a file descriptor. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, (err) => { + * if (err) throw err; + * console.log('The file has been saved!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { writeFile } from 'node:fs'; + * + * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); + * ``` + * + * It is unsafe to use `fs.writeFile()` multiple times on the same file without + * waiting for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that + * performs multiple `write` calls internally to write the buffer passed to it. + * For performance sensitive code consider using {@link createWriteStream}. + * + * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, { signal }, (err) => { + * // When a request is aborted - the callback is called with an AbortError + * }); + * // When the request should be aborted + * controller.abort(); + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFile( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function writeFile( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + callback: NoParamCallback, + ): void; + export namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): Promise; + } + /** + * Returns `undefined`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writeFile}. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFileSync( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', (err) => { + * if (err) throw err; + * console.log('The "data to append" was appended to file!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', 'utf8', callback); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { open, close, appendFile } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('message.txt', 'a', (err, fd) => { + * if (err) throw err; + * + * try { + * appendFile(fd, 'data to append', 'utf8', (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * throw err; + * } + * }); + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFile( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void; + export namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__( + file: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): Promise; + } + /** + * Synchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * try { + * appendFileSync('message.txt', 'data to append'); + * console.log('The "data to append" was appended to file!'); + * } catch (err) { + * // Handle the error + * } + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * appendFileSync('message.txt', 'data to append', 'utf8'); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { openSync, closeSync, appendFileSync } from 'node:fs'; + * + * let fd; + * + * try { + * fd = openSync('message.txt', 'a'); + * appendFileSync(fd, 'data to append', 'utf8'); + * } catch (err) { + * // Handle the error + * } finally { + * if (fd !== undefined) + * closeSync(fd); + * } + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFileSync( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): void; + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'node:fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export interface WatchFileOptions { + bigint?: boolean | undefined; + persistent?: boolean | undefined; + interval?: number | undefined; + } + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'node:fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint?: false | undefined; + }) + | undefined, + listener: StatsListener, + ): StatWatcher; + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint: true; + }) + | undefined, + listener: BigIntStatsListener, + ): StatWatcher; + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watchFile(filename: PathLike, listener: StatsListener): StatWatcher; + /** + * Stop watching for changes on `filename`. If `listener` is specified, only that + * particular listener is removed. Otherwise, _all_ listeners are removed, + * effectively stopping watching of `filename`. + * + * Calling `fs.unwatchFile()` with a filename that is not being watched is a + * no-op, not an error. + * + * Using {@link watch} is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` when possible. + * @since v0.1.31 + * @param listener Optional, a listener previously attached using `fs.watchFile()` + */ + export function unwatchFile(filename: PathLike, listener?: StatsListener): void; + export function unwatchFile(filename: PathLike, listener?: BigIntStatsListener): void; + export interface WatchOptions extends Abortable { + encoding?: BufferEncoding | "buffer" | undefined; + persistent?: boolean | undefined; + recursive?: boolean | undefined; + } + export interface WatchOptionsWithBufferEncoding extends WatchOptions { + encoding: "buffer"; + } + export interface WatchOptionsWithStringEncoding extends WatchOptions { + encoding?: BufferEncoding | undefined; + } + export type WatchEventType = "rename" | "change"; + export type WatchListener = (event: WatchEventType, filename: T | null) => void; + export type StatsListener = (curr: Stats, prev: Stats) => void; + export type BigIntStatsListener = (curr: BigIntStats, prev: BigIntStats) => void; + /** + * Watch for changes on `filename`, where `filename` is either a file or a + * directory. + * + * The second argument is optional. If `options` is provided as a string, it + * specifies the `encoding`. Otherwise `options` should be passed as an object. + * + * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file + * which triggered the event. + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of `eventType`. + * + * If a `signal` is passed, aborting the corresponding AbortController will close + * the returned `fs.FSWatcher`. + * @since v0.5.10 + * @param listener + */ + export function watch( + filename: PathLike, + options?: WatchOptionsWithStringEncoding | BufferEncoding | null, + listener?: WatchListener, + ): FSWatcher; + export function watch( + filename: PathLike, + options: WatchOptionsWithBufferEncoding | "buffer", + listener: WatchListener, + ): FSWatcher; + export function watch( + filename: PathLike, + options: WatchOptions | BufferEncoding | "buffer" | null, + listener: WatchListener, + ): FSWatcher; + export function watch(filename: PathLike, listener: WatchListener): FSWatcher; + /** + * Test whether or not the given path exists by checking with the file system. + * Then call the `callback` argument with either true or false: + * + * ```js + * import { exists } from 'node:fs'; + * + * exists('/etc/passwd', (e) => { + * console.log(e ? 'it exists' : 'no passwd!'); + * }); + * ``` + * + * **The parameters for this callback are not consistent with other Node.js** + * **callbacks.** Normally, the first parameter to a Node.js callback is an `err` parameter, optionally followed by other parameters. The `fs.exists()` callback + * has only one boolean parameter. This is one reason `fs.access()` is recommended + * instead of `fs.exists()`. + * + * Using `fs.exists()` to check for the existence of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file does not exist. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { exists, open, close } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * console.error('myfile already exists'); + * } else { + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { open, close, exists } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } else { + * console.error('myfile does not exist'); + * } + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for existence and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the existence of a file only if the file won't be + * used directly, for example when its existence is a signal from another + * process. + * @since v0.0.2 + * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead. + */ + export function exists(path: PathLike, callback: (exists: boolean) => void): void; + /** @deprecated */ + export namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Returns `true` if the path exists, `false` otherwise. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link exists}. + * + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback` parameter to `fs.exists()` accepts parameters that are inconsistent with other + * Node.js callbacks. `fs.existsSync()` does not use a callback. + * + * ```js + * import { existsSync } from 'node:fs'; + * + * if (existsSync('/etc/passwd')) + * console.log('The path exists.'); + * ``` + * @since v0.1.21 + */ + export function existsSync(path: PathLike): boolean; + export namespace constants { + // File Access Constants + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + // File Copy Constants + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + // File Open Constants + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + // File Type Constants + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + // File Mode Constants + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * The final argument, `callback`, is a callback function that is invoked with + * a possible error argument. If any of the accessibility checks fail, the error + * argument will be an `Error` object. The following examples check if `package.json` exists, and if it is readable or writable. + * + * ```js + * import { access, constants } from 'node:fs'; + * + * const file = 'package.json'; + * + * // Check if the file exists in the current directory. + * access(file, constants.F_OK, (err) => { + * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); + * }); + * + * // Check if the file is readable. + * access(file, constants.R_OK, (err) => { + * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); + * }); + * + * // Check if the file is writable. + * access(file, constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); + * }); + * + * // Check if the file is readable and writable. + * access(file, constants.R_OK | constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); + * }); + * ``` + * + * Do not use `fs.access()` to check for the accessibility of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file is not accessible. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * + * access('myfile', (err) => { + * if (!err) { + * console.error('myfile already exists'); + * return; + * } + * + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * access('myfile', (err) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for accessibility and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the accessibility of a file only if the file will not be + * used directly, for example when its accessibility is a signal from another + * process. + * + * On Windows, access-control policies (ACLs) on a directory may limit access to + * a file or directory. The `fs.access()` function, however, does not check the + * ACL and therefore may report that a path is accessible even if the ACL restricts + * the user from reading or writing to it. + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function access(path: PathLike, callback: NoParamCallback): void; + export namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + /** + * Synchronously tests a user's permissions for the file or directory specified + * by `path`. The `mode` argument is an optional integer that specifies the + * accessibility checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and + * `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, + * the method will return `undefined`. + * + * ```js + * import { accessSync, constants } from 'node:fs'; + * + * try { + * accessSync('etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can read/write'); + * } catch (err) { + * console.error('no access!'); + * } + * ``` + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function accessSync(path: PathLike, mode?: number): void; + interface StreamOptions { + flags?: string | undefined; + encoding?: BufferEncoding | undefined; + fd?: number | promises.FileHandle | undefined; + mode?: number | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + signal?: AbortSignal | null | undefined; + highWaterMark?: number | undefined; + } + interface FSImplementation { + open?: (...args: any[]) => any; + close?: (...args: any[]) => any; + } + interface CreateReadStreamFSImplementation extends FSImplementation { + read: (...args: any[]) => any; + } + interface CreateWriteStreamFSImplementation extends FSImplementation { + write: (...args: any[]) => any; + writev?: (...args: any[]) => any; + } + interface ReadStreamOptions extends StreamOptions { + fs?: CreateReadStreamFSImplementation | null | undefined; + end?: number | undefined; + } + interface WriteStreamOptions extends StreamOptions { + fs?: CreateWriteStreamFSImplementation | null | undefined; + flush?: boolean | undefined; + } + /** + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is + * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the + * current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use + * the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. + * + * If `fd` points to a character device that only supports blocking reads + * (such as keyboard or sound card), read operations do not finish until data is + * available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option, it is possible to override the corresponding `fs` implementations for `open`, `read`, and `close`. When providing the `fs` option, + * an override for `read` is required. If no `fd` is provided, an override for `open` is also required. If `autoClose` is `true`, an override for `close` is + * also required. + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * // Create a stream from some character device. + * const stream = createReadStream('/dev/input/event0'); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * `mode` sets the file mode (permission and sticky bits), but only if the + * file was created. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * createReadStream('sample.txt', { start: 90, end: 99 }); + * ``` + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` option to be set to `r+` rather than the + * default `w`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option it is possible to override the corresponding `fs` implementations for `open`, `write`, `writev`, and `close`. Overriding `write()` without `writev()` can reduce + * performance as some optimizations (`_writev()`) + * will be disabled. When providing the `fs` option, overrides for at least one of `write` and `writev` are required. If no `fd` option is supplied, an override + * for `open` is also required. If `autoClose` is `true`, an override for `close` is also required. + * + * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the `path` argument and will use the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s + * should be passed to `net.Socket`. + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createWriteStream(path: PathLike, options?: BufferEncoding | WriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other + * than a possible + * exception are given to the completion callback. + * @since v0.1.96 + */ + export function fdatasync(fd: number, callback: NoParamCallback): void; + export namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`. + * @since v0.1.96 + */ + export function fdatasyncSync(fd: number): void; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. No arguments other than a possible exception are given to the + * callback function. Node.js makes no guarantees about the atomicity of the copy + * operation. If an error occurs after the destination file has been opened for + * writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFile, constants } from 'node:fs'; + * + * function callback(err) { + * if (err) throw err; + * console.log('source.txt was copied to destination.txt'); + * } + * + * // destination.txt will be created or overwritten by default. + * copyFile('source.txt', 'destination.txt', callback); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + export function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void; + export namespace copyFile { + function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise; + } + /** + * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. Returns `undefined`. Node.js makes no guarantees about the + * atomicity of the copy operation. If an error occurs after the destination file + * has been opened for writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFileSync, constants } from 'node:fs'; + * + * // destination.txt will be created or overwritten by default. + * copyFileSync('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; + /** + * Write an array of `ArrayBufferView`s to the file specified by `fd` using `writev()`. + * + * `position` is the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. + * + * The callback will be given three arguments: `err`, `bytesWritten`, and `buffers`. `bytesWritten` is how many bytes were written from `buffers`. + * + * If this method is `util.promisify()` ed, it returns a promise for an `Object` with `bytesWritten` and `buffers` properties. + * + * It is unsafe to use `fs.writev()` multiple times on the same file without + * waiting for the callback. For this scenario, use {@link createWriteStream}. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] + */ + export function writev( + fd: number, + buffers: TBuffers, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: TBuffers) => void, + ): void; + export function writev( + fd: number, + buffers: TBuffers, + position: number | null, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: TBuffers) => void, + ): void; + // Providing a default type parameter doesn't provide true BC for userland consumers, but at least suppresses TS2314 + // TODO: remove default in future major version + export interface WriteVResult { + bytesWritten: number; + buffers: T; + } + export namespace writev { + function __promisify__( + fd: number, + buffers: TBuffers, + position?: number, + ): Promise>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writev}. + * @since v12.9.0 + * @param [position='null'] + * @return The number of bytes written. + */ + export function writevSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + /** + * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s + * using `readv()`. + * + * `position` is the offset from the beginning of the file from where data + * should be read. If `typeof position !== 'number'`, the data will be read + * from the current position. + * + * The callback will be given three arguments: `err`, `bytesRead`, and `buffers`. `bytesRead` is how many bytes were read from the file. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffers` properties. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + */ + export function readv( + fd: number, + buffers: TBuffers, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: TBuffers) => void, + ): void; + export function readv( + fd: number, + buffers: TBuffers, + position: number | null, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: TBuffers) => void, + ): void; + // Providing a default type parameter doesn't provide true BC for userland consumers, but at least suppresses TS2314 + // TODO: remove default in future major version + export interface ReadVResult { + bytesRead: number; + buffers: T; + } + export namespace readv { + function __promisify__( + fd: number, + buffers: TBuffers, + position?: number, + ): Promise>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readv}. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + * @return The number of bytes read. + */ + export function readvSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + + export interface OpenAsBlobOptions { + /** + * An optional mime type for the blob. + * + * @default 'undefined' + */ + type?: string | undefined; + } + + /** + * Returns a `Blob` whose data is backed by the given file. + * + * The file must not be modified after the `Blob` is created. Any modifications + * will cause reading the `Blob` data to fail with a `DOMException` error. + * Synchronous stat operations on the file when the `Blob` is created, and before + * each read in order to detect whether the file data has been modified on disk. + * + * ```js + * import { openAsBlob } from 'node:fs'; + * + * const blob = await openAsBlob('the.file.txt'); + * const ab = await blob.arrayBuffer(); + * blob.stream(); + * ``` + * @since v19.8.0 + */ + export function openAsBlob(path: PathLike, options?: OpenAsBlobOptions): Promise; + + export interface OpenDirOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number | undefined; + /** + * @default false + */ + recursive?: boolean | undefined; + } + /** + * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendirSync(path: PathLike, options?: OpenDirOptions): Dir; + /** + * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for + * more details. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendir(path: PathLike, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export function opendir( + path: PathLike, + options: OpenDirOptions, + cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void, + ): void; + export namespace opendir { + function __promisify__(path: PathLike, options?: OpenDirOptions): Promise; + } + export interface BigIntStats extends StatsBase { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; + } + export interface BigIntOptions { + bigint: true; + } + export interface StatOptions { + bigint?: boolean | undefined; + } + export interface StatSyncOptions extends StatOptions { + throwIfNoEntry?: boolean | undefined; + } + interface CopyOptionsBase { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean | undefined; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: boolean | undefined; + /** + * Overwrite existing file or directory. _The copy + * operation will ignore errors if you set this to false and the destination + * exists. Use the `errorOnExist` option to change this behavior. + * @default true + */ + force?: boolean | undefined; + /** + * Modifiers for copy operation. See `mode` flag of {@link copyFileSync()} + */ + mode?: number | undefined; + /** + * When `true` timestamps from `src` will + * be preserved. + * @default false + */ + preserveTimestamps?: boolean | undefined; + /** + * Copy directories recursively. + * @default false + */ + recursive?: boolean | undefined; + /** + * When true, path resolution for symlinks will be skipped + * @default false + */ + verbatimSymlinks?: boolean | undefined; + } + export interface CopyOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?: ((source: string, destination: string) => boolean | Promise) | undefined; + } + export interface CopySyncOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?: ((source: string, destination: string) => boolean) | undefined; + } + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cp( + source: string | URL, + destination: string | URL, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + export function cp( + source: string | URL, + destination: string | URL, + opts: CopyOptions, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + /** + * Synchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void; + + interface _GlobOptions { + /** + * Current working directory. + * @default process.cwd() + */ + cwd?: string | URL | undefined; + /** + * `true` if the glob should return paths as `Dirent`s, `false` otherwise. + * @default false + * @since v22.2.0 + */ + withFileTypes?: boolean | undefined; + /** + * Function to filter out files/directories or a + * list of glob patterns to be excluded. If a function is provided, return + * `true` to exclude the item, `false` to include it. + * @default undefined + */ + exclude?: ((fileName: T) => boolean) | readonly string[] | undefined; + } + export interface GlobOptions extends _GlobOptions {} + export interface GlobOptionsWithFileTypes extends _GlobOptions { + withFileTypes: true; + } + export interface GlobOptionsWithoutFileTypes extends _GlobOptions { + withFileTypes?: false | undefined; + } + + /** + * Retrieves the files matching the specified pattern. + * + * ```js + * import { glob } from 'node:fs'; + * + * glob('*.js', (err, matches) => { + * if (err) throw err; + * console.log(matches); + * }); + * ``` + * @since v22.0.0 + */ + export function glob( + pattern: string | readonly string[], + callback: (err: NodeJS.ErrnoException | null, matches: string[]) => void, + ): void; + export function glob( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + callback: ( + err: NodeJS.ErrnoException | null, + matches: Dirent[], + ) => void, + ): void; + export function glob( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + callback: ( + err: NodeJS.ErrnoException | null, + matches: string[], + ) => void, + ): void; + export function glob( + pattern: string | readonly string[], + options: GlobOptions, + callback: ( + err: NodeJS.ErrnoException | null, + matches: Dirent[] | string[], + ) => void, + ): void; + /** + * ```js + * import { globSync } from 'node:fs'; + * + * console.log(globSync('*.js')); + * ``` + * @since v22.0.0 + * @returns paths of files that match the pattern. + */ + export function globSync(pattern: string | readonly string[]): string[]; + export function globSync( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + ): Dirent[]; + export function globSync( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + ): string[]; + export function globSync( + pattern: string | readonly string[], + options: GlobOptions, + ): Dirent[] | string[]; +} +declare module "node:fs" { + export * from "fs"; +} diff --git a/node_modules/@types/node/fs/promises.d.ts b/node_modules/@types/node/fs/promises.d.ts new file mode 100644 index 0000000..051ddba --- /dev/null +++ b/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,1295 @@ +/** + * The `fs/promises` API provides asynchronous file system methods that return + * promises. + * + * The promise APIs use the underlying Node.js threadpool to perform file + * system operations off the event loop thread. These operations are not + * synchronized or threadsafe. Care must be taken when performing multiple + * concurrent modifications on the same file or data corruption may occur. + * @since v10.0.0 + */ +declare module "fs/promises" { + import { NonSharedBuffer } from "node:buffer"; + import { Abortable } from "node:events"; + import { Stream } from "node:stream"; + import { ReadableStream } from "node:stream/web"; + import { + BigIntStats, + BigIntStatsFs, + BufferEncodingOption, + constants as fsConstants, + CopyOptions, + Dir, + Dirent, + GlobOptions, + GlobOptionsWithFileTypes, + GlobOptionsWithoutFileTypes, + MakeDirectoryOptions, + Mode, + ObjectEncodingOptions, + OpenDirOptions, + OpenMode, + PathLike, + ReadOptions, + ReadOptionsWithBuffer, + ReadPosition, + ReadStream, + ReadVResult, + RmDirOptions, + RmOptions, + StatFsOptions, + StatOptions, + Stats, + StatsFs, + TimeLike, + WatchEventType, + WatchOptions as _WatchOptions, + WriteStream, + WriteVResult, + } from "node:fs"; + import { Interface as ReadlineInterface } from "node:readline"; + interface FileChangeInfo { + eventType: WatchEventType; + filename: T | null; + } + interface FlagAndOpenMode { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } + interface FileReadResult { + bytesRead: number; + buffer: T; + } + /** @deprecated This interface will be removed in a future version. Use `import { ReadOptionsWithBuffer } from "node:fs"` instead. */ + interface FileReadOptions { + /** + * @default `Buffer.alloc(0xffff)` + */ + buffer?: T; + /** + * @default 0 + */ + offset?: number | null; + /** + * @default `buffer.byteLength` + */ + length?: number | null; + position?: ReadPosition | null; + } + interface CreateReadStreamOptions extends Abortable { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + end?: number | undefined; + highWaterMark?: number | undefined; + } + interface CreateWriteStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + highWaterMark?: number | undefined; + flush?: boolean | undefined; + } + interface ReadableWebStreamOptions { + autoClose?: boolean | undefined; + } + // TODO: Add `EventEmitter` close + interface FileHandle { + /** + * The numeric file descriptor managed by the {FileHandle} object. + * @since v10.0.0 + */ + readonly fd: number; + /** + * Alias of `filehandle.writeFile()`. + * + * When operating on file handles, the mode cannot be changed from what it was set + * to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + appendFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html). + * @since v10.0.0 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + * @return Fulfills with `undefined` upon success. + */ + chown(uid: number, gid: number): Promise; + /** + * Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html). + * @since v10.0.0 + * @param mode the file mode bit mask. + * @return Fulfills with `undefined` upon success. + */ + chmod(mode: Mode): Promise; + /** + * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 KiB. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `start` is + * omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from + * the current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If the `FileHandle` points to a character device that only supports blocking + * reads (such as keyboard or sound card), read operations do not finish until data + * is available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('/dev/input/event0'); + * // Create a stream from some character device. + * const stream = fd.createReadStream(); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('sample.txt'); + * fd.createReadStream({ start: 90, end: 99 }); + * ``` + * @since v16.11.0 + */ + createReadStream(options?: CreateReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` `open` option to be set to `r+` rather than + * the default `r`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * @since v16.11.0 + */ + createWriteStream(options?: CreateWriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. + * + * Unlike `filehandle.sync` this method does not flush modified metadata. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + datasync(): Promise; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + sync(): Promise; + /** + * Reads data from the file and stores that in the given buffer. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * @since v10.0.0 + * @param buffer A buffer that will be filled with the file data read. + * @param offset The location in the buffer at which to start filling. + * @param length The number of bytes to read. + * @param position The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an + * integer, the current file position will remain unchanged. + * @return Fulfills upon success with an object with two properties: + */ + read( + buffer: T, + offset?: number | null, + length?: number | null, + position?: ReadPosition | null, + ): Promise>; + read( + buffer: T, + options?: ReadOptions, + ): Promise>; + read( + options?: ReadOptionsWithBuffer, + ): Promise>; + /** + * Returns a byte-oriented `ReadableStream` that may be used to read the file's + * contents. + * + * An error will be thrown if this method is called more than once or is called + * after the `FileHandle` is closed or closing. + * + * ```js + * import { + * open, + * } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const chunk of file.readableWebStream()) + * console.log(chunk); + * + * await file.close(); + * ``` + * + * While the `ReadableStream` will read the file to completion, it will not + * close the `FileHandle` automatically. User code must still call the`fileHandle.close()` method. + * @since v17.0.0 + */ + readableWebStream(options?: ReadableWebStreamOptions): ReadableStream; + /** + * Asynchronously reads the entire contents of a file. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support reading. + * + * If one or more `filehandle.read()` calls are made on a file handle and then a `filehandle.readFile()` call is made, the data will be read from the current + * position till the end of the file. It doesn't always read from the beginning + * of the file. + * @since v10.0.0 + * @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the + * data will be a string. + */ + readFile( + options?: + | ({ encoding?: null | undefined } & Abortable) + | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + */ + readFile( + options: + | ({ encoding: BufferEncoding } & Abortable) + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + */ + readFile( + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Convenience method to create a `readline` interface and stream over the file. + * See `filehandle.createReadStream()` for the options. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const line of file.readLines()) { + * console.log(line); + * } + * ``` + * @since v18.11.0 + */ + readLines(options?: CreateReadStreamOptions): ReadlineInterface; + /** + * @since v10.0.0 + * @return Fulfills with an {fs.Stats} for the file. + */ + stat( + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + stat( + opts: StatOptions & { + bigint: true; + }, + ): Promise; + stat(opts?: StatOptions): Promise; + /** + * Truncates the file. + * + * If the file was larger than `len` bytes, only the first `len` bytes will be + * retained in the file. + * + * The following example retains only the first four bytes of the file: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle = null; + * try { + * filehandle = await open('temp.txt', 'r+'); + * await filehandle.truncate(4); + * } finally { + * await filehandle?.close(); + * } + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + truncate(len?: number): Promise; + /** + * Change the file system timestamps of the object referenced by the `FileHandle` then fulfills the promise with no arguments upon success. + * @since v10.0.0 + */ + utimes(atime: TimeLike, mtime: TimeLike): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * The promise is fulfilled with no arguments upon success. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support writing. + * + * It is unsafe to use `filehandle.writeFile()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). + * + * If one or more `filehandle.write()` calls are made on a file handle and then a`filehandle.writeFile()` call is made, the data will be written from the + * current position till the end of the file. It doesn't always write from the + * beginning of the file. + * @since v10.0.0 + */ + writeFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Write `buffer` to the file. + * + * The promise is fulfilled with an object containing two properties: + * + * It is unsafe to use `filehandle.write()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). For this + * scenario, use `filehandle.createWriteStream()`. + * + * On Linux, positional writes do not work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v10.0.0 + * @param offset The start position from within `buffer` where the data to write begins. + * @param [length=buffer.byteLength - offset] The number of bytes from `buffer` to write. + * @param [position='null'] The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current + * position. See the POSIX pwrite(2) documentation for more detail. + */ + write( + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + buffer: TBuffer, + options?: { offset?: number; length?: number; position?: number }, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + data: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + /** + * Write an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s to the file. + * + * The promise is fulfilled with an object containing a two properties: + * + * It is unsafe to call `writev()` multiple times on the same file without waiting + * for the promise to be fulfilled (or rejected). + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current + * position. + */ + writev( + buffers: TBuffers, + position?: number, + ): Promise>; + /** + * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s + * @since v13.13.0, v12.17.0 + * @param [position='null'] The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. + * @return Fulfills upon success an object containing two properties: + */ + readv( + buffers: TBuffers, + position?: number, + ): Promise>; + /** + * Closes the file handle after waiting for any pending operation on the handle to + * complete. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle; + * try { + * filehandle = await open('thefile.txt', 'r'); + * } finally { + * await filehandle?.close(); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + close(): Promise; + /** + * Calls `filehandle.close()` and returns a promise that fulfills when the + * filehandle is closed. + * @since v20.4.0 + */ + [Symbol.asyncDispose](): Promise; + } + const constants: typeof fsConstants; + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If the accessibility check is successful, the promise is fulfilled with no + * value. If any of the accessibility checks fail, the promise is rejected + * with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and + * written by the current process. + * + * ```js + * import { access, constants } from 'node:fs/promises'; + * + * try { + * await access('/etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can access'); + * } catch { + * console.error('cannot access'); + * } + * ``` + * + * Using `fsPromises.access()` to check for the accessibility of a file before + * calling `fsPromises.open()` is not recommended. Doing so introduces a race + * condition, since other processes may change the file's state between the two + * calls. Instead, user code should open/read/write the file directly and handle + * the error raised if the file is not accessible. + * @since v10.0.0 + * @param [mode=fs.constants.F_OK] + * @return Fulfills with `undefined` upon success. + */ + function access(path: PathLike, mode?: number): Promise; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. + * + * No guarantees are made about the atomicity of the copy operation. If an + * error occurs after the destination file has been opened for writing, an attempt + * will be made to remove the destination. + * + * ```js + * import { copyFile, constants } from 'node:fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * try { + * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * ``` + * @since v10.0.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. + * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`) + * @return Fulfills with `undefined` upon success. + */ + function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise; + /** + * Opens a `FileHandle`. + * + * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * @since v10.0.0 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created. + * @return Fulfills with a {FileHandle} object. + */ + function open(path: PathLike, flags?: string | number, mode?: Mode): Promise; + /** + * Renames `oldPath` to `newPath`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + /** + * Truncates (shortens or extends the length) of the content at `path` to `len` bytes. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + function truncate(path: PathLike, len?: number): Promise; + /** + * Removes the directory identified by `path`. + * + * Using `fsPromises.rmdir()` on a file (not a directory) results in the + * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rmdir(path: PathLike, options?: RmDirOptions): Promise; + /** + * Removes files and directories (modeled on the standard POSIX `rm` utility). + * @since v14.14.0 + * @return Fulfills with `undefined` upon success. + */ + function rm(path: PathLike, options?: RmOptions): Promise; + /** + * Asynchronously creates a directory. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fsPromises.mkdir()` when `path` is a directory + * that exists results in a + * rejection only when `recursive` is false. + * + * ```js + * import { mkdir } from 'node:fs/promises'; + * + * try { + * const projectFolder = new URL('./test/project/', import.meta.url); + * const createDir = await mkdir(projectFolder, { recursive: true }); + * + * console.log(`created ${createDir}`); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * @since v10.0.0 + * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + /** + * Reads the contents of a directory. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned + * will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the returned array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from 'node:fs/promises'; + * + * try { + * const files = await readdir(path); + * for (const file of files) + * console.log(file); + * } catch (err) { + * console.error(err); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a directory. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + function readdir( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise[]>; + /** + * Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is + * fulfilled with the`linkString` upon success. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, the link path + * returned will be passed as a `Buffer` object. + * @since v10.0.0 + * @return Fulfills with the `linkString` upon success. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink( + path: PathLike, + options?: ObjectEncodingOptions | string | null, + ): Promise; + /** + * Creates a symbolic link. + * + * The `type` argument is only used on Windows platforms and can be one of `'dir'`, `'file'`, or `'junction'`. If the `type` argument is not a string, Node.js will + * autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not + * exist, `'file'` will be used. Windows junction points require the destination + * path to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. Junction points on NTFS volumes + * can only point to directories. + * @since v10.0.0 + * @param [type='null'] + * @return Fulfills with `undefined` upon success. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + /** + * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, + * in which case the link itself is stat-ed, not the file that it refers to. + * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail. + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. + */ + function lstat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function lstat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function lstat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given `path`. + */ + function stat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function stat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function stat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v19.6.0, v18.15.0 + * @return Fulfills with the {fs.StatFs} object for the given `path`. + */ + function statfs( + path: PathLike, + opts?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function statfs( + path: PathLike, + opts: StatFsOptions & { + bigint: true; + }, + ): Promise; + function statfs(path: PathLike, opts?: StatFsOptions): Promise; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + /** + * If `path` refers to a symbolic link, then the link is removed without affecting + * the file or directory to which that link refers. If the `path` refers to a file + * path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function unlink(path: PathLike): Promise; + /** + * Changes the permissions of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the permissions on a symbolic link. + * + * This method is only implemented on macOS. + * @deprecated Since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the ownership on a symbolic link. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a + * symbolic link, then the link is not dereferenced: instead, the timestamps of + * the symbolic link itself are changed. + * @since v14.5.0, v12.19.0 + * @return Fulfills with `undefined` upon success. + */ + function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Changes the ownership of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time, `Date`s, or a + * numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Determines the actual location of `path` using the same semantics as the `fs.realpath.native()` function. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path. If the `encoding` is set to `'buffer'`, the path returned will be + * passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v10.0.0 + * @return Fulfills with the resolved path upon success. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath( + path: PathLike, + options?: ObjectEncodingOptions | BufferEncoding | null, + ): Promise; + /** + * Creates a unique temporary directory. A unique directory name is generated by + * appending six random characters to the end of the provided `prefix`. Due to + * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some + * platforms, notably the BSDs, can return more than six random characters, and + * replace trailing `X` characters in `prefix` with random characters. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs/promises'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * try { + * await mkdtemp(join(tmpdir(), 'foo-')); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * The `fsPromises.mkdtemp()` method will append the six randomly selected + * characters directly to the `prefix` string. For instance, given a directory `/tmp`, if the intention is to create a temporary directory _within_ `/tmp`, the `prefix` must end with a trailing + * platform-specific path separator + * (`import { sep } from 'node:path'`). + * @since v10.0.0 + * @return Fulfills with a string containing the file system path of the newly created temporary directory. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp( + prefix: string, + options?: ObjectEncodingOptions | BufferEncoding | null, + ): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * If `options` is a string, then it specifies the encoding. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * Any specified `FileHandle` has to support writing. + * + * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file + * without waiting for the promise to be settled. + * + * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience + * method that performs multiple `write` calls internally to write the buffer + * passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`. + * + * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs/promises'; + * import { Buffer } from 'node:buffer'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * const promise = writeFile('message.txt', data, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v10.0.0 + * @param file filename or `FileHandle` + * @return Fulfills with `undefined` upon success. + */ + function writeFile( + file: PathLike | FileHandle, + data: + | string + | NodeJS.ArrayBufferView + | Iterable + | AsyncIterable + | Stream, + options?: + | (ObjectEncodingOptions & { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + /** + * If all data is successfully written to the file, and `flush` + * is `true`, `filehandle.sync()` is used to flush the data. + * @default false + */ + flush?: boolean | undefined; + } & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * The `path` may be specified as a `FileHandle` that has been opened + * for appending (using `fsPromises.open()`). + * @since v10.0.0 + * @param path filename or {FileHandle} + * @return Fulfills with `undefined` upon success. + */ + function appendFile( + path: PathLike | FileHandle, + data: string | Uint8Array, + options?: (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined }) | BufferEncoding | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * + * If no encoding is specified (using `options.encoding`), the data is returned + * as a `Buffer` object. Otherwise, the data will be a string. + * + * If `options` is a string, then it specifies the encoding. + * + * When the `path` is a directory, the behavior of `fsPromises.readFile()` is + * platform-specific. On macOS, Linux, and Windows, the promise will be rejected + * with an error. On FreeBSD, a representation of the directory's contents will be + * returned. + * + * An example of reading a `package.json` file located in the same directory of the + * running code: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * try { + * const filePath = new URL('./package.json', import.meta.url); + * const contents = await readFile(filePath, { encoding: 'utf8' }); + * console.log(contents); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * + * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a + * request is aborted the promise returned is rejected with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const promise = readFile(fileName, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * + * Any specified `FileHandle` has to support reading. + * @since v10.0.0 + * @param path filename or `FileHandle` + * @return Fulfills with the contents of the file. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ({ + encoding?: null | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options: + | ({ + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ( + & ObjectEncodingOptions + & Abortable + & { + flag?: OpenMode | undefined; + } + ) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * + * Example using async iteration: + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + * @return Fulfills with an {fs.Dir}. + */ + function opendir(path: PathLike, options?: OpenDirOptions): Promise; + interface WatchOptions extends _WatchOptions { + maxQueue?: number | undefined; + overflow?: "ignore" | "throw" | undefined; + } + interface WatchOptionsWithBufferEncoding extends WatchOptions { + encoding: "buffer"; + } + interface WatchOptionsWithStringEncoding extends WatchOptions { + encoding?: BufferEncoding | undefined; + } + /** + * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. + * + * ```js + * import { watch } from 'node:fs/promises'; + * + * const ac = new AbortController(); + * const { signal } = ac; + * setTimeout(() => ac.abort(), 10000); + * + * (async () => { + * try { + * const watcher = watch(__filename, { signal }); + * for await (const event of watcher) + * console.log(event); + * } catch (err) { + * if (err.name === 'AbortError') + * return; + * throw err; + * } + * })(); + * ``` + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. + * @since v15.9.0, v14.18.0 + * @return of objects with the properties: + */ + function watch( + filename: PathLike, + options?: WatchOptionsWithStringEncoding | BufferEncoding, + ): NodeJS.AsyncIterator>; + function watch( + filename: PathLike, + options: WatchOptionsWithBufferEncoding | "buffer", + ): NodeJS.AsyncIterator>; + function watch( + filename: PathLike, + options: WatchOptions | BufferEncoding | "buffer", + ): NodeJS.AsyncIterator>; + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + * @return Fulfills with `undefined` upon success. + */ + function cp(source: string | URL, destination: string | URL, opts?: CopyOptions): Promise; + /** + * ```js + * import { glob } from 'node:fs/promises'; + * + * for await (const entry of glob('*.js')) + * console.log(entry); + * ``` + * @since v22.0.0 + * @returns An AsyncIterator that yields the paths of files + * that match the pattern. + */ + function glob(pattern: string | readonly string[]): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + ): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + ): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptions, + ): NodeJS.AsyncIterator; +} +declare module "node:fs/promises" { + export * from "fs/promises"; +} diff --git a/node_modules/@types/node/globals.d.ts b/node_modules/@types/node/globals.d.ts new file mode 100644 index 0000000..8358597 --- /dev/null +++ b/node_modules/@types/node/globals.d.ts @@ -0,0 +1,172 @@ +declare var global: typeof globalThis; + +declare var process: NodeJS.Process; +declare var console: Console; + +interface ErrorConstructor { + /** + * Creates a `.stack` property on `targetObject`, which when accessed returns + * a string representing the location in the code at which + * `Error.captureStackTrace()` was called. + * + * ```js + * const myObject = {}; + * Error.captureStackTrace(myObject); + * myObject.stack; // Similar to `new Error().stack` + * ``` + * + * The first line of the trace will be prefixed with + * `${myObject.name}: ${myObject.message}`. + * + * The optional `constructorOpt` argument accepts a function. If given, all frames + * above `constructorOpt`, including `constructorOpt`, will be omitted from the + * generated stack trace. + * + * The `constructorOpt` argument is useful for hiding implementation + * details of error generation from the user. For instance: + * + * ```js + * function a() { + * b(); + * } + * + * function b() { + * c(); + * } + * + * function c() { + * // Create an error without stack trace to avoid calculating the stack trace twice. + * const { stackTraceLimit } = Error; + * Error.stackTraceLimit = 0; + * const error = new Error(); + * Error.stackTraceLimit = stackTraceLimit; + * + * // Capture the stack trace above function b + * Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace + * throw error; + * } + * + * a(); + * ``` + */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + /** + * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces + */ + prepareStackTrace(err: Error, stackTraces: NodeJS.CallSite[]): any; + /** + * The `Error.stackTraceLimit` property specifies the number of stack frames + * collected by a stack trace (whether generated by `new Error().stack` or + * `Error.captureStackTrace(obj)`). + * + * The default value is `10` but may be set to any valid JavaScript number. Changes + * will affect any stack trace captured _after_ the value has been changed. + * + * If set to a non-number value, or set to a negative number, stack traces will + * not capture any frames. + */ + stackTraceLimit: number; +} + +/** + * Enable this API with the `--expose-gc` CLI flag. + */ +declare var gc: NodeJS.GCFunction | undefined; + +declare namespace NodeJS { + interface CallSite { + getColumnNumber(): number | null; + getEnclosingColumnNumber(): number | null; + getEnclosingLineNumber(): number | null; + getEvalOrigin(): string | undefined; + getFileName(): string | null; + getFunction(): Function | undefined; + getFunctionName(): string | null; + getLineNumber(): number | null; + getMethodName(): string | null; + getPosition(): number; + getPromiseIndex(): number | null; + getScriptHash(): string; + getScriptNameOrSourceURL(): string | null; + getThis(): unknown; + getTypeName(): string | null; + isAsync(): boolean; + isConstructor(): boolean; + isEval(): boolean; + isNative(): boolean; + isPromiseAll(): boolean; + isToplevel(): boolean; + } + + interface ErrnoException extends Error { + errno?: number | undefined; + code?: string | undefined; + path?: string | undefined; + syscall?: string | undefined; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: BufferEncoding): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean | undefined }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): this; + end(data: string | Uint8Array, cb?: () => void): this; + end(str: string, encoding?: BufferEncoding, cb?: () => void): this; + } + + interface ReadWriteStream extends ReadableStream, WritableStream {} + + interface RefCounted { + ref(): this; + unref(): this; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } + + type PartialOptions = { [K in keyof T]?: T[K] | undefined }; + + interface GCFunction { + (minor?: boolean): void; + (options: NodeJS.GCOptions & { execution: "async" }): Promise; + (options: NodeJS.GCOptions): void; + } + + interface GCOptions { + execution?: "sync" | "async" | undefined; + flavor?: "regular" | "last-resort" | undefined; + type?: "major-snapshot" | "major" | "minor" | undefined; + filename?: string | undefined; + } + + /** An iterable iterator returned by the Node.js API. */ + // Default TReturn/TNext in v22 is `any`, for compatibility with the previously-used IterableIterator. + interface Iterator extends IteratorObject { + [Symbol.iterator](): NodeJS.Iterator; + } + + /** An async iterable iterator returned by the Node.js API. */ + // Default TReturn/TNext in v22 is `any`, for compatibility with the previously-used AsyncIterableIterator. + interface AsyncIterator extends AsyncIteratorObject { + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + } +} diff --git a/node_modules/@types/node/globals.typedarray.d.ts b/node_modules/@types/node/globals.typedarray.d.ts new file mode 100644 index 0000000..8eafc3b --- /dev/null +++ b/node_modules/@types/node/globals.typedarray.d.ts @@ -0,0 +1,38 @@ +export {}; // Make this a module + +declare global { + namespace NodeJS { + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float32Array + | Float64Array; + type ArrayBufferView = + | TypedArray + | DataView; + + // The following aliases are required to allow use of non-shared ArrayBufferViews in @types/node + // while maintaining compatibility with TS <=5.6. + type NonSharedUint8Array = Uint8Array; + type NonSharedUint8ClampedArray = Uint8ClampedArray; + type NonSharedUint16Array = Uint16Array; + type NonSharedUint32Array = Uint32Array; + type NonSharedInt8Array = Int8Array; + type NonSharedInt16Array = Int16Array; + type NonSharedInt32Array = Int32Array; + type NonSharedBigUint64Array = BigUint64Array; + type NonSharedBigInt64Array = BigInt64Array; + type NonSharedFloat32Array = Float32Array; + type NonSharedFloat64Array = Float64Array; + type NonSharedDataView = DataView; + type NonSharedTypedArray = TypedArray; + type NonSharedArrayBufferView = ArrayBufferView; + } +} diff --git a/node_modules/@types/node/http.d.ts b/node_modules/@types/node/http.d.ts new file mode 100644 index 0000000..af7d21c --- /dev/null +++ b/node_modules/@types/node/http.d.ts @@ -0,0 +1,2089 @@ +/** + * To use the HTTP server and client one must import the `node:http` module. + * + * The HTTP interfaces in Node.js are designed to support many features + * of the protocol which have been traditionally difficult to use. + * In particular, large, possibly chunk-encoded, messages. The interface is + * careful to never buffer entire requests or responses, so the + * user is able to stream data. + * + * HTTP message headers are represented by an object like this: + * + * ```json + * { "content-length": "123", + * "content-type": "text/plain", + * "connection": "keep-alive", + * "host": "example.com", + * "accept": "*" } + * ``` + * + * Keys are lowercased. Values are not modified. + * + * In order to support the full spectrum of possible HTTP applications, the Node.js + * HTTP API is very low-level. It deals with stream handling and message + * parsing only. It parses a message into headers and body but it does not + * parse the actual headers or the body. + * + * See `message.headers` for details on how duplicate headers are handled. + * + * The raw headers as they were received are retained in the `rawHeaders` property, which is an array of `[key, value, key2, value2, ...]`. For + * example, the previous message header object might have a `rawHeaders` list like the following: + * + * ```js + * [ 'ConTent-Length', '123456', + * 'content-LENGTH', '123', + * 'content-type', 'text/plain', + * 'CONNECTION', 'keep-alive', + * 'Host', 'example.com', + * 'accepT', '*' ] + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/http.js) + */ +declare module "http" { + import { NonSharedBuffer } from "node:buffer"; + import * as stream from "node:stream"; + import { URL } from "node:url"; + import { LookupOptions } from "node:dns"; + import { EventEmitter } from "node:events"; + import { LookupFunction, Server as NetServer, Socket, TcpSocketConnectOpts } from "node:net"; + // incoming headers will never contain number + interface IncomingHttpHeaders extends NodeJS.Dict { + accept?: string | undefined; + "accept-encoding"?: string | undefined; + "accept-language"?: string | undefined; + "accept-patch"?: string | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + "alt-svc"?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + connection?: string | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + location?: string | undefined; + origin?: string | undefined; + pragma?: string | undefined; + "proxy-authenticate"?: string | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "retry-after"?: string | undefined; + "sec-fetch-site"?: string | undefined; + "sec-fetch-mode"?: string | undefined; + "sec-fetch-user"?: string | undefined; + "sec-fetch-dest"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | undefined; + "sec-websocket-version"?: string | undefined; + "set-cookie"?: string[] | undefined; + "strict-transport-security"?: string | undefined; + tk?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + upgrade?: string | undefined; + "user-agent"?: string | undefined; + vary?: string | undefined; + via?: string | undefined; + warning?: string | undefined; + "www-authenticate"?: string | undefined; + } + // outgoing headers allows numbers (as they are converted internally to strings) + type OutgoingHttpHeader = number | string | string[]; + interface OutgoingHttpHeaders extends NodeJS.Dict { + accept?: string | string[] | undefined; + "accept-charset"?: string | string[] | undefined; + "accept-encoding"?: string | string[] | undefined; + "accept-language"?: string | string[] | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + "cdn-cache-control"?: string | undefined; + connection?: string | string[] | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | number | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-security-policy"?: string | undefined; + "content-security-policy-report-only"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | string[] | undefined; + dav?: string | string[] | undefined; + dnt?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-range"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + link?: string | string[] | undefined; + location?: string | undefined; + "max-forwards"?: string | undefined; + origin?: string | undefined; + pragma?: string | string[] | undefined; + "proxy-authenticate"?: string | string[] | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + "public-key-pins-report-only"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "referrer-policy"?: string | undefined; + refresh?: string | undefined; + "retry-after"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | string[] | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | string[] | undefined; + "sec-websocket-version"?: string | undefined; + server?: string | undefined; + "set-cookie"?: string | string[] | undefined; + "strict-transport-security"?: string | undefined; + te?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + "user-agent"?: string | undefined; + upgrade?: string | undefined; + "upgrade-insecure-requests"?: string | undefined; + vary?: string | undefined; + via?: string | string[] | undefined; + warning?: string | undefined; + "www-authenticate"?: string | string[] | undefined; + "x-content-type-options"?: string | undefined; + "x-dns-prefetch-control"?: string | undefined; + "x-frame-options"?: string | undefined; + "x-xss-protection"?: string | undefined; + } + interface ClientRequestArgs extends Pick { + _defaultAgent?: Agent | undefined; + agent?: Agent | boolean | undefined; + auth?: string | null | undefined; + createConnection?: + | (( + options: ClientRequestArgs, + oncreate: (err: Error | null, socket: stream.Duplex) => void, + ) => stream.Duplex | null | undefined) + | undefined; + defaultPort?: number | string | undefined; + family?: number | undefined; + headers?: OutgoingHttpHeaders | readonly string[] | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + insecureHTTPParser?: boolean | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + lookup?: LookupFunction | undefined; + /** + * @default 16384 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + port?: number | string | null | undefined; + protocol?: string | null | undefined; + setDefaultHeaders?: boolean | undefined; + setHost?: boolean | undefined; + signal?: AbortSignal | undefined; + socketPath?: string | undefined; + timeout?: number | undefined; + uniqueHeaders?: Array | undefined; + joinDuplicateHeaders?: boolean | undefined; + } + interface ServerOptions< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > { + /** + * Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. + */ + IncomingMessage?: Request | undefined; + /** + * Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. + */ + ServerResponse?: Response | undefined; + /** + * Sets the timeout value in milliseconds for receiving the entire request from the client. + * @see Server.requestTimeout for more information. + * @default 300000 + * @since v18.0.0 + */ + requestTimeout?: number | undefined; + /** + * It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. + * @default false + * @since v18.14.0 + */ + joinDuplicateHeaders?: boolean | undefined; + /** + * The number of milliseconds of inactivity a server needs to wait for additional incoming data, + * after it has finished writing the last response, before a socket will be destroyed. + * @see Server.keepAliveTimeout for more information. + * @default 5000 + * @since v18.0.0 + */ + keepAliveTimeout?: number | undefined; + /** + * An additional buffer time added to the + * `server.keepAliveTimeout` to extend the internal socket timeout. + * @since 22.19.0 + * @default 1000 + */ + keepAliveTimeoutBuffer?: number | undefined; + /** + * Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests. + * @default 30000 + */ + connectionsCheckingInterval?: number | undefined; + /** + * Sets the timeout value in milliseconds for receiving the complete HTTP headers from the client. + * See {@link Server.headersTimeout} for more information. + * @default 60000 + * @since 18.0.0 + */ + headersTimeout?: number | undefined; + /** + * Optionally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. + * Default: @see stream.getDefaultHighWaterMark(). + * @since v20.1.0 + */ + highWaterMark?: number | undefined; + /** + * Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. + * Using the insecure parser should be avoided. + * See --insecure-http-parser for more information. + * @default false + */ + insecureHTTPParser?: boolean | undefined; + /** + * Optionally overrides the value of `--max-http-header-size` for requests received by + * this server, i.e. the maximum length of request headers in bytes. + * @default 16384 + * @since v13.3.0 + */ + maxHeaderSize?: number | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default true + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it forces the server to respond with a 400 (Bad Request) status code + * to any HTTP/1.1 request message that lacks a Host header (as mandated by the specification). + * @default true + * @since 20.0.0 + */ + requireHostHeader?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * A list of response headers that should be sent only once. + * If the header's value is an array, the items will be joined using `; `. + */ + uniqueHeaders?: Array | undefined; + /** + * If set to `true`, an error is thrown when writing to an HTTP response which does not have a body. + * @default false + * @since v18.17.0, v20.2.0 + */ + rejectNonStandardBodyWrites?: boolean | undefined; + } + type RequestListener< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > = (req: InstanceType, res: InstanceType & { req: InstanceType }) => void; + /** + * @since v0.1.17 + */ + class Server< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > extends NetServer { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + /** + * Sets the timeout value for sockets, and emits a `'timeout'` event on + * the Server object, passing the socket as an argument, if a timeout + * occurs. + * + * If there is a `'timeout'` event listener on the Server object, then it + * will be called with the timed-out socket as an argument. + * + * By default, the Server does not timeout sockets. However, if a callback + * is assigned to the Server's `'timeout'` event, timeouts must be handled + * explicitly. + * @since v0.9.12 + * @param [msecs=0 (no timeout)] + */ + setTimeout(msecs?: number, callback?: (socket: Socket) => void): this; + setTimeout(callback: (socket: Socket) => void): this; + /** + * Limits maximum incoming headers count. If set to 0, no limit will be applied. + * @since v0.7.0 + */ + maxHeadersCount: number | null; + /** + * The maximum number of requests socket can handle + * before closing keep alive connection. + * + * A value of `0` will disable the limit. + * + * When the limit is reached it will set the `Connection` header value to `close`, + * but will not actually close the connection, subsequent requests sent + * after the limit is reached will get `503 Service Unavailable` as a response. + * @since v16.10.0 + */ + maxRequestsPerSocket: number | null; + /** + * The number of milliseconds of inactivity before a socket is presumed + * to have timed out. + * + * A value of `0` will disable the timeout behavior on incoming connections. + * + * The socket timeout logic is set up on connection, so changing this + * value only affects new connections to the server, not any existing connections. + * @since v0.9.12 + */ + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP + * headers. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v11.3.0, v10.14.0 + */ + headersTimeout: number; + /** + * The number of milliseconds of inactivity a server needs to wait for additional + * incoming data, after it has finished writing the last response, before a socket + * will be destroyed. + * + * This timeout value is combined with the + * `server.keepAliveTimeoutBuffer` option to determine the actual socket + * timeout, calculated as: + * socketTimeout = keepAliveTimeout + keepAliveTimeoutBuffer + * If the server receives new data before the keep-alive timeout has fired, it + * will reset the regular inactivity timeout, i.e., `server.timeout`. + * + * A value of `0` will disable the keep-alive timeout behavior on incoming + * connections. + * A value of `0` makes the HTTP server behave similarly to Node.js versions prior + * to 8.0.0, which did not have a keep-alive timeout. + * + * The socket timeout logic is set up on connection, so changing this value only + * affects new connections to the server, not any existing connections. + * @since v8.0.0 + */ + keepAliveTimeout: number; + /** + * An additional buffer time added to the + * `server.keepAliveTimeout` to extend the internal socket timeout. + * + * This buffer helps reduce connection reset (`ECONNRESET`) errors by increasing + * the socket timeout slightly beyond the advertised keep-alive timeout. + * + * This option applies only to new incoming connections. + * @since v22.19.0 + * @default 1000 + */ + keepAliveTimeoutBuffer: number; + /** + * Sets the timeout value in milliseconds for receiving the entire request from + * the client. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v14.11.0 + */ + requestTimeout: number; + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request + * or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: RequestListener): this; + addListener(event: "checkExpectation", listener: RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + addListener(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + addListener(event: "request", listener: RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "clientError", err: Error, socket: stream.Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer): boolean; + emit(event: "dropRequest", req: InstanceType, socket: stream.Duplex): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: RequestListener): this; + on(event: "checkExpectation", listener: RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + on( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + on(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + on(event: "request", listener: RequestListener): this; + on( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: RequestListener): this; + once(event: "checkExpectation", listener: RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + once( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + once(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + once(event: "request", listener: RequestListener): this; + once( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: RequestListener): this; + prependListener(event: "checkExpectation", listener: RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + prependListener( + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependListener(event: "request", listener: RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + prependOnceListener( + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependOnceListener(event: "request", listener: RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + } + /** + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract outgoing message from + * the perspective of the participants of an HTTP transaction. + * @since v0.1.17 + */ + class OutgoingMessage extends stream.Writable { + readonly req: Request; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + /** + * @deprecated Use `writableEnded` instead. + */ + finished: boolean; + /** + * Read-only. `true` if the headers were sent, otherwise `false`. + * @since v0.9.3 + */ + readonly headersSent: boolean; + /** + * Alias of `outgoingMessage.socket`. + * @since v0.3.0 + * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead. + */ + readonly connection: Socket | null; + /** + * Reference to the underlying socket. Usually, users will not want to access + * this property. + * + * After calling `outgoingMessage.end()`, this property will be nulled. + * @since v0.3.0 + */ + readonly socket: Socket | null; + constructor(); + /** + * Once a socket is associated with the message and is connected, `socket.setTimeout()` will be called with `msecs` as the first parameter. + * @since v0.9.12 + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * Sets a single header value. If the header already exists in the to-be-sent + * headers, its value will be replaced. Use an array of strings to send multiple + * headers with the same name. + * @since v0.4.0 + * @param name Header name + * @param value Header value + */ + setHeader(name: string, value: number | string | readonly string[]): this; + /** + * Sets multiple header values for implicit headers. headers must be an instance of + * `Headers` or `Map`, if a header already exists in the to-be-sent headers, its + * value will be replaced. + * + * ```js + * const headers = new Headers({ foo: 'bar' }); + * outgoingMessage.setHeaders(headers); + * ``` + * + * or + * + * ```js + * const headers = new Map([['foo', 'bar']]); + * outgoingMessage.setHeaders(headers); + * ``` + * + * When headers have been set with `outgoingMessage.setHeaders()`, they will be + * merged with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * const headers = new Headers({ 'Content-Type': 'text/html' }); + * res.setHeaders(headers); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * @since v19.6.0, v18.15.0 + * @param name Header name + * @param value Header value + */ + setHeaders(headers: Headers | Map): this; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple + * times. + * + * If there were no previous values for the header, this is equivalent to calling `outgoingMessage.setHeader(name, value)`. + * + * Depending of the value of `options.uniqueHeaders` when the client request or the + * server were created, this will end up in the header being sent multiple times or + * a single time with values joined using `; `. + * @since v18.3.0, v16.17.0 + * @param name Header name + * @param value Header value + */ + appendHeader(name: string, value: string | readonly string[]): this; + /** + * Gets the value of the HTTP header with the given name. If that header is not + * set, the returned value will be `undefined`. + * @since v0.4.0 + * @param name Name of header + */ + getHeader(name: string): number | string | string[] | undefined; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow + * copy is used, array values may be mutated without additional calls to + * various header-related HTTP module methods. The keys of the returned + * object are the header names and the values are the respective header + * values. All header names are lowercase. + * + * The object returned by the `outgoingMessage.getHeaders()` method does + * not prototypically inherit from the JavaScript `Object`. This means that + * typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, + * and others are not defined and will not work. + * + * ```js + * outgoingMessage.setHeader('Foo', 'bar'); + * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = outgoingMessage.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v7.7.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All names are lowercase. + * @since v7.7.0 + */ + getHeaderNames(): string[]; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name is case-insensitive. + * + * ```js + * const hasContentType = outgoingMessage.hasHeader('content-type'); + * ``` + * @since v7.7.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that is queued for implicit sending. + * + * ```js + * outgoingMessage.removeHeader('Content-Encoding'); + * ``` + * @since v0.4.0 + * @param name Header name + */ + removeHeader(name: string): void; + /** + * Adds HTTP trailers (headers but at the end of the message) to the message. + * + * Trailers will **only** be emitted if the message is chunked encoded. If not, + * the trailers will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header field names in its value, e.g. + * + * ```js + * message.writeHead(200, { 'Content-Type': 'text/plain', + * 'Trailer': 'Content-MD5' }); + * message.write(fileData); + * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); + * message.end(); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.3.0 + */ + addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + /** + * Flushes the message headers. + * + * For efficiency reason, Node.js normally buffers the message headers + * until `outgoingMessage.end()` is called or the first chunk of message data + * is written. It then tries to pack the headers and data into a single TCP + * packet. + * + * It is usually desired (it saves a TCP round-trip), but not when the first + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()` bypasses the optimization and kickstarts the message. + * @since v1.6.0 + */ + flushHeaders(): void; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v0.1.17 + */ + class ServerResponse extends OutgoingMessage { + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v0.4.0 + */ + statusCode: number; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status message that will be sent to the client when + * the headers get flushed. If this is left as `undefined` then the standard + * message for the status code will be used. + * + * ```js + * response.statusMessage = 'Not found'; + * ``` + * + * After response header was sent to the client, this property indicates the + * status message which was sent out. + * @since v0.11.8 + */ + statusMessage: string; + /** + * If set to `true`, Node.js will check whether the `Content-Length` header value and the size of the body, in bytes, are equal. + * Mismatching the `Content-Length` header value will result + * in an `Error` being thrown, identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * @since v18.10.0, v16.18.0 + */ + strictContentLength: boolean; + constructor(req: Request); + assignSocket(socket: Socket): void; + detachSocket(socket: Socket): void; + /** + * Sends an HTTP/1.1 100 Continue message to the client, indicating that + * the request body should be sent. See the `'checkContinue'` event on `Server`. + * @since v0.3.0 + */ + writeContinue(callback?: () => void): void; + /** + * Sends an HTTP/1.1 103 Early Hints message to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. The optional `callback` argument will be called when + * the response message has been written. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * 'x-trace-id': 'id for diagnostics', + * }); + * + * const earlyHintsCallback = () => console.log('early hints message sent'); + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }, earlyHintsCallback); + * ``` + * @since v18.11.0 + * @param hints An object containing the values of headers + * @param callback Will be called when the response message has been written + */ + writeEarlyHints(hints: Record, callback?: () => void): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * Optionally one can give a human-readable `statusMessage` as the second + * argument. + * + * `headers` may be an `Array` where the keys and values are in the same list. + * It is _not_ a list of tuples. So, the even-numbered offsets are key values, + * and the odd-numbered offsets are the associated values. The array is in the same + * format as `request.rawHeaders`. + * + * Returns a reference to the `ServerResponse`, so that calls can be chained. + * + * ```js + * const body = 'hello world'; + * response + * .writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain', + * }) + * .end(body); + * ``` + * + * This method must only be called once on a message and it must + * be called before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * If this method is called and `response.setHeader()` has not been called, + * it will directly write the supplied header values onto the network channel + * without caching internally, and the `response.getHeader()` on the header + * will not yield the expected result. If progressive population of headers is + * desired with potential future retrieval and modification, use `response.setHeader()` instead. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * `Content-Length` is read in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * will check whether `Content-Length` and the length of the body which has + * been transmitted are equal or not. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `Error` being thrown. + * @since v0.1.30 + */ + writeHead( + statusCode: number, + statusMessage?: string, + headers?: OutgoingHttpHeaders | OutgoingHttpHeader[], + ): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends a HTTP/1.1 102 Processing message to the client, indicating that + * the request body should be sent. + * @since v10.0.0 + */ + writeProcessing(callback?: () => void): void; + } + interface InformationEvent { + statusCode: number; + statusMessage: string; + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + } + /** + * This object is created internally and returned from {@link request}. It + * represents an _in-progress_ request whose header has already been queued. The + * header is still mutable using the `setHeader(name, value)`, `getHeader(name)`, `removeHeader(name)` API. The actual header will + * be sent along with the first data chunk or when calling `request.end()`. + * + * To get the response, add a listener for `'response'` to the request object. `'response'` will be emitted from the request object when the response + * headers have been received. The `'response'` event is executed with one + * argument which is an instance of {@link IncomingMessage}. + * + * During the `'response'` event, one can add listeners to the + * response object; particularly to listen for the `'data'` event. + * + * If no `'response'` handler is added, then the response will be + * entirely discarded. However, if a `'response'` event handler is added, + * then the data from the response object **must** be consumed, either by + * calling `response.read()` whenever there is a `'readable'` event, or + * by adding a `'data'` handler, or by calling the `.resume()` method. + * Until the data is consumed, the `'end'` event will not fire. Also, until + * the data is read it will consume memory that can eventually lead to a + * 'process out of memory' error. + * + * For backward compatibility, `res` will only emit `'error'` if there is an `'error'` listener registered. + * + * Set `Content-Length` header to limit the response body size. + * If `response.strictContentLength` is set to `true`, mismatching the `Content-Length` header value will result in an `Error` being thrown, + * identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * + * `Content-Length` value should be in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. + * @since v0.1.17 + */ + class ClientRequest extends OutgoingMessage { + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v0.11.14 + * @deprecated Since v17.0.0, v16.12.0 - Check `destroyed` instead. + */ + aborted: boolean; + /** + * The request host. + * @since v14.5.0, v12.19.0 + */ + host: string; + /** + * The request protocol. + * @since v14.5.0, v12.19.0 + */ + protocol: string; + /** + * When sending request through a keep-alive enabled agent, the underlying socket + * might be reused. But if server closes connection at unfortunate time, client + * may run into a 'ECONNRESET' error. + * + * ```js + * import http from 'node:http'; + * + * // Server has a 5 seconds keep-alive timeout by default + * http + * .createServer((req, res) => { + * res.write('hello\n'); + * res.end(); + * }) + * .listen(3000); + * + * setInterval(() => { + * // Adapting a keep-alive agent + * http.get('http://localhost:3000', { agent }, (res) => { + * res.on('data', (data) => { + * // Do nothing + * }); + * }); + * }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout + * ``` + * + * By marking a request whether it reused socket or not, we can do + * automatic error retry base on it. + * + * ```js + * import http from 'node:http'; + * const agent = new http.Agent({ keepAlive: true }); + * + * function retriableRequest() { + * const req = http + * .get('http://localhost:3000', { agent }, (res) => { + * // ... + * }) + * .on('error', (err) => { + * // Check if retry is needed + * if (req.reusedSocket && err.code === 'ECONNRESET') { + * retriableRequest(); + * } + * }); + * } + * + * retriableRequest(); + * ``` + * @since v13.0.0, v12.16.0 + */ + reusedSocket: boolean; + /** + * Limits maximum response headers count. If set to 0, no limit will be applied. + */ + maxHeadersCount: number; + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + /** + * The request method. + * @since v0.1.97 + */ + method: string; + /** + * The request path. + * @since v0.4.0 + */ + path: string; + /** + * Marks the request as aborting. Calling this will cause remaining data + * in the response to be dropped and the socket to be destroyed. + * @since v0.3.8 + * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. + */ + abort(): void; + onSocket(socket: Socket): void; + /** + * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. + * @since v0.5.9 + * @param timeout Milliseconds before a request times out. + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. + * @since v0.5.9 + */ + setNoDelay(noDelay?: boolean): void; + /** + * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. + * @since v0.5.9 + */ + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + /** + * Returns an array containing the unique names of the current outgoing raw + * headers. Header names are returned with their exact casing being set. + * + * ```js + * request.setHeader('Foo', 'bar'); + * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = request.getRawHeaderNames(); + * // headerNames === ['Foo', 'Set-Cookie'] + * ``` + * @since v15.13.0, v14.17.0 + */ + getRawHeaderNames(): string[]; + /** + * @deprecated + */ + addListener(event: "abort", listener: () => void): this; + addListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + addListener(event: "continue", listener: () => void): this; + addListener(event: "information", listener: (info: InformationEvent) => void): this; + addListener(event: "response", listener: (response: IncomingMessage) => void): this; + addListener(event: "socket", listener: (socket: Socket) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + on(event: "abort", listener: () => void): this; + on( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + on(event: "continue", listener: () => void): this; + on(event: "information", listener: (info: InformationEvent) => void): this; + on(event: "response", listener: (response: IncomingMessage) => void): this; + on(event: "socket", listener: (socket: Socket) => void): this; + on(event: "timeout", listener: () => void): this; + on( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + once(event: "abort", listener: () => void): this; + once( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + once(event: "continue", listener: () => void): this; + once(event: "information", listener: (info: InformationEvent) => void): this; + once(event: "response", listener: (response: IncomingMessage) => void): this; + once(event: "socket", listener: (socket: Socket) => void): this; + once(event: "timeout", listener: () => void): this; + once( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependListener(event: "abort", listener: () => void): this; + prependListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + prependListener(event: "continue", listener: () => void): this; + prependListener(event: "information", listener: (info: InformationEvent) => void): this; + prependListener(event: "response", listener: (response: IncomingMessage) => void): this; + prependListener(event: "socket", listener: (socket: Socket) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependOnceListener(event: "abort", listener: () => void): this; + prependOnceListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + prependOnceListener(event: "continue", listener: () => void): this; + prependOnceListener(event: "information", listener: (info: InformationEvent) => void): this; + prependOnceListener(event: "response", listener: (response: IncomingMessage) => void): this; + prependOnceListener(event: "socket", listener: (socket: Socket) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to + * access response + * status, headers, and data. + * + * Different from its `socket` value which is a subclass of `stream.Duplex`, the `IncomingMessage` itself extends `stream.Readable` and is created separately to + * parse and emit the incoming HTTP headers and payload, as the underlying socket + * may be reused multiple times in case of keep-alive. + * @since v0.1.17 + */ + class IncomingMessage extends stream.Readable { + constructor(socket: Socket); + /** + * The `message.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + * @deprecated Since v17.0.0,v16.12.0 - Check `message.destroyed` from stream.Readable. + */ + aborted: boolean; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. + * Probably either `'1.1'` or `'1.0'`. + * + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. + * @since v0.1.1 + */ + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + /** + * The `message.complete` property will be `true` if a complete HTTP message has + * been received and successfully parsed. + * + * This property is particularly useful as a means of determining if a client or + * server fully transmitted a message before a connection was terminated: + * + * ```js + * const req = http.request({ + * host: '127.0.0.1', + * port: 8080, + * method: 'POST', + * }, (res) => { + * res.resume(); + * res.on('end', () => { + * if (!res.complete) + * console.error( + * 'The connection was terminated while the message was still being sent'); + * }); + * }); + * ``` + * @since v0.3.0 + */ + complete: boolean; + /** + * Alias for `message.socket`. + * @since v0.1.90 + * @deprecated Since v16.0.0 - Use `socket`. + */ + connection: Socket; + /** + * The `net.Socket` object associated with the connection. + * + * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the + * client's authentication details. + * + * This property is guaranteed to be an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specified a socket + * type other than `net.Socket` or internally nulled. + * @since v0.3.0 + */ + socket: Socket; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * Duplicates in raw headers are handled in the following ways, depending on the + * header name: + * + * * Duplicates of `age`, `authorization`, `content-length`, `content-type`, `etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`, `last-modified`, `location`, + * `max-forwards`, `proxy-authorization`, `referer`, `retry-after`, `server`, or `user-agent` are discarded. + * To allow duplicate values of the headers listed above to be joined, + * use the option `joinDuplicateHeaders` in {@link request} and {@link createServer}. See RFC 9110 Section 5.3 for more + * information. + * * `set-cookie` is always an array. Duplicates are added to the array. + * * For duplicate `cookie` headers, the values are joined together with `; `. + * * For all other headers, the values are joined together with `, `. + * @since v0.1.5 + */ + headers: IncomingHttpHeaders; + /** + * Similar to `message.headers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': ['curl/7.22.0'], + * // host: ['127.0.0.1:8000'], + * // accept: ['*'] } + * console.log(request.headersDistinct); + * ``` + * @since v18.3.0, v16.17.0 + */ + headersDistinct: NodeJS.Dict; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v0.11.6 + */ + rawHeaders: string[]; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v0.3.0 + */ + trailers: NodeJS.Dict; + /** + * Similar to `message.trailers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * Only populated at the `'end'` event. + * @since v18.3.0, v16.17.0 + */ + trailersDistinct: NodeJS.Dict; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v0.11.6 + */ + rawTrailers: string[]; + /** + * Calls `message.socket.setTimeout(msecs, callback)`. + * @since v0.5.9 + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * **Only valid for request obtained from {@link Server}.** + * + * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. + * @since v0.1.1 + */ + method?: string | undefined; + /** + * **Only valid for request obtained from {@link Server}.** + * + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. Take the following request: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * To parse the URL into its parts: + * + * ```js + * new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and `process.env.HOST` is undefined: + * + * ```console + * $ node + * > new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); + * URL { + * href: 'http://localhost/status?name=ryan', + * origin: 'http://localhost', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost', + * hostname: 'localhost', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * + * Ensure that you set `process.env.HOST` to the server's host name, or consider replacing this part entirely. If using `req.headers.host`, ensure proper + * validation is used, as clients may specify a custom `Host` header. + * @since v0.1.90 + */ + url?: string | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The 3-digit HTTP response status code. E.G. `404`. + * @since v0.1.1 + */ + statusCode?: number | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + * @since v0.11.10 + */ + statusMessage?: string | undefined; + /** + * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error` is provided, an `'error'` event is emitted on the socket and `error` is passed + * as an argument to any listeners on the event. + * @since v0.3.0 + */ + destroy(error?: Error): this; + } + interface AgentOptions extends NodeJS.PartialOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean | undefined; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number | undefined; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number | undefined; + /** + * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. + */ + maxTotalSockets?: number | undefined; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number | undefined; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number | undefined; + /** + * Scheduling strategy to apply when picking the next free socket to use. + * @default `lifo` + */ + scheduling?: "fifo" | "lifo" | undefined; + } + /** + * An `Agent` is responsible for managing connection persistence + * and reuse for HTTP clients. It maintains a queue of pending requests + * for a given host and port, reusing a single socket connection for each + * until the queue is empty, at which time the socket is either destroyed + * or put into a pool where it is kept to be used again for requests to the + * same host and port. Whether it is destroyed or pooled depends on the `keepAlive` `option`. + * + * Pooled connections have TCP Keep-Alive enabled for them, but servers may + * still close idle connections, in which case they will be removed from the + * pool and a new connection will be made when a new HTTP request is made for + * that host and port. Servers may also refuse to allow multiple requests + * over the same connection, in which case the connection will have to be + * remade for every request and cannot be pooled. The `Agent` will still make + * the requests to that server, but each one will occur over a new connection. + * + * When a connection is closed by the client or the server, it is removed + * from the pool. Any unused sockets in the pool will be unrefed so as not + * to keep the Node.js process running when there are no outstanding requests. + * (see `socket.unref()`). + * + * It is good practice, to `destroy()` an `Agent` instance when it is no + * longer in use, because unused sockets consume OS resources. + * + * Sockets are removed from an agent when the socket emits either + * a `'close'` event or an `'agentRemove'` event. When intending to keep one + * HTTP request open for a long time without keeping it in the agent, something + * like the following may be done: + * + * ```js + * http.get(options, (res) => { + * // Do stuff + * }).on('socket', (socket) => { + * socket.emit('agentRemove'); + * }); + * ``` + * + * An agent may also be used for an individual request. By providing `{agent: false}` as an option to the `http.get()` or `http.request()` functions, a one-time use `Agent` with default options + * will be used + * for the client connection. + * + * `agent:false`: + * + * ```js + * http.get({ + * hostname: 'localhost', + * port: 80, + * path: '/', + * agent: false, // Create a new agent just for this one request + * }, (res) => { + * // Do stuff with response + * }); + * ``` + * + * `options` in [`socket.connect()`](https://nodejs.org/docs/latest-v22.x/api/net.html#socketconnectoptions-connectlistener) are also supported. + * + * To configure any of them, a custom {@link Agent} instance must be created. + * + * ```js + * import http from 'node:http'; + * const keepAliveAgent = new http.Agent({ keepAlive: true }); + * options.agent = keepAliveAgent; + * http.request(options, onResponseCallback) + * ``` + * @since v0.3.4 + */ + class Agent extends EventEmitter { + /** + * By default set to 256. For agents with `keepAlive` enabled, this + * sets the maximum number of sockets that will be left open in the free + * state. + * @since v0.11.7 + */ + maxFreeSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open per origin. Origin is the returned value of `agent.getName()`. + * @since v0.3.6 + */ + maxSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open. Unlike `maxSockets`, this parameter applies across all origins. + * @since v14.5.0, v12.19.0 + */ + maxTotalSockets: number; + /** + * An object which contains arrays of sockets currently awaiting use by + * the agent when `keepAlive` is enabled. Do not modify. + * + * Sockets in the `freeSockets` list will be automatically destroyed and + * removed from the array on `'timeout'`. + * @since v0.11.4 + */ + readonly freeSockets: NodeJS.ReadOnlyDict; + /** + * An object which contains arrays of sockets currently in use by the + * agent. Do not modify. + * @since v0.3.6 + */ + readonly sockets: NodeJS.ReadOnlyDict; + /** + * An object which contains queues of requests that have not yet been assigned to + * sockets. Do not modify. + * @since v0.5.9 + */ + readonly requests: NodeJS.ReadOnlyDict; + constructor(opts?: AgentOptions); + /** + * Destroy any sockets that are currently in use by the agent. + * + * It is usually not necessary to do this. However, if using an + * agent with `keepAlive` enabled, then it is best to explicitly shut down + * the agent when it is no longer needed. Otherwise, + * sockets might stay open for quite a long time before the server + * terminates them. + * @since v0.11.4 + */ + destroy(): void; + /** + * Produces a socket/stream to be used for HTTP requests. + * + * By default, this function is the same as `net.createConnection()`. However, + * custom agents may override this method in case greater flexibility is desired. + * + * A socket/stream can be supplied in one of two ways: by returning the + * socket/stream from this function, or by passing the socket/stream to `callback`. + * + * This method is guaranteed to return an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specifies a socket + * type other than `net.Socket`. + * + * `callback` has a signature of `(err, stream)`. + * @since v0.11.4 + * @param options Options containing connection details. Check `createConnection` for the format of the options + * @param callback Callback function that receives the created socket + */ + createConnection( + options: ClientRequestArgs, + callback?: (err: Error | null, stream: stream.Duplex) => void, + ): stream.Duplex | null | undefined; + /** + * Called when `socket` is detached from a request and could be persisted by the`Agent`. Default behavior is to: + * + * ```js + * socket.setKeepAlive(true, this.keepAliveMsecs); + * socket.unref(); + * return true; + * ``` + * + * This method can be overridden by a particular `Agent` subclass. If this + * method returns a falsy value, the socket will be destroyed instead of persisting + * it for use with the next request. + * + * The `socket` argument can be an instance of `net.Socket`, a subclass of `stream.Duplex`. + * @since v8.1.0 + */ + keepSocketAlive(socket: stream.Duplex): void; + /** + * Called when `socket` is attached to `request` after being persisted because of + * the keep-alive options. Default behavior is to: + * + * ```js + * socket.ref(); + * ``` + * + * This method can be overridden by a particular `Agent` subclass. + * + * The `socket` argument can be an instance of `net.Socket`, a subclass of `stream.Duplex`. + * @since v8.1.0 + */ + reuseSocket(socket: stream.Duplex, request: ClientRequest): void; + /** + * Get a unique name for a set of request options, to determine whether a + * connection can be reused. For an HTTP agent, this returns`host:port:localAddress` or `host:port:localAddress:family`. For an HTTPS agent, + * the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options + * that determine socket reusability. + * @since v0.11.4 + * @param options A set of options providing information for name generation + */ + getName(options?: ClientRequestArgs): string; + } + const METHODS: string[]; + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + /** + * Returns a new instance of {@link Server}. + * + * The `requestListener` is a function which is automatically + * added to the `'request'` event. + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer(); + * + * // Listen to the request event + * server.on('request', (request, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.1.13 + */ + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + >(requestListener?: RequestListener): Server; + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + >( + options: ServerOptions, + requestListener?: RequestListener, + ): Server; + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs {} + /** + * `options` in `socket.connect()` are also supported. + * + * Node.js maintains several connections per server to make HTTP requests. + * This function allows one to transparently issue requests. + * + * `url` can be a string or a `URL` object. If `url` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * If both `url` and `options` are specified, the objects are merged, with the `options` properties taking precedence. + * + * The optional `callback` parameter will be added as a one-time listener for + * the `'response'` event. + * + * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * import http from 'node:http'; + * import { Buffer } from 'node:buffer'; + * + * const postData = JSON.stringify({ + * 'msg': 'Hello World!', + * }); + * + * const options = { + * hostname: 'www.google.com', + * port: 80, + * path: '/upload', + * method: 'POST', + * headers: { + * 'Content-Type': 'application/json', + * 'Content-Length': Buffer.byteLength(postData), + * }, + * }; + * + * const req = http.request(options, (res) => { + * console.log(`STATUS: ${res.statusCode}`); + * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); + * res.setEncoding('utf8'); + * res.on('data', (chunk) => { + * console.log(`BODY: ${chunk}`); + * }); + * res.on('end', () => { + * console.log('No more data in response.'); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(`problem with request: ${e.message}`); + * }); + * + * // Write data to request body + * req.write(postData); + * req.end(); + * ``` + * + * In the example `req.end()` was called. With `http.request()` one + * must always call `req.end()` to signify the end of the request - + * even if there is no data being written to the request body. + * + * If any error is encountered during the request (be that with DNS resolution, + * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted + * on the returned request object. As with all `'error'` events, if no listeners + * are registered the error will be thrown. + * + * There are a few special headers that should be noted. + * + * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to + * the server should be persisted until the next request. + * * Sending a 'Content-Length' header will disable the default chunked encoding. + * * Sending an 'Expect' header will immediately send the request headers. + * Usually, when sending 'Expect: 100-continue', both a timeout and a listener + * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more + * information. + * * Sending an Authorization header will override using the `auth` option + * to compute basic authentication. + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('http://abc:xyz@example.com'); + * + * const req = http.request(options, (res) => { + * // ... + * }); + * ``` + * + * In a successful request, the following events will be emitted in the following + * order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * (`'data'` will not be emitted at all if the response body is empty, for + * instance, in most redirects) + * * `'end'` on the `res` object + * * `'close'` + * + * In the case of a connection error, the following events will be emitted: + * + * * `'socket'` + * * `'error'` + * * `'close'` + * + * In the case of a premature connection close before the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` + * * `'close'` + * + * In the case of a premature connection close after the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (connection closed here) + * * `'aborted'` on the `res` object + * * `'close'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'` + * * `'close'` on the `res` object + * + * If `req.destroy()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.destroy()` called here) + * * `'aborted'` on the `res` object + * * `'close'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` on the `res` object + * + * If `req.abort()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.abort()` called here) + * * `'abort'` + * * `'close'` + * + * If `req.abort()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.abort()` called here) + * * `'abort'` + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` + * * `'close'` + * + * If `req.abort()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.abort()` called here) + * * `'abort'` + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * Setting the `timeout` option or using the `setTimeout()` function will + * not abort the request or do anything besides add a `'timeout'` event. + * + * Passing an `AbortSignal` and then calling `abort()` on the corresponding `AbortController` will behave the same way as calling `.destroy()` on the + * request. Specifically, the `'error'` event will be emitted with an error with + * the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'` and the `cause`, if one was provided. + * @since v0.3.6 + */ + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: IncomingMessage) => void, + ): ClientRequest; + /** + * Since most requests are GET requests without bodies, Node.js provides this + * convenience method. The only difference between this method and {@link request} is that it sets the method to GET by default and calls `req.end()` automatically. The callback must take care to + * consume the response + * data for reasons stated in {@link ClientRequest} section. + * + * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. + * + * JSON fetching example: + * + * ```js + * http.get('http://localhost:8000/', (res) => { + * const { statusCode } = res; + * const contentType = res.headers['content-type']; + * + * let error; + * // Any 2xx status code signals a successful response but + * // here we're only checking for 200. + * if (statusCode !== 200) { + * error = new Error('Request Failed.\n' + + * `Status Code: ${statusCode}`); + * } else if (!/^application\/json/.test(contentType)) { + * error = new Error('Invalid content-type.\n' + + * `Expected application/json but received ${contentType}`); + * } + * if (error) { + * console.error(error.message); + * // Consume response data to free up memory + * res.resume(); + * return; + * } + * + * res.setEncoding('utf8'); + * let rawData = ''; + * res.on('data', (chunk) => { rawData += chunk; }); + * res.on('end', () => { + * try { + * const parsedData = JSON.parse(rawData); + * console.log(parsedData); + * } catch (e) { + * console.error(e.message); + * } + * }); + * }).on('error', (e) => { + * console.error(`Got error: ${e.message}`); + * }); + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the method set to GET by default. + */ + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + /** + * Performs the low-level validations on the provided `name` that are done when `res.setHeader(name, value)` is called. + * + * Passing illegal value as `name` will result in a `TypeError` being thrown, + * identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Example: + * + * ```js + * import { validateHeaderName } from 'node:http'; + * + * try { + * validateHeaderName(''); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN' + * console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' + * } + * ``` + * @since v14.3.0 + * @param [label='Header name'] Label for error message. + */ + function validateHeaderName(name: string): void; + /** + * Performs the low-level validations on the provided `value` that are done when `res.setHeader(name, value)` is called. + * + * Passing illegal value as `value` will result in a `TypeError` being thrown. + * + * * Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. + * * Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Examples: + * + * ```js + * import { validateHeaderValue } from 'node:http'; + * + * try { + * validateHeaderValue('x-my-header', undefined); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true + * console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' + * } + * + * try { + * validateHeaderValue('x-my-header', 'oʊmɪɡə'); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_INVALID_CHAR'); // --> true + * console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' + * } + * ``` + * @since v14.3.0 + * @param name Header name + * @param value Header value + */ + function validateHeaderValue(name: string, value: string): void; + /** + * Set the maximum number of idle HTTP parsers. + * @since v18.8.0, v16.18.0 + * @param [max=1000] + */ + function setMaxIdleHTTPParsers(max: number): void; + /** + * Global instance of `Agent` which is used as the default for all HTTP client + * requests. Diverges from a default `Agent` configuration by having `keepAlive` + * enabled and a `timeout` of 5 seconds. + * @since v0.5.9 + */ + let globalAgent: Agent; + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; + /** + * A browser-compatible implementation of `WebSocket`. + * @since v22.5.0 + */ + const WebSocket: typeof import("undici-types").WebSocket; + /** + * @since v22.5.0 + */ + const CloseEvent: typeof import("undici-types").CloseEvent; + /** + * @since v22.5.0 + */ + const MessageEvent: typeof import("undici-types").MessageEvent; +} +declare module "node:http" { + export * from "http"; +} diff --git a/node_modules/@types/node/http2.d.ts b/node_modules/@types/node/http2.d.ts new file mode 100644 index 0000000..da24362 --- /dev/null +++ b/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2721 @@ +/** + * The `node:http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. + * It can be accessed using: + * + * ```js + * import http2 from 'node:http2'; + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/http2.js) + */ +declare module "http2" { + import { NonSharedBuffer } from "node:buffer"; + import EventEmitter = require("node:events"); + import * as fs from "node:fs"; + import * as net from "node:net"; + import * as stream from "node:stream"; + import * as tls from "node:tls"; + import * as url from "node:url"; + import { + IncomingHttpHeaders as Http1IncomingHttpHeaders, + IncomingMessage, + OutgoingHttpHeaders, + ServerResponse, + } from "node:http"; + export { OutgoingHttpHeaders } from "node:http"; + export interface IncomingHttpStatusHeader { + ":status"?: number | undefined; + } + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ":path"?: string | undefined; + ":method"?: string | undefined; + ":authority"?: string | undefined; + ":scheme"?: string | undefined; + } + // Http2Stream + export interface StreamPriorityOptions { + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + silent?: boolean | undefined; + } + export interface StreamState { + localWindowSize?: number | undefined; + state?: number | undefined; + localClose?: number | undefined; + remoteClose?: number | undefined; + sumDependencyWeight?: number | undefined; + weight?: number | undefined; + } + export interface ServerStreamResponseOptions { + endStream?: boolean | undefined; + waitForTrailers?: boolean | undefined; + } + export interface StatOptions { + offset: number; + length: number; + } + export interface ServerStreamFileResponseOptions { + statCheck?: + | ((stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void) + | undefined; + waitForTrailers?: boolean | undefined; + offset?: number | undefined; + length?: number | undefined; + } + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?: ((err: NodeJS.ErrnoException) => void) | undefined; + } + export interface Http2Stream extends stream.Duplex { + /** + * Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, + * the `'aborted'` event will have been emitted. + * @since v8.4.0 + */ + readonly aborted: boolean; + /** + * This property shows the number of characters currently buffered to be written. + * See `net.Socket.bufferSize` for details. + * @since v11.2.0, v10.16.0 + */ + readonly bufferSize: number; + /** + * Set to `true` if the `Http2Stream` instance has been closed. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Set to `true` if the `Http2Stream` instance has been destroyed and is no longer + * usable. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Set to `true` if the `END_STREAM` flag was set in the request or response + * HEADERS frame received, indicating that no additional data should be received + * and the readable side of the `Http2Stream` will be closed. + * @since v10.11.0 + */ + readonly endAfterHeaders: boolean; + /** + * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined` if the stream identifier has not yet been assigned. + * @since v8.4.0 + */ + readonly id?: number | undefined; + /** + * Set to `true` if the `Http2Stream` instance has not yet been assigned a + * numeric stream identifier. + * @since v9.4.0 + */ + readonly pending: boolean; + /** + * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is + * destroyed after either receiving an `RST_STREAM` frame from the connected peer, + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be `undefined` if the `Http2Stream` has not been closed. + * @since v8.4.0 + */ + readonly rstCode: number; + /** + * An object containing the outbound headers sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentHeaders: OutgoingHttpHeaders; + /** + * An array of objects containing the outbound informational (additional) headers + * sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined; + /** + * An object containing the outbound trailers sent for this `HttpStream`. + * @since v9.5.0 + */ + readonly sentTrailers?: OutgoingHttpHeaders | undefined; + /** + * A reference to the `Http2Session` instance that owns this `Http2Stream`. The + * value will be `undefined` after the `Http2Stream` instance is destroyed. + * @since v8.4.0 + */ + readonly session: Http2Session | undefined; + /** + * Provides miscellaneous information about the current state of the `Http2Stream`. + * + * A current state of this `Http2Stream`. + * @since v8.4.0 + */ + readonly state: StreamState; + /** + * Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the + * connected HTTP/2 peer. + * @since v8.4.0 + * @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code. + * @param callback An optional function registered to listen for the `'close'` event. + */ + close(code?: number, callback?: () => void): void; + /** + * Updates the priority for this `Http2Stream` instance. + * @since v8.4.0 + */ + priority(options: StreamPriorityOptions): void; + /** + * ```js + * import http2 from 'node:http2'; + * const client = http2.connect('http://example.org:8000'); + * const { NGHTTP2_CANCEL } = http2.constants; + * const req = client.request({ ':path': '/' }); + * + * // Cancel the stream if there's no activity after 5 seconds + * req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); + * ``` + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method + * will cause the `Http2Stream` to be immediately closed and must only be + * called after the `'wantTrailers'` event has been emitted. When sending a + * request or sending a response, the `options.waitForTrailers` option must be set + * in order to keep the `Http2Stream` open after the final `DATA` frame so that + * trailers can be sent. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond(undefined, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ xyz: 'abc' }); + * }); + * stream.end('Hello World'); + * }); + * ``` + * + * The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header + * fields (e.g. `':method'`, `':path'`, etc). + * @since v10.0.0 + */ + sendTrailers(headers: OutgoingHttpHeaders): void; + addListener(event: "aborted", listener: () => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener( + event: "frameError", + listener: (frameType: number, errorCode: number, id: number) => void, + ): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: "streamClosed", listener: (code: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "wantTrailers", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted"): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: NonSharedBuffer | string): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "frameError", frameType: number, errorCode: number, id: number): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: "streamClosed", code: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "wantTrailers"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: () => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number, id: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: "streamClosed", listener: (code: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "wantTrailers", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: () => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number, id: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: "streamClosed", listener: (code: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "wantTrailers", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: () => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener( + event: "frameError", + listener: (frameType: number, errorCode: number, id: number) => void, + ): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "streamClosed", listener: (code: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "wantTrailers", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: () => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener( + event: "frameError", + listener: (frameType: number, errorCode: number, id: number) => void, + ): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "wantTrailers", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: "continue", listener: () => {}): this; + addListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "continue"): boolean; + emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "continue", listener: () => {}): this; + on( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "continue", listener: () => {}): this; + once( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "continue", listener: () => {}): this; + prependListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "continue", listener: () => {}): this; + prependOnceListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ServerHttp2Stream extends Http2Stream { + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote + * client's most recent `SETTINGS` frame. Will be `true` if the remote peer + * accepts push streams, `false` otherwise. Settings are the same for every `Http2Stream` in the same `Http2Session`. + * @since v8.4.0 + */ + readonly pushAllowed: boolean; + /** + * Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. + * @since v8.4.0 + */ + additionalHeaders(headers: OutgoingHttpHeaders): void; + /** + * Initiates a push stream. The callback is invoked with the new `Http2Stream` instance created for the push stream passed as the second argument, or an `Error` passed as the first argument. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { + * if (err) throw err; + * pushStream.respond({ ':status': 200 }); + * pushStream.end('some pushed data'); + * }); + * stream.end('some data'); + * }); + * ``` + * + * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass + * a `weight` value to `http2stream.priority` with the `silent` option set to `true` to enable server-side bandwidth balancing between concurrent streams. + * + * Calling `http2stream.pushStream()` from within a pushed stream is not permitted + * and will throw an error. + * @since v8.4.0 + * @param callback Callback that is called once the push stream has been initiated. + */ + pushStream( + headers: OutgoingHttpHeaders, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + pushStream( + headers: OutgoingHttpHeaders, + options?: StreamPriorityOptions, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + /** + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * Initiates a response. When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be used to send trailing header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either `http2stream.sendTrailers()` or `http2stream.close()` to close the `Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * stream.end('some data'); + * }); + * ``` + * @since v8.4.0 + */ + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + /** + * Initiates a response whose data is read from the given file descriptor. No + * validation is performed on the given file descriptor. If an error occurs while + * attempting to read data using the file descriptor, the `Http2Stream` will be + * closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers); + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given fd. If the `statCheck` function is provided, the `http2stream.respondWithFD()` method will + * perform an `fs.fstat()` call to collect details on the provided file descriptor. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The file descriptor or `FileHandle` is not closed when the stream is closed, + * so it will need to be closed manually once it is no longer needed. + * Using the same file descriptor concurrently for multiple streams + * is not supported and may result in data loss. Re-using a file descriptor + * after a stream has finished is supported. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code _must_ call either `http2stream.sendTrailers()` + * or `http2stream.close()` to close the `Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * @since v8.4.0 + * @param fd A readable file descriptor. + */ + respondWithFD( + fd: number | fs.promises.FileHandle, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptions, + ): void; + /** + * Sends a regular file as the response. The `path` must specify a regular file + * or an `'error'` event will be emitted on the `Http2Stream` object. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given file: + * + * If an error occurs while attempting to read the file data, the `Http2Stream` will be closed using an + * `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * If the `onError` callback is defined, then it will be called. Otherwise, the stream will be destroyed. + * + * Example using a file path: + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * headers['last-modified'] = stat.mtime.toUTCString(); + * } + * + * function onError(err) { + * // stream.respond() can throw if the stream has been destroyed by + * // the other side. + * try { + * if (err.code === 'ENOENT') { + * stream.respond({ ':status': 404 }); + * } else { + * stream.respond({ ':status': 500 }); + * } + * } catch (err) { + * // Perform actual error handling. + * console.error(err); + * } + * stream.end(); + * } + * + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck, onError }); + * }); + * ``` + * + * The `options.statCheck` function may also be used to cancel the send operation + * by returning `false`. For instance, a conditional request may check the stat + * results to determine if the file has been modified to return an appropriate `304` response: + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * // Check the stat here... + * stream.respond({ ':status': 304 }); + * return false; // Cancel the send operation + * } + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck }); + * }); + * ``` + * + * The `content-length` header field will be automatically set. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The `options.onError` function may also be used to handle all the errors + * that could happen before the delivery of the file is initiated. The + * default behavior is to destroy the stream. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * }); + * ``` + * @since v8.4.0 + */ + respondWithFile( + path: string, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptionsWithError, + ): void; + } + // Http2Session + export interface Settings { + headerTableSize?: number | undefined; + enablePush?: boolean | undefined; + initialWindowSize?: number | undefined; + maxFrameSize?: number | undefined; + maxConcurrentStreams?: number | undefined; + maxHeaderListSize?: number | undefined; + enableConnectProtocol?: boolean | undefined; + } + export interface ClientSessionRequestOptions { + endStream?: boolean | undefined; + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + waitForTrailers?: boolean | undefined; + signal?: AbortSignal | undefined; + } + export interface SessionState { + effectiveLocalWindowSize?: number | undefined; + effectiveRecvDataLength?: number | undefined; + nextStreamID?: number | undefined; + localWindowSize?: number | undefined; + lastProcStreamID?: number | undefined; + remoteWindowSize?: number | undefined; + outboundQueueSize?: number | undefined; + deflateDynamicTableSize?: number | undefined; + inflateDynamicTableSize?: number | undefined; + } + export interface Http2Session extends EventEmitter { + /** + * Value will be `undefined` if the `Http2Session` is not yet connected to a + * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or + * will return the value of the connected `TLSSocket`'s own `alpnProtocol` property. + * @since v9.4.0 + */ + readonly alpnProtocol?: string | undefined; + /** + * Will be `true` if this `Http2Session` instance has been closed, otherwise `false`. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Will be `true` if this `Http2Session` instance is still connecting, will be set + * to `false` before emitting `connect` event and/or calling the `http2.connect` callback. + * @since v10.0.0 + */ + readonly connecting: boolean; + /** + * Will be `true` if this `Http2Session` instance has been destroyed and must no + * longer be used, otherwise `false`. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Value is `undefined` if the `Http2Session` session socket has not yet been + * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, + * and `false` if the `Http2Session` is connected to any other kind of socket + * or stream. + * @since v9.4.0 + */ + readonly encrypted?: boolean | undefined; + /** + * A prototype-less object describing the current local settings of this `Http2Session`. + * The local settings are local to _this_`Http2Session` instance. + * @since v8.4.0 + */ + readonly localSettings: Settings; + /** + * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property + * will return an `Array` of origins for which the `Http2Session` may be + * considered authoritative. + * + * The `originSet` property is only available when using a secure TLS connection. + * @since v9.4.0 + */ + readonly originSet?: string[] | undefined; + /** + * Indicates whether the `Http2Session` is currently waiting for acknowledgment of + * a sent `SETTINGS` frame. Will be `true` after calling the `http2session.settings()` method. + * Will be `false` once all sent `SETTINGS` frames have been acknowledged. + * @since v8.4.0 + */ + readonly pendingSettingsAck: boolean; + /** + * A prototype-less object describing the current remote settings of this`Http2Session`. + * The remote settings are set by the _connected_ HTTP/2 peer. + * @since v8.4.0 + */ + readonly remoteSettings: Settings; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * limits available methods to ones safe to use with HTTP/2. + * + * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw + * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. + * + * `setTimeout` method will be called on this `Http2Session`. + * + * All other interactions will be routed directly to the socket. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * Provides miscellaneous information about the current state of the`Http2Session`. + * + * An object describing the current status of this `Http2Session`. + * @since v8.4.0 + */ + readonly state: SessionState; + /** + * The `http2session.type` will be equal to `http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a + * client. + * @since v8.4.0 + */ + readonly type: number; + /** + * Gracefully closes the `Http2Session`, allowing any existing streams to + * complete on their own and preventing new `Http2Stream` instances from being + * created. Once closed, `http2session.destroy()`_might_ be called if there + * are no open `Http2Stream` instances. + * + * If specified, the `callback` function is registered as a handler for the`'close'` event. + * @since v9.4.0 + */ + close(callback?: () => void): void; + /** + * Immediately terminates the `Http2Session` and the associated `net.Socket` or `tls.TLSSocket`. + * + * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error` is not undefined, an `'error'` event will be emitted immediately before the `'close'` event. + * + * If there are any remaining open `Http2Streams` associated with the `Http2Session`, those will also be destroyed. + * @since v8.4.0 + * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. + * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. + */ + destroy(error?: Error, code?: number): void; + /** + * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. + * @since v9.4.0 + * @param code An HTTP/2 error code + * @param lastStreamID The numeric ID of the last processed `Http2Stream` + * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. + */ + goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; + /** + * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must + * be provided. The method will return `true` if the `PING` was sent, `false` otherwise. + * + * The maximum number of outstanding (unacknowledged) pings is determined by the `maxOutstandingPings` configuration option. The default maximum is 10. + * + * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView` containing 8 bytes of data that will be transmitted with the `PING` and + * returned with the ping acknowledgment. + * + * The callback will be invoked with three arguments: an error argument that will + * be `null` if the `PING` was successfully acknowledged, a `duration` argument + * that reports the number of milliseconds elapsed since the ping was sent and the + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING` payload. + * + * ```js + * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { + * if (!err) { + * console.log(`Ping acknowledged in ${duration} milliseconds`); + * console.log(`With payload '${payload.toString()}'`); + * } + * }); + * ``` + * + * If the `payload` argument is not specified, the default payload will be the + * 64-bit timestamp (little endian) marking the start of the `PING` duration. + * @since v8.9.3 + * @param payload Optional ping payload. + */ + ping(callback: (err: Error | null, duration: number, payload: NonSharedBuffer) => void): boolean; + ping( + payload: NodeJS.ArrayBufferView, + callback: (err: Error | null, duration: number, payload: NonSharedBuffer) => void, + ): boolean; + /** + * Calls `ref()` on this `Http2Session` instance's underlying `net.Socket`. + * @since v9.4.0 + */ + ref(): void; + /** + * Sets the local endpoint's window size. + * The `windowSize` is the total window size to set, not + * the delta. + * + * ```js + * import http2 from 'node:http2'; + * + * const server = http2.createServer(); + * const expectedWindowSize = 2 ** 20; + * server.on('connect', (session) => { + * + * // Set local window size to be 2 ** 20 + * session.setLocalWindowSize(expectedWindowSize); + * }); + * ``` + * @since v15.3.0, v14.18.0 + */ + setLocalWindowSize(windowSize: number): void; + /** + * Used to set a callback function that is called when there is no activity on + * the `Http2Session` after `msecs` milliseconds. The given `callback` is + * registered as a listener on the `'timeout'` event. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Updates the current local settings for this `Http2Session` and sends a new `SETTINGS` frame to the connected HTTP/2 peer. + * + * Once called, the `http2session.pendingSettingsAck` property will be `true` while the session is waiting for the remote peer to acknowledge the new + * settings. + * + * The new settings will not become effective until the `SETTINGS` acknowledgment + * is received and the `'localSettings'` event is emitted. It is possible to send + * multiple `SETTINGS` frames while acknowledgment is still pending. + * @since v8.4.0 + * @param callback Callback that is called once the session is connected or right away if the session is already connected. + */ + settings( + settings: Settings, + callback?: (err: Error | null, settings: Settings, duration: number) => void, + ): void; + /** + * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + unref(): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "frameError", + listener: (frameType: number, errorCode: number, id: number) => void, + ): this; + addListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer) => void, + ): this; + addListener(event: "localSettings", listener: (settings: Settings) => void): this; + addListener(event: "ping", listener: () => void): this; + addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "frameError", frameType: number, errorCode: number, id: number): boolean; + emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer): boolean; + emit(event: "localSettings", settings: Settings): boolean; + emit(event: "ping"): boolean; + emit(event: "remoteSettings", settings: Settings): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number, id: number) => void): this; + on( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer) => void, + ): this; + on(event: "localSettings", listener: (settings: Settings) => void): this; + on(event: "ping", listener: () => void): this; + on(event: "remoteSettings", listener: (settings: Settings) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number, id: number) => void): this; + once( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer) => void, + ): this; + once(event: "localSettings", listener: (settings: Settings) => void): this; + once(event: "ping", listener: () => void): this; + once(event: "remoteSettings", listener: (settings: Settings) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "frameError", + listener: (frameType: number, errorCode: number, id: number) => void, + ): this; + prependListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer) => void, + ): this; + prependListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependListener(event: "ping", listener: () => void): this; + prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "frameError", + listener: (frameType: number, errorCode: number, id: number) => void, + ): this; + prependOnceListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer) => void, + ): this; + prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "ping", listener: () => void): this; + prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Session extends Http2Session { + /** + * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()` creates and returns an `Http2Stream` instance that can be used to send an + * HTTP/2 request to the connected server. + * + * When a `ClientHttp2Session` is first created, the socket may not yet be + * connected. if `clienthttp2session.request()` is called during this time, the + * actual request will be deferred until the socket is ready to go. + * If the `session` is closed before the actual request be executed, an `ERR_HTTP2_GOAWAY_SESSION` is thrown. + * + * This method is only available if `http2session.type` is equal to `http2.constants.NGHTTP2_SESSION_CLIENT`. + * + * ```js + * import http2 from 'node:http2'; + * const clientSession = http2.connect('https://localhost:1234'); + * const { + * HTTP2_HEADER_PATH, + * HTTP2_HEADER_STATUS, + * } = http2.constants; + * + * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); + * req.on('response', (headers) => { + * console.log(headers[HTTP2_HEADER_STATUS]); + * req.on('data', (chunk) => { // .. }); + * req.on('end', () => { // .. }); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * is emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be called to send trailing + * headers to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * When `options.signal` is set with an `AbortSignal` and then `abort` on the + * corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error. + * + * The `:method` and `:path` pseudo-headers are not specified within `headers`, + * they respectively default to: + * + * * `:method` \= `'GET'` + * * `:path` \= `/` + * @since v8.4.0 + */ + request( + headers?: OutgoingHttpHeaders | readonly string[], + options?: ClientSessionRequestOptions, + ): ClientHttp2Stream; + addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: "origin", listener: (origins: string[]) => void): this; + addListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + addListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; + emit(event: "origin", origins: readonly string[]): boolean; + emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit( + event: "stream", + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + on(event: "origin", listener: (origins: string[]) => void): this; + on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + once(event: "origin", listener: (origins: string[]) => void): this; + once( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + once( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: "origin", listener: (origins: string[]) => void): this; + prependListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: "origin", listener: (origins: string[]) => void): this; + prependOnceListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependOnceListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + export interface ServerHttp2Session< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends Http2Session { + readonly server: + | Http2Server + | Http2SecureServer; + /** + * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. + * + * ```js + * import http2 from 'node:http2'; + * + * const server = http2.createServer(); + * server.on('session', (session) => { + * // Set altsvc for origin https://example.org:80 + * session.altsvc('h2=":8000"', 'https://example.org:80'); + * }); + * + * server.on('stream', (stream) => { + * // Set altsvc for a specific stream + * stream.session.altsvc('h2=":8000"', stream.id); + * }); + * ``` + * + * Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate + * service is associated with the origin of the given `Http2Stream`. + * + * The `alt` and origin string _must_ contain only ASCII bytes and are + * strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given + * domain. + * + * When a string is passed for the `originOrStream` argument, it will be parsed as + * a URL and the origin will be derived. For instance, the origin for the + * HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * @since v9.4.0 + * @param alt A description of the alternative service configuration as defined by `RFC 7838`. + * @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the + * `http2stream.id` property. + */ + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + /** + * Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client + * to advertise the set of origins for which the server is capable of providing + * authoritative responses. + * + * ```js + * import http2 from 'node:http2'; + * const options = getSecureOptionsSomehow(); + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * server.on('session', (session) => { + * session.origin('https://example.com', 'https://example.org'); + * }); + * ``` + * + * When a string is passed as an `origin`, it will be parsed as a URL and the + * origin will be derived. For instance, the origin for the HTTP URL `'https://example.org/foo/bar'` is the ASCII string` 'https://example.org'`. An error will be thrown if either the given + * string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as + * an `origin`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * + * Alternatively, the `origins` option may be used when creating a new HTTP/2 + * server using the `http2.createSecureServer()` method: + * + * ```js + * import http2 from 'node:http2'; + * const options = getSecureOptionsSomehow(); + * options.origins = ['https://example.com', 'https://example.org']; + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * ``` + * @since v10.12.0 + * @param origins One or more URL Strings passed as separate arguments. + */ + origin( + ...origins: Array< + | string + | url.URL + | { + origin: string; + } + > + ): void; + addListener( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit( + event: "connect", + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + // Http2Server + export interface SessionOptions { + /** + * Sets the maximum dynamic table size for deflating header fields. + * @default 4Kib + */ + maxDeflateDynamicTableSize?: number | undefined; + /** + * Sets the maximum number of settings entries per `SETTINGS` frame. + * The minimum value allowed is `1`. + * @default 32 + */ + maxSettings?: number | undefined; + /** + * Sets the maximum memory that the `Http2Session` is permitted to use. + * The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. + * The minimum value allowed is `1`. + * This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, + * but new `Http2Stream` instances will be rejected while this limit is exceeded. + * The current number of `Http2Stream` sessions, the current memory use of the header compression tables, + * current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit. + * @default 10 + */ + maxSessionMemory?: number | undefined; + /** + * Sets the maximum number of header entries. + * This is similar to `server.maxHeadersCount` or `request.maxHeadersCount` in the `node:http` module. + * The minimum value is `1`. + * @default 128 + */ + maxHeaderListPairs?: number | undefined; + /** + * Sets the maximum number of outstanding, unacknowledged pings. + * @default 10 + */ + maxOutstandingPings?: number | undefined; + /** + * Sets the maximum allowed size for a serialized, compressed block of headers. + * Attempts to send headers that exceed this limit will result in + * a `'frameError'` event being emitted and the stream being closed and destroyed. + */ + maxSendHeaderBlockLength?: number | undefined; + /** + * Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames. + * @default http2.constants.PADDING_STRATEGY_NONE + */ + paddingStrategy?: number | undefined; + /** + * Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. + * Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. + * @default 100 + */ + peerMaxConcurrentStreams?: number | undefined; + /** + * The initial settings to send to the remote peer upon connection. + */ + settings?: Settings | undefined; + /** + * The array of integer values determines the settings types, + * which are included in the `CustomSettings`-property of the received remoteSettings. + * Please see the `CustomSettings`-property of the `Http2Settings` object for more information, on the allowed setting types. + */ + remoteCustomSettings?: number[] | undefined; + /** + * Specifies a timeout in milliseconds that + * a server should wait when an [`'unknownProtocol'`][] is emitted. If the + * socket has not been destroyed by that time the server will destroy it. + * @default 100000 + */ + unknownProtocolTimeout?: number | undefined; + /** + * If `true`, it turns on strict leading + * and trailing whitespace validation for HTTP/2 header field names and values + * as per [RFC-9113](https://www.rfc-editor.org/rfc/rfc9113.html#section-8.2.1). + * @since v24.2.0 + * @default true + */ + strictFieldWhitespaceValidation?: boolean | undefined; + } + export interface ClientSessionOptions extends SessionOptions { + /** + * Sets the maximum number of reserved push streams the client will accept at any given time. + * Once the current number of currently reserved push streams exceeds reaches this limit, + * new push streams sent by the server will be automatically rejected. + * The minimum allowed value is 0. The maximum allowed value is 232-1. + * A negative value sets this option to the maximum allowed value. + * @default 200 + */ + maxReservedRemoteStreams?: number | undefined; + /** + * An optional callback that receives the `URL` instance passed to `connect` and the `options` object, + * and returns any `Duplex` stream that is to be used as the connection for this session. + */ + createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; + /** + * The protocol to connect with, if not set in the `authority`. + * Value may be either `'http:'` or `'https:'`. + * @default 'https:' + */ + protocol?: "http:" | "https:" | undefined; + } + export interface ServerSessionOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends SessionOptions { + streamResetBurst?: number | undefined; + streamResetRate?: number | undefined; + Http1IncomingMessage?: Http1Request | undefined; + Http1ServerResponse?: Http1Response | undefined; + Http2ServerRequest?: Http2Request | undefined; + Http2ServerResponse?: Http2Response | undefined; + } + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + export interface SecureServerSessionOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends ServerSessionOptions, tls.TlsOptions {} + export interface ServerOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends ServerSessionOptions {} + export interface SecureServerOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends SecureServerSessionOptions { + allowHTTP1?: boolean | undefined; + origins?: string[] | undefined; + } + interface HTTP2ServerCommon { + setTimeout(msec?: number, callback?: () => void): this; + /** + * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. + * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. + */ + updateSettings(settings: Settings): void; + } + export interface Http2Server< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends net.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + addListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + addListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + addListener( + event: "sessionError", + listener: ( + err: Error, + session: ServerHttp2Session, + ) => void, + ): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit( + event: "checkContinue", + request: InstanceType, + response: InstanceType, + ): boolean; + emit(event: "request", request: InstanceType, response: InstanceType): boolean; + emit( + event: "session", + session: ServerHttp2Session, + ): boolean; + emit( + event: "sessionError", + err: Error, + session: ServerHttp2Session, + ): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + on( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + on( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + on( + event: "sessionError", + listener: ( + err: Error, + session: ServerHttp2Session, + ) => void, + ): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + once( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + once( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + once( + event: "sessionError", + listener: ( + err: Error, + session: ServerHttp2Session, + ) => void, + ): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + prependListener( + event: "sessionError", + listener: ( + err: Error, + session: ServerHttp2Session, + ) => void, + ): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependOnceListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + prependOnceListener( + event: "sessionError", + listener: ( + err: Error, + session: ServerHttp2Session, + ) => void, + ): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface Http2SecureServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends tls.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + addListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + addListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + addListener( + event: "sessionError", + listener: ( + err: Error, + session: ServerHttp2Session, + ) => void, + ): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit( + event: "checkContinue", + request: InstanceType, + response: InstanceType, + ): boolean; + emit(event: "request", request: InstanceType, response: InstanceType): boolean; + emit( + event: "session", + session: ServerHttp2Session, + ): boolean; + emit( + event: "sessionError", + err: Error, + session: ServerHttp2Session, + ): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + on( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + on( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + on( + event: "sessionError", + listener: ( + err: Error, + session: ServerHttp2Session, + ) => void, + ): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + once( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + once( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + once( + event: "sessionError", + listener: ( + err: Error, + session: ServerHttp2Session, + ) => void, + ): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + prependListener( + event: "sessionError", + listener: ( + err: Error, + session: ServerHttp2Session, + ) => void, + ): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependOnceListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + prependOnceListener( + event: "sessionError", + listener: ( + err: Error, + session: ServerHttp2Session, + ) => void, + ): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status, + * headers, and + * data. + * @since v8.4.0 + */ + export class Http2ServerRequest extends stream.Readable { + constructor( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + options: stream.ReadableOptions, + rawHeaders: readonly string[], + ); + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ + readonly aborted: boolean; + /** + * The request authority pseudo header field. Because HTTP/2 allows requests + * to set either `:authority` or `host`, this value is derived from `req.headers[':authority']` if present. Otherwise, it is derived from `req.headers['host']`. + * @since v8.4.0 + */ + readonly authority: string; + /** + * See `request.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * The `request.complete` property will be `true` if the request has + * been completed, aborted, or destroyed. + * @since v12.10.0 + */ + readonly complete: boolean; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * See `HTTP/2 Headers Object`. + * + * In HTTP/2, the request path, host name, protocol, and method are represented as + * special headers prefixed with the `:` character (e.g. `':path'`). These special + * headers will be included in the `request.headers` object. Care must be taken not + * to inadvertently modify these special headers or errors may occur. For instance, + * removing all headers from the request will cause errors to occur: + * + * ```js + * removeAllHeaders(request.headers); + * assert(request.url); // Fails because the :path header has been removed + * ``` + * @since v8.4.0 + */ + readonly headers: IncomingHttpHeaders; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. Returns `'2.0'`. + * + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. + * @since v8.4.0 + */ + readonly httpVersion: string; + readonly httpVersionMinor: number; + readonly httpVersionMajor: number; + /** + * The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. + * @since v8.4.0 + */ + readonly method: string; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v8.4.0 + */ + readonly rawHeaders: string[]; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly rawTrailers: string[]; + /** + * The request scheme pseudo header field indicating the scheme + * portion of the target URL. + * @since v8.4.0 + */ + readonly scheme: string; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `request.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `request.stream`. + * + * `setTimeout` method will be called on `request.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. With TLS support, + * use `request.socket.getPeerCertificate()` to obtain the client's + * authentication details. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the request. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly trailers: IncomingHttpHeaders; + /** + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. If the request is: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * Then `request.url` will be: + * + * ```js + * '/status?name=ryan' + * ``` + * + * To parse the url into its parts, `new URL()` can be used: + * + * ```console + * $ node + * > new URL('/status?name=ryan', 'http://example.com') + * URL { + * href: 'http://example.com/status?name=ryan', + * origin: 'http://example.com', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'example.com', + * hostname: 'example.com', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v8.4.0 + */ + url: string; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream`s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + read(size?: number): NonSharedBuffer | string | null; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted", hadError: boolean, code: number): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: NonSharedBuffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v8.4.0 + */ + export class Http2ServerResponse extends stream.Writable { + constructor(stream: ServerHttp2Stream); + /** + * See `response.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple times. + * + * If there were no previous values for the header, this is equivalent to calling {@link setHeader}. + * + * Attempting to set a header field name or value that contains invalid characters will result in a + * [TypeError](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-typeerror) being thrown. + * + * ```js + * // Returns headers including "set-cookie: a" and "set-cookie: b" + * const server = http2.createServer((req, res) => { + * res.setHeader('set-cookie', 'a'); + * res.appendHeader('set-cookie', 'b'); + * res.writeHead(200); + * res.end('ok'); + * }); + * ``` + * @since v20.12.0 + */ + appendHeader(name: string, value: string | string[]): void; + /** + * Boolean value that indicates whether the response has completed. Starts + * as `false`. After `response.end()` executes, the value will be `true`. + * @since v8.4.0 + * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. + */ + readonly finished: boolean; + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * A reference to the original HTTP2 `request` object. + * @since v15.7.0 + */ + readonly req: Request; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `response.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `response.stream`. + * + * `setTimeout` method will be called on `response.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer((req, res) => { + * const ip = req.socket.remoteAddress; + * const port = req.socket.remotePort; + * res.end(`Your IP address is ${ip} and your source port is ${port}.`); + * }).listen(3000); + * ``` + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the response. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * When true, the Date header will be automatically generated and sent in + * the response if it is not already present in the headers. Defaults to true. + * + * This should only be disabled for testing; HTTP requires the Date header + * in responses. + * @since v8.4.0 + */ + sendDate: boolean; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v8.4.0 + */ + statusCode: number; + /** + * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns + * an empty string. + * @since v8.4.0 + */ + statusMessage: ""; + /** + * This method adds HTTP trailing headers (a header but at the end of the + * message) to the response. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + addTrailers(trailers: OutgoingHttpHeaders): void; + /** + * This method signals to the server that all of the response headers and body + * have been sent; that server should consider this message complete. + * The method, `response.end()`, MUST be called on each response. + * + * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. + * + * If `callback` is specified, it will be called when the response stream + * is finished. + * @since v8.4.0 + */ + end(callback?: () => void): this; + end(data: string | Uint8Array, callback?: () => void): this; + end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): this; + /** + * Reads out a header that has already been queued but not sent to the client. + * The name is case-insensitive. + * + * ```js + * const contentType = response.getHeader('content-type'); + * ``` + * @since v8.4.0 + */ + getHeader(name: string): string; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All header names are lowercase. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = response.getHeaderNames(); + * // headerNames === ['foo', 'set-cookie'] + * ``` + * @since v8.4.0 + */ + getHeaderNames(): string[]; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow copy + * is used, array values may be mutated without additional calls to various + * header-related http module methods. The keys of the returned object are the + * header names and the values are the respective header values. All header names + * are lowercase. + * + * The object returned by the `response.getHeaders()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = response.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.4.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name matching is case-insensitive. + * + * ```js + * const hasContentType = response.hasHeader('content-type'); + * ``` + * @since v8.4.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that has been queued for implicit sending. + * + * ```js + * response.removeHeader('Content-Encoding'); + * ``` + * @since v8.4.0 + */ + removeHeader(name: string): void; + /** + * Sets a single header value for implicit headers. If this header already exists + * in the to-be-sent headers, its value will be replaced. Use an array of strings + * here to send multiple headers with the same name. + * + * ```js + * response.setHeader('Content-Type', 'text/html; charset=utf-8'); + * ``` + * + * or + * + * ```js + * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * @since v8.4.0 + */ + setHeader(name: string, value: number | string | readonly string[]): void; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * If this method is called and `response.writeHead()` has not been called, + * it will switch to implicit header mode and flush the implicit headers. + * + * This sends a chunk of the response body. This method may + * be called multiple times to provide successive parts of the body. + * + * In the `node:http` module, the response body is omitted when the + * request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body. + * + * `chunk` can be a string or a buffer. If `chunk` is a string, + * the second parameter specifies how to encode it into a byte stream. + * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk + * of data is flushed. + * + * This is the raw HTTP body and has nothing to do with higher-level multi-part + * body encodings that may be used. + * + * The first time `response.write()` is called, it will send the buffered + * header information and the first chunk of the body to the client. The second + * time `response.write()` is called, Node.js assumes data will be streamed, + * and sends the new data separately. That is, the response is buffered up to the + * first chunk of the body. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again. + * @since v8.4.0 + */ + write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; + /** + * Sends a status `100 Continue` to the client, indicating that the request body + * should be sent. See the `'checkContinue'` event on `Http2Server` and `Http2SecureServer`. + * @since v8.4.0 + */ + writeContinue(): void; + /** + * Sends a status `103 Early Hints` to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }); + * ``` + * @since v18.11.0 + */ + writeEarlyHints(hints: Record): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * + * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. + * + * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be + * passed as the second argument. However, because the `statusMessage` has no + * meaning within HTTP/2, the argument will have no effect and a process warning + * will be emitted. + * + * ```js + * const body = 'hello world'; + * response.writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain; charset=utf-8', + * }); + * ``` + * + * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a + * given encoding. On outbound messages, Node.js does not check if Content-Length + * and the length of the body being transmitted are equal or not. However, when + * receiving messages, Node.js will automatically reject messages when the `Content-Length` does not match the actual payload size. + * + * This method may be called at most one time on a message before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; + /** + * Call `http2stream.pushStream()` with the given headers, and wrap the + * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback + * parameter if successful. When `Http2ServerRequest` is closed, the callback is + * called with an error `ERR_HTTP2_INVALID_STREAM`. + * @since v8.4.0 + * @param headers An object describing the headers + * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of + * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method + */ + createPushResponse( + headers: OutgoingHttpHeaders, + callback: (err: Error | null, res: Http2ServerResponse) => void, + ): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + /** + * This symbol can be set as a property on the HTTP/2 headers object with + * an array value in order to provide a list of headers considered sensitive. + */ + export const sensitiveHeaders: symbol; + /** + * Returns an object containing the default settings for an `Http2Session` instance. This method returns a new object instance every time it is called + * so instances returned may be safely modified for use. + * @since v8.4.0 + */ + export function getDefaultSettings(): Settings; + /** + * Returns a `Buffer` instance containing serialized representation of the given + * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended + * for use with the `HTTP2-Settings` header field. + * + * ```js + * import http2 from 'node:http2'; + * + * const packed = http2.getPackedSettings({ enablePush: false }); + * + * console.log(packed.toString('base64')); + * // Prints: AAIAAAAA + * ``` + * @since v8.4.0 + */ + export function getPackedSettings(settings: Settings): NonSharedBuffer; + /** + * Returns a `HTTP/2 Settings Object` containing the deserialized settings from + * the given `Buffer` as generated by `http2.getPackedSettings()`. + * @since v8.4.0 + * @param buf The packed settings. + */ + export function getUnpackedSettings(buf: Uint8Array): Settings; + /** + * Returns a `net.Server` instance that creates and manages `Http2Session` instances. + * + * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when + * communicating + * with browser clients. + * + * ```js + * import http2 from 'node:http2'; + * + * // Create an unencrypted HTTP/2 server. + * // Since there are no browsers known that support + * // unencrypted HTTP/2, the use of `http2.createSecureServer()` + * // is necessary when communicating with browser clients. + * const server = http2.createServer(); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8000); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + export function createServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + options: ServerOptions, + onRequestHandler?: (request: InstanceType, response: InstanceType) => void, + ): Http2Server; + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session` instances. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * }; + * + * // Create a secure HTTP/2 server + * const server = http2.createSecureServer(options); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8443); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createSecureServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + export function createSecureServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + options: SecureServerOptions, + onRequestHandler?: (request: InstanceType, response: InstanceType) => void, + ): Http2SecureServer; + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * import http2 from 'node:http2'; + * const client = http2.connect('https://localhost:1234'); + * + * // Use the client + * + * client.close(); + * ``` + * @since v8.4.0 + * @param authority The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port + * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. + * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. + */ + export function connect( + authority: string | url.URL, + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + /** + * Create an HTTP/2 server session from an existing socket. + * @param socket A Duplex Stream + * @param options Any `{@link createServer}` options can be provided. + * @since v20.12.0 + */ + export function performServerHandshake< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + socket: stream.Duplex, + options?: ServerOptions, + ): ServerHttp2Session; +} +declare module "node:http2" { + export * from "http2"; +} diff --git a/node_modules/@types/node/https.d.ts b/node_modules/@types/node/https.d.ts new file mode 100644 index 0000000..e050255 --- /dev/null +++ b/node_modules/@types/node/https.d.ts @@ -0,0 +1,579 @@ +/** + * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a + * separate module. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/https.js) + */ +declare module "https" { + import { NonSharedBuffer } from "node:buffer"; + import { Duplex } from "node:stream"; + import * as tls from "node:tls"; + import * as http from "node:http"; + import { URL } from "node:url"; + interface ServerOptions< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends http.ServerOptions, tls.TlsOptions {} + interface RequestOptions extends http.RequestOptions, tls.SecureContextOptions { + checkServerIdentity?: + | ((hostname: string, cert: tls.DetailedPeerCertificate) => Error | undefined) + | undefined; + rejectUnauthorized?: boolean | undefined; // Defaults to true + servername?: string | undefined; // SNI TLS Extension + } + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + maxCachedSessions?: number | undefined; + } + /** + * An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information. + * @since v0.4.5 + */ + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + createConnection( + options: RequestOptions, + callback?: (err: Error | null, stream: Duplex) => void, + ): Duplex | null | undefined; + getName(options?: RequestOptions): string; + } + interface Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends http.Server {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor( + options: ServerOptions, + requestListener?: http.RequestListener, + ); + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Duplex) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: http.RequestListener): this; + addListener(event: "checkExpectation", listener: http.RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + addListener(event: "request", listener: http.RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "keylog", line: NonSharedBuffer, tlsSocket: tls.TLSSocket): boolean; + emit( + event: "newSession", + sessionId: NonSharedBuffer, + sessionData: NonSharedBuffer, + callback: () => void, + ): boolean; + emit( + event: "OCSPRequest", + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ): boolean; + emit( + event: "resumeSession", + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ): boolean; + emit(event: "secureConnection", tlsSocket: tls.TLSSocket): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: tls.TLSSocket): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Duplex): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType, + ): boolean; + emit(event: "clientError", err: Error, socket: Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: Duplex, head: NonSharedBuffer): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: Duplex, head: NonSharedBuffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this; + on( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + on( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Duplex) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: http.RequestListener): this; + on(event: "checkExpectation", listener: http.RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + on( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + on(event: "request", listener: http.RequestListener): this; + on( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Duplex) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: http.RequestListener): this; + once(event: "checkExpectation", listener: http.RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + once( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + once(event: "request", listener: http.RequestListener): this; + once( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Duplex) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: http.RequestListener): this; + prependListener(event: "checkExpectation", listener: http.RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + prependListener(event: "request", listener: http.RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Duplex) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: http.RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: http.RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + prependOnceListener(event: "request", listener: http.RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + } + /** + * ```js + * // curl -k https://localhost:8000/ + * import https from 'node:https'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * + * Or + * + * ```js + * import https from 'node:https'; + * import fs from 'node:fs'; + * + * const options = { + * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), + * passphrase: 'sample', + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * @since v0.3.4 + * @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`. + * @param requestListener A listener to be added to the `'request'` event. + */ + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + >(requestListener?: http.RequestListener): Server; + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + >( + options: ServerOptions, + requestListener?: http.RequestListener, + ): Server; + /** + * Makes a request to a secure web server. + * + * The following additional `options` from `tls.connect()` are also accepted: `ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`, `honorCipherOrder`, `key`, `passphrase`, + * `pfx`, `rejectUnauthorized`, `secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`, `highWaterMark`. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * import https from 'node:https'; + * + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * }; + * + * const req = https.request(options, (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(e); + * }); + * req.end(); + * ``` + * + * Example using options from `tls.connect()`: + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * options.agent = new https.Agent(options); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Alternatively, opt out of connection pooling by not using an `Agent`. + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * agent: false, + * }; + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('https://abc:xyz@example.com'); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): + * + * ```js + * import tls from 'node:tls'; + * import https from 'node:https'; + * import crypto from 'node:crypto'; + * + * function sha256(s) { + * return crypto.createHash('sha256').update(s).digest('base64'); + * } + * const options = { + * hostname: 'github.com', + * port: 443, + * path: '/', + * method: 'GET', + * checkServerIdentity: function(host, cert) { + * // Make sure the certificate is issued to the host we are connected to + * const err = tls.checkServerIdentity(host, cert); + * if (err) { + * return err; + * } + * + * // Pin the public key, similar to HPKP pin-sha256 pinning + * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; + * if (sha256(cert.pubkey) !== pubkey256) { + * const msg = 'Certificate verification error: ' + + * `The public key of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // Pin the exact certificate, rather than the pub key + * const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + + * 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; + * if (cert.fingerprint256 !== cert256) { + * const msg = 'Certificate verification error: ' + + * `The certificate of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // This loop is informational only. + * // Print the certificate and public key fingerprints of all certs in the + * // chain. Its common to pin the public key of the issuer on the public + * // internet, while pinning the public key of the service in sensitive + * // environments. + * do { + * console.log('Subject Common Name:', cert.subject.CN); + * console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); + * + * hash = crypto.createHash('sha256'); + * console.log(' Public key ping-sha256:', sha256(cert.pubkey)); + * + * lastprint256 = cert.fingerprint256; + * cert = cert.issuerCertificate; + * } while (cert.fingerprint256 !== lastprint256); + * + * }, + * }; + * + * options.agent = new https.Agent(options); + * const req = https.request(options, (res) => { + * console.log('All OK. Server matched our pinned cert or public key'); + * console.log('statusCode:', res.statusCode); + * // Print the HPKP values + * console.log('headers:', res.headers['public-key-pins']); + * + * res.on('data', (d) => {}); + * }); + * + * req.on('error', (e) => { + * console.error(e.message); + * }); + * req.end(); + * ``` + * + * Outputs for example: + * + * ```text + * Subject Common Name: github.com + * Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 + * Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= + * Subject Common Name: DigiCert SHA2 Extended Validation Server CA + * Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A + * Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= + * Subject Common Name: DigiCert High Assurance EV Root CA + * Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF + * Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= + * All OK. Server matched our pinned cert or public key + * statusCode: 200 + * headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; + * pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; + * pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains + * ``` + * @since v0.3.6 + * @param options Accepts all `options` from `request`, with some differences in default values: + */ + function request( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + /** + * Like `http.get()` but for HTTPS. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * ```js + * import https from 'node:https'; + * + * https.get('https://encrypted.google.com/', (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * + * }).on('error', (e) => { + * console.error(e); + * }); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. + */ + function get( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function get( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + let globalAgent: Agent; +} +declare module "node:https" { + export * from "https"; +} diff --git a/node_modules/@types/node/index.d.ts b/node_modules/@types/node/index.d.ts new file mode 100644 index 0000000..c9edbd7 --- /dev/null +++ b/node_modules/@types/node/index.d.ts @@ -0,0 +1,97 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +// NOTE: These definitions support Node.js and TypeScript 5.7+. + +// Reference required TypeScript libs: +/// + +// TypeScript backwards-compatibility definitions: +/// + +// Definitions specific to TypeScript 5.7+: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/node_modules/@types/node/inspector.d.ts b/node_modules/@types/node/inspector.d.ts new file mode 100644 index 0000000..1f1a6fe --- /dev/null +++ b/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,253 @@ +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/inspector.js) + */ +declare module "inspector" { + import EventEmitter = require("node:events"); + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend. + */ + constructor(); + /** + * Connects a session to the inspector back-end. + */ + connect(): void; + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + * @since v12.11.0 + */ + connectToMainThread(): void; + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * `session.connect()` will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + } + /** + * Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has + * started. + * + * If wait is `true`, will block until a client has connected to the inspect port + * and flow control has been passed to the debugger client. + * + * See the [security warning](https://nodejs.org/docs/latest-v22.x/api/cli.html#warning-binding-inspector-to-a-public-ipport-combination-is-insecure) + * regarding the `host` parameter usage. + * @param port Port to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param host Host to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param wait Block until a client has connected. Defaults to what was specified on the CLI. + * @returns Disposable that calls `inspector.close()`. + */ + function open(port?: number, host?: string, wait?: boolean): Disposable; + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + /** + * Return the URL of the active inspector, or `undefined` if there is none. + * + * ```console + * $ node --inspect -p 'inspector.url()' + * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * For help, see: https://nodejs.org/en/docs/inspector + * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * + * $ node --inspect=localhost:3000 -p 'inspector.url()' + * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * For help, see: https://nodejs.org/en/docs/inspector + * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * + * $ node -p 'inspector.url()' + * undefined + * ``` + */ + function url(): string | undefined; + /** + * Blocks until a client (existing or connected later) has sent `Runtime.runIfWaitingForDebugger` command. + * + * An exception will be thrown if there is no active inspector. + * @since v12.7.0 + */ + function waitForDebugger(): void; + // These methods are exposed by the V8 inspector console API (inspector/v8-console.h). + // The method signatures differ from those of the Node.js console, and are deliberately + // typed permissively. + interface InspectorConsole { + debug(...data: any[]): void; + error(...data: any[]): void; + info(...data: any[]): void; + log(...data: any[]): void; + warn(...data: any[]): void; + dir(...data: any[]): void; + dirxml(...data: any[]): void; + table(...data: any[]): void; + trace(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(...data: any[]): void; + clear(...data: any[]): void; + count(label?: any): void; + countReset(label?: any): void; + assert(value?: any, ...data: any[]): void; + profile(label?: any): void; + profileEnd(label?: any): void; + time(label?: any): void; + timeLog(label?: any): void; + timeStamp(label?: any): void; + } + /** + * An object to send messages to the remote inspector console. + * @since v11.0.0 + */ + const console: InspectorConsole; + // DevTools protocol event broadcast methods + namespace Network { + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.requestWillBeSent` event to connected frontends. This event indicates that + * the application is about to send an HTTP request. + * @since v22.6.0 + */ + function requestWillBeSent(params: RequestWillBeSentEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.dataReceived` event to connected frontends, or buffers the data if + * `Network.streamResourceContent` command was not invoked for the given request yet. + * + * Also enables `Network.getResponseBody` command to retrieve the response data. + * @since v22.17.0 + */ + function dataReceived(params: DataReceivedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Enables `Network.getRequestPostData` command to retrieve the request data. + * @since v22.18.0 + */ + function dataSent(params: unknown): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.responseReceived` event to connected frontends. This event indicates that + * HTTP response is available. + * @since v22.6.0 + */ + function responseReceived(params: ResponseReceivedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.loadingFinished` event to connected frontends. This event indicates that + * HTTP request has finished loading. + * @since v22.6.0 + */ + function loadingFinished(params: LoadingFinishedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.loadingFailed` event to connected frontends. This event indicates that + * HTTP request has failed to load. + * @since v22.7.0 + */ + function loadingFailed(params: LoadingFailedEventDataType): void; + } + namespace NetworkResources { + /** + * This feature is only available with the `--experimental-inspector-network-resource` flag enabled. + * + * The inspector.NetworkResources.put method is used to provide a response for a loadNetworkResource + * request issued via the Chrome DevTools Protocol (CDP). + * This is typically triggered when a source map is specified by URL, and a DevTools frontend—such as + * Chrome—requests the resource to retrieve the source map. + * + * This method allows developers to predefine the resource content to be served in response to such CDP requests. + * + * ```js + * const inspector = require('node:inspector'); + * // By preemptively calling put to register the resource, a source map can be resolved when + * // a loadNetworkResource request is made from the frontend. + * async function setNetworkResources() { + * const mapUrl = 'http://localhost:3000/dist/app.js.map'; + * const tsUrl = 'http://localhost:3000/src/app.ts'; + * const distAppJsMap = await fetch(mapUrl).then((res) => res.text()); + * const srcAppTs = await fetch(tsUrl).then((res) => res.text()); + * inspector.NetworkResources.put(mapUrl, distAppJsMap); + * inspector.NetworkResources.put(tsUrl, srcAppTs); + * }; + * setNetworkResources().then(() => { + * require('./dist/app'); + * }); + * ``` + * + * For more details, see the official CDP documentation: [Network.loadNetworkResource](https://chromedevtools.github.io/devtools-protocol/tot/Network/#method-loadNetworkResource) + * @since v22.19.0 + * @experimental + */ + function put(url: string, data: string): void; + } +} + +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + */ +declare module "node:inspector" { + export * from "inspector"; +} + +/** + * The `node:inspector/promises` module provides an API for interacting with the V8 + * inspector. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/inspector/promises.js) + * @since v19.0.0 + */ +declare module "inspector/promises" { + import EventEmitter = require("node:events"); + export { close, console, NetworkResources, open, url, waitForDebugger } from "inspector"; + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + * @since v19.0.0 + */ + export class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend. + */ + constructor(); + /** + * Connects a session to the inspector back-end. + */ + connect(): void; + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + * @since v12.11.0 + */ + connectToMainThread(): void; + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * `session.connect()` will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + } +} + +/** + * The `node:inspector/promises` module provides an API for interacting with the V8 + * inspector. + * @since v19.0.0 + */ +declare module "node:inspector/promises" { + export * from "inspector/promises"; +} diff --git a/node_modules/@types/node/inspector.generated.d.ts b/node_modules/@types/node/inspector.generated.d.ts new file mode 100644 index 0000000..bcf0b3b --- /dev/null +++ b/node_modules/@types/node/inspector.generated.d.ts @@ -0,0 +1,4052 @@ +// These definitions are automatically generated by the generate-inspector script. +// Do not edit this file directly. +// See scripts/generate-inspector/README.md for information on how to update the protocol definitions. +// Changes to the module itself should be added to the generator template (scripts/generate-inspector/inspector.d.ts.template). + +declare module "inspector" { + interface InspectorNotification { + method: string; + params: T; + } + + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string | undefined; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview | undefined; + /** + * @experimental + */ + customPreview?: CustomPreview | undefined; + } + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId | undefined; + } + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[] | undefined; + } + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + } + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean | undefined; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | undefined; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject | undefined; + } + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + } + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + } + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: object | undefined; + } + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId | undefined; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string | undefined; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace | undefined; + /** + * Exception object if available. + */ + exception?: RemoteObject | undefined; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId | undefined; + } + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string | undefined; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace | undefined; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId | undefined; + } + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId | undefined; + } + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + } + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId | undefined; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string | undefined; + } + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean | undefined; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean | undefined; + } + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace | undefined; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string | undefined; + } + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: object; + } + } + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + /** + * Call frame identifier. + */ + type CallFrameId = string; + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + } + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location | undefined; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject | undefined; + } + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string | undefined; + /** + * Location in the source code where scope starts + */ + startLocation?: Location | undefined; + /** + * Location in the source code where scope ends + */ + endLocation?: Location | undefined; + } + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + type?: string | undefined; + } + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string | undefined; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string | undefined; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location | undefined; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean | undefined; + } + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string | undefined; + } + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean | undefined; + } + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean | undefined; + } + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean | undefined; + } + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean | undefined; + } + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[] | undefined; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + } + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: object | undefined; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: object | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: object | undefined; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[] | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId | undefined; + } + } + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number | undefined; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number | undefined; + } + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number | undefined; + /** + * Child node ids. + */ + children?: number[] | undefined; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string | undefined; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[] | undefined; + } + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[] | undefined; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[] | undefined; + } + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean | undefined; + /** + * Collect block-based coverage. + */ + detailed?: boolean | undefined; + } + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + } + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean | undefined; + } + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean | undefined; + } + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean | undefined; + } + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + } + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number | undefined; + } + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean | undefined; + } + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string | undefined; + /** + * Included category filters. + */ + includedCategories: string[]; + } + interface StartParameterType { + traceConfig: TraceConfig; + } + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + interface DataCollectedEventDataType { + value: object[]; + } + } + namespace NodeWorker { + type WorkerID = string; + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + interface DetachParameterType { + sessionId: SessionID; + } + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + namespace Network { + /** + * Resource type as it was perceived by the rendering engine. + */ + type ResourceType = string; + /** + * Unique request identifier. + */ + type RequestId = string; + /** + * UTC time in seconds, counted from January 1, 1970. + */ + type TimeSinceEpoch = number; + /** + * Monotonically increasing time in seconds since an arbitrary point in the past. + */ + type MonotonicTime = number; + /** + * Information about the request initiator. + */ + interface Initiator { + /** + * Type of this initiator. + */ + type: string; + /** + * Initiator JavaScript stack trace, set for Script only. + * Requires the Debugger domain to be enabled. + */ + stack?: Runtime.StackTrace | undefined; + /** + * Initiator URL, set for Parser type or for Script type (when script is importing module) or for SignedExchange type. + */ + url?: string | undefined; + /** + * Initiator line number, set for Parser type or for Script type (when script is importing + * module) (0-based). + */ + lineNumber?: number | undefined; + /** + * Initiator column number, set for Parser type or for Script type (when script is importing + * module) (0-based). + */ + columnNumber?: number | undefined; + /** + * Set if another request triggered this request (e.g. preflight). + */ + requestId?: RequestId | undefined; + } + /** + * HTTP request data. + */ + interface Request { + url: string; + method: string; + headers: Headers; + hasPostData: boolean; + } + /** + * HTTP response data. + */ + interface Response { + url: string; + status: number; + statusText: string; + headers: Headers; + mimeType: string; + charset: string; + } + /** + * Request / response headers as keys / values of JSON object. + */ + interface Headers { + } + interface LoadNetworkResourcePageResult { + success: boolean; + stream?: IO.StreamHandle | undefined; + } + interface GetRequestPostDataParameterType { + /** + * Identifier of the network request to get content for. + */ + requestId: RequestId; + } + interface GetResponseBodyParameterType { + /** + * Identifier of the network request to get content for. + */ + requestId: RequestId; + } + interface StreamResourceContentParameterType { + /** + * Identifier of the request to stream. + */ + requestId: RequestId; + } + interface LoadNetworkResourceParameterType { + /** + * URL of the resource to get content for. + */ + url: string; + } + interface GetRequestPostDataReturnType { + /** + * Request body string, omitting files from multipart requests + */ + postData: string; + } + interface GetResponseBodyReturnType { + /** + * Response body. + */ + body: string; + /** + * True, if content was sent as base64. + */ + base64Encoded: boolean; + } + interface StreamResourceContentReturnType { + /** + * Data that has been buffered until streaming is enabled. + */ + bufferedData: string; + } + interface LoadNetworkResourceReturnType { + resource: LoadNetworkResourcePageResult; + } + interface RequestWillBeSentEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Request data. + */ + request: Request; + /** + * Request initiator. + */ + initiator: Initiator; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Timestamp. + */ + wallTime: TimeSinceEpoch; + } + interface ResponseReceivedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Resource type. + */ + type: ResourceType; + /** + * Response data. + */ + response: Response; + } + interface LoadingFailedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Resource type. + */ + type: ResourceType; + /** + * Error message. + */ + errorText: string; + } + interface LoadingFinishedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + } + interface DataReceivedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Data chunk length. + */ + dataLength: number; + /** + * Actual bytes received (might be less than dataLength for compressed encodings). + */ + encodedDataLength: number; + /** + * Data that was received. + * @experimental + */ + data?: string | undefined; + } + } + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + namespace Target { + type SessionID = string; + type TargetID = string; + interface TargetInfo { + targetId: TargetID; + type: string; + title: string; + url: string; + attached: boolean; + canAccessOpener: boolean; + } + interface SetAutoAttachParameterType { + autoAttach: boolean; + waitForDebuggerOnStart: boolean; + } + interface TargetCreatedEventDataType { + targetInfo: TargetInfo; + } + interface AttachedToTargetEventDataType { + sessionId: SessionID; + targetInfo: TargetInfo; + waitingForDebugger: boolean; + } + } + namespace IO { + type StreamHandle = string; + interface ReadParameterType { + /** + * Handle of the stream to read. + */ + handle: StreamHandle; + /** + * Seek to the specified offset before reading (if not specified, proceed with offset + * following the last read). Some types of streams may only support sequential reads. + */ + offset?: number | undefined; + /** + * Maximum number of bytes to read (left upon the agent discretion if not specified). + */ + size?: number | undefined; + } + interface CloseParameterType { + /** + * Handle of the stream to close. + */ + handle: StreamHandle; + } + interface ReadReturnType { + /** + * Data that were read. + */ + data: string; + /** + * Set if the end-of-file condition occurred while reading. + */ + eof: boolean; + } + } + + interface Session { + /** + * Posts a message to the inspector back-end. `callback` will be notified when + * a response is received. `callback` is a function that accepts two optional + * arguments: error and message-specific result. + * + * ```js + * session.post('Runtime.evaluate', { expression: '2 + 2' }, + * (error, { result }) => console.log(result)); + * // Output: { type: 'number', value: 4, description: '4' } + * ``` + * + * The latest version of the V8 inspector protocol is published on the + * [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + */ + post(method: string, callback?: (err: Error | null, params?: object) => void): void; + post(method: string, params?: object, callback?: (err: Error | null, params?: object) => void): void; + /** + * Returns supported domains. + */ + post(method: "Schema.getDomains", callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Evaluates expression on global object. + */ + post(method: "Runtime.evaluate", params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: "Runtime.evaluate", callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post(method: "Runtime.awaitPromise", params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: "Runtime.awaitPromise", callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.callFunctionOn", params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: "Runtime.callFunctionOn", callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.getProperties", params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: "Runtime.getProperties", callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + /** + * Releases remote object with given id. + */ + post(method: "Runtime.releaseObject", params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObject", callback?: (err: Error | null) => void): void; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: "Runtime.releaseObjectGroup", params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObjectGroup", callback?: (err: Error | null) => void): void; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: "Runtime.runIfWaitingForDebugger", callback?: (err: Error | null) => void): void; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: "Runtime.enable", callback?: (err: Error | null) => void): void; + /** + * Disables reporting of execution contexts creation. + */ + post(method: "Runtime.disable", callback?: (err: Error | null) => void): void; + /** + * Discards collected exceptions and console API calls. + */ + post(method: "Runtime.discardConsoleEntries", callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: "Runtime.setCustomObjectFormatterEnabled", params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.setCustomObjectFormatterEnabled", callback?: (err: Error | null) => void): void; + /** + * Compiles expression. + */ + post(method: "Runtime.compileScript", params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: "Runtime.compileScript", callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + /** + * Runs script with given id in a given context. + */ + post(method: "Runtime.runScript", params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: "Runtime.runScript", callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: "Runtime.queryObjects", params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: "Runtime.queryObjects", callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: "Runtime.globalLexicalScopeNames", + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: "Runtime.globalLexicalScopeNames", callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: "Debugger.enable", callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + /** + * Disables debugger for given page. + */ + post(method: "Debugger.disable", callback?: (err: Error | null) => void): void; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: "Debugger.setBreakpointsActive", params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBreakpointsActive", callback?: (err: Error | null) => void): void; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: "Debugger.setSkipAllPauses", params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setSkipAllPauses", callback?: (err: Error | null) => void): void; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: "Debugger.setBreakpointByUrl", params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: "Debugger.setBreakpointByUrl", callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: "Debugger.setBreakpoint", params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: "Debugger.setBreakpoint", callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + /** + * Removes JavaScript breakpoint. + */ + post(method: "Debugger.removeBreakpoint", params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.removeBreakpoint", callback?: (err: Error | null) => void): void; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: "Debugger.getPossibleBreakpoints", + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: "Debugger.getPossibleBreakpoints", callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + /** + * Continues execution until specific location is reached. + */ + post(method: "Debugger.continueToLocation", params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.continueToLocation", callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: "Debugger.pauseOnAsyncCall", params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.pauseOnAsyncCall", callback?: (err: Error | null) => void): void; + /** + * Steps over the statement. + */ + post(method: "Debugger.stepOver", callback?: (err: Error | null) => void): void; + /** + * Steps into the function call. + */ + post(method: "Debugger.stepInto", params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.stepInto", callback?: (err: Error | null) => void): void; + /** + * Steps out of the function call. + */ + post(method: "Debugger.stepOut", callback?: (err: Error | null) => void): void; + /** + * Stops on the next JavaScript statement. + */ + post(method: "Debugger.pause", callback?: (err: Error | null) => void): void; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: "Debugger.scheduleStepIntoAsync", callback?: (err: Error | null) => void): void; + /** + * Resumes JavaScript execution. + */ + post(method: "Debugger.resume", callback?: (err: Error | null) => void): void; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: "Debugger.getStackTrace", params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: "Debugger.getStackTrace", callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + /** + * Searches for given string in script content. + */ + post(method: "Debugger.searchInContent", params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: "Debugger.searchInContent", callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + /** + * Edits JavaScript source live. + */ + post(method: "Debugger.setScriptSource", params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: "Debugger.setScriptSource", callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + /** + * Restarts particular call frame from the beginning. + */ + post(method: "Debugger.restartFrame", params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: "Debugger.restartFrame", callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + /** + * Returns source for the script with given id. + */ + post(method: "Debugger.getScriptSource", params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: "Debugger.getScriptSource", callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: "Debugger.setPauseOnExceptions", params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setPauseOnExceptions", callback?: (err: Error | null) => void): void; + /** + * Evaluates expression on a given call frame. + */ + post(method: "Debugger.evaluateOnCallFrame", params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: "Debugger.evaluateOnCallFrame", callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: "Debugger.setVariableValue", params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setVariableValue", callback?: (err: Error | null) => void): void; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: "Debugger.setReturnValue", params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setReturnValue", callback?: (err: Error | null) => void): void; + /** + * Enables or disables async call stacks tracking. + */ + post(method: "Debugger.setAsyncCallStackDepth", params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setAsyncCallStackDepth", callback?: (err: Error | null) => void): void; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: "Debugger.setBlackboxPatterns", params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxPatterns", callback?: (err: Error | null) => void): void; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: "Debugger.setBlackboxedRanges", params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxedRanges", callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: "Console.enable", callback?: (err: Error | null) => void): void; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: "Console.disable", callback?: (err: Error | null) => void): void; + /** + * Does nothing. + */ + post(method: "Console.clearMessages", callback?: (err: Error | null) => void): void; + post(method: "Profiler.enable", callback?: (err: Error | null) => void): void; + post(method: "Profiler.disable", callback?: (err: Error | null) => void): void; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: "Profiler.setSamplingInterval", params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.setSamplingInterval", callback?: (err: Error | null) => void): void; + post(method: "Profiler.start", callback?: (err: Error | null) => void): void; + post(method: "Profiler.stop", callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: "Profiler.startPreciseCoverage", params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.startPreciseCoverage", callback?: (err: Error | null) => void): void; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: "Profiler.stopPreciseCoverage", callback?: (err: Error | null) => void): void; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: "Profiler.takePreciseCoverage", callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: "Profiler.getBestEffortCoverage", callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + post(method: "HeapProfiler.enable", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.disable", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startTrackingHeapObjects", params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startTrackingHeapObjects", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopTrackingHeapObjects", params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopTrackingHeapObjects", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.takeHeapSnapshot", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.collectGarbage", callback?: (err: Error | null) => void): void; + post( + method: "HeapProfiler.getObjectByHeapObjectId", + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: "HeapProfiler.getObjectByHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: "HeapProfiler.addInspectedHeapObject", params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.addInspectedHeapObject", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.getHeapObjectId", params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: "HeapProfiler.getHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: "HeapProfiler.startSampling", params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startSampling", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopSampling", callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + post(method: "HeapProfiler.getSamplingProfile", callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: "NodeTracing.getCategories", callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + /** + * Start trace events collection. + */ + post(method: "NodeTracing.start", params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeTracing.start", callback?: (err: Error | null) => void): void; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: "NodeTracing.stop", callback?: (err: Error | null) => void): void; + /** + * Sends protocol message over session with given id. + */ + post(method: "NodeWorker.sendMessageToWorker", params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.sendMessageToWorker", callback?: (err: Error | null) => void): void; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: "NodeWorker.enable", params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.enable", callback?: (err: Error | null) => void): void; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: "NodeWorker.disable", callback?: (err: Error | null) => void): void; + /** + * Detached from the worker with given sessionId. + */ + post(method: "NodeWorker.detach", params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.detach", callback?: (err: Error | null) => void): void; + /** + * Disables network tracking, prevents network events from being sent to the client. + */ + post(method: "Network.disable", callback?: (err: Error | null) => void): void; + /** + * Enables network tracking, network events will now be delivered to the client. + */ + post(method: "Network.enable", callback?: (err: Error | null) => void): void; + /** + * Returns post data sent with the request. Returns an error when no data was sent with the request. + */ + post(method: "Network.getRequestPostData", params?: Network.GetRequestPostDataParameterType, callback?: (err: Error | null, params: Network.GetRequestPostDataReturnType) => void): void; + post(method: "Network.getRequestPostData", callback?: (err: Error | null, params: Network.GetRequestPostDataReturnType) => void): void; + /** + * Returns content served for the given request. + */ + post(method: "Network.getResponseBody", params?: Network.GetResponseBodyParameterType, callback?: (err: Error | null, params: Network.GetResponseBodyReturnType) => void): void; + post(method: "Network.getResponseBody", callback?: (err: Error | null, params: Network.GetResponseBodyReturnType) => void): void; + /** + * Enables streaming of the response for the given requestId. + * If enabled, the dataReceived event contains the data that was received during streaming. + * @experimental + */ + post( + method: "Network.streamResourceContent", + params?: Network.StreamResourceContentParameterType, + callback?: (err: Error | null, params: Network.StreamResourceContentReturnType) => void + ): void; + post(method: "Network.streamResourceContent", callback?: (err: Error | null, params: Network.StreamResourceContentReturnType) => void): void; + /** + * Fetches the resource and returns the content. + */ + post(method: "Network.loadNetworkResource", params?: Network.LoadNetworkResourceParameterType, callback?: (err: Error | null, params: Network.LoadNetworkResourceReturnType) => void): void; + post(method: "Network.loadNetworkResource", callback?: (err: Error | null, params: Network.LoadNetworkResourceReturnType) => void): void; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.enable", callback?: (err: Error | null) => void): void; + /** + * Disable NodeRuntime events + */ + post(method: "NodeRuntime.disable", callback?: (err: Error | null) => void): void; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.notifyWhenWaitingForDisconnect", params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeRuntime.notifyWhenWaitingForDisconnect", callback?: (err: Error | null) => void): void; + post(method: "Target.setAutoAttach", params?: Target.SetAutoAttachParameterType, callback?: (err: Error | null) => void): void; + post(method: "Target.setAutoAttach", callback?: (err: Error | null) => void): void; + /** + * Read a chunk of the stream + */ + post(method: "IO.read", params?: IO.ReadParameterType, callback?: (err: Error | null, params: IO.ReadReturnType) => void): void; + post(method: "IO.read", callback?: (err: Error | null, params: IO.ReadReturnType) => void): void; + post(method: "IO.close", params?: IO.CloseParameterType, callback?: (err: Error | null) => void): void; + post(method: "IO.close", callback?: (err: Error | null) => void): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + addListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + addListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + addListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + addListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + addListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + addListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + addListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + addListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + addListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "inspectorNotification", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextCreated", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextsCleared"): boolean; + emit(event: "Runtime.exceptionThrown", message: InspectorNotification): boolean; + emit(event: "Runtime.exceptionRevoked", message: InspectorNotification): boolean; + emit(event: "Runtime.consoleAPICalled", message: InspectorNotification): boolean; + emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptParsed", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptFailedToParse", message: InspectorNotification): boolean; + emit(event: "Debugger.breakpointResolved", message: InspectorNotification): boolean; + emit(event: "Debugger.paused", message: InspectorNotification): boolean; + emit(event: "Debugger.resumed"): boolean; + emit(event: "Console.messageAdded", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileStarted", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileFinished", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.addHeapSnapshotChunk", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.resetProfiles"): boolean; + emit(event: "HeapProfiler.reportHeapSnapshotProgress", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.lastSeenObjectId", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.heapStatsUpdate", message: InspectorNotification): boolean; + emit(event: "NodeTracing.dataCollected", message: InspectorNotification): boolean; + emit(event: "NodeTracing.tracingComplete"): boolean; + emit(event: "NodeWorker.attachedToWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.detachedFromWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification): boolean; + emit(event: "Network.requestWillBeSent", message: InspectorNotification): boolean; + emit(event: "Network.responseReceived", message: InspectorNotification): boolean; + emit(event: "Network.loadingFailed", message: InspectorNotification): boolean; + emit(event: "Network.loadingFinished", message: InspectorNotification): boolean; + emit(event: "Network.dataReceived", message: InspectorNotification): boolean; + emit(event: "NodeRuntime.waitingForDisconnect"): boolean; + emit(event: "NodeRuntime.waitingForDebugger"): boolean; + emit(event: "Target.targetCreated", message: InspectorNotification): boolean; + emit(event: "Target.attachedToTarget", message: InspectorNotification): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + on(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.resetProfiles", listener: () => void): this; + on(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + on(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + on(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + on(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + on(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + on(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + on(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + on(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + once(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.resetProfiles", listener: () => void): this; + once(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + once(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + once(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + once(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + once(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + once(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + once(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + once(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + prependListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependOnceListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependOnceListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependOnceListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependOnceListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + prependOnceListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + } +} + +declare module "inspector/promises" { + export { + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + NodeTracing, + NodeWorker, + Network, + NodeRuntime, + Target, + IO, + } from 'inspector'; +} + +declare module "inspector/promises" { + import { + InspectorNotification, + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + NodeTracing, + NodeWorker, + Network, + NodeRuntime, + Target, + IO, + } from "inspector"; + + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + * @since v19.0.0 + */ + interface Session { + /** + * Posts a message to the inspector back-end. + * + * ```js + * import { Session } from 'node:inspector/promises'; + * try { + * const session = new Session(); + * session.connect(); + * const result = await session.post('Runtime.evaluate', { expression: '2 + 2' }); + * console.log(result); + * } catch (error) { + * console.error(error); + * } + * // Output: { result: { type: 'number', value: 4, description: '4' } } + * ``` + * + * The latest version of the V8 inspector protocol is published on the + * [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + */ + post(method: string, params?: object): Promise; + /** + * Returns supported domains. + */ + post(method: "Schema.getDomains"): Promise; + /** + * Evaluates expression on global object. + */ + post(method: "Runtime.evaluate", params?: Runtime.EvaluateParameterType): Promise; + /** + * Add handler to promise with given promise object id. + */ + post(method: "Runtime.awaitPromise", params?: Runtime.AwaitPromiseParameterType): Promise; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.callFunctionOn", params?: Runtime.CallFunctionOnParameterType): Promise; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.getProperties", params?: Runtime.GetPropertiesParameterType): Promise; + /** + * Releases remote object with given id. + */ + post(method: "Runtime.releaseObject", params?: Runtime.ReleaseObjectParameterType): Promise; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: "Runtime.releaseObjectGroup", params?: Runtime.ReleaseObjectGroupParameterType): Promise; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: "Runtime.runIfWaitingForDebugger"): Promise; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: "Runtime.enable"): Promise; + /** + * Disables reporting of execution contexts creation. + */ + post(method: "Runtime.disable"): Promise; + /** + * Discards collected exceptions and console API calls. + */ + post(method: "Runtime.discardConsoleEntries"): Promise; + /** + * @experimental + */ + post(method: "Runtime.setCustomObjectFormatterEnabled", params?: Runtime.SetCustomObjectFormatterEnabledParameterType): Promise; + /** + * Compiles expression. + */ + post(method: "Runtime.compileScript", params?: Runtime.CompileScriptParameterType): Promise; + /** + * Runs script with given id in a given context. + */ + post(method: "Runtime.runScript", params?: Runtime.RunScriptParameterType): Promise; + post(method: "Runtime.queryObjects", params?: Runtime.QueryObjectsParameterType): Promise; + /** + * Returns all let, const and class variables from global scope. + */ + post(method: "Runtime.globalLexicalScopeNames", params?: Runtime.GlobalLexicalScopeNamesParameterType): Promise; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: "Debugger.enable"): Promise; + /** + * Disables debugger for given page. + */ + post(method: "Debugger.disable"): Promise; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: "Debugger.setBreakpointsActive", params?: Debugger.SetBreakpointsActiveParameterType): Promise; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: "Debugger.setSkipAllPauses", params?: Debugger.SetSkipAllPausesParameterType): Promise; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: "Debugger.setBreakpointByUrl", params?: Debugger.SetBreakpointByUrlParameterType): Promise; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: "Debugger.setBreakpoint", params?: Debugger.SetBreakpointParameterType): Promise; + /** + * Removes JavaScript breakpoint. + */ + post(method: "Debugger.removeBreakpoint", params?: Debugger.RemoveBreakpointParameterType): Promise; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post(method: "Debugger.getPossibleBreakpoints", params?: Debugger.GetPossibleBreakpointsParameterType): Promise; + /** + * Continues execution until specific location is reached. + */ + post(method: "Debugger.continueToLocation", params?: Debugger.ContinueToLocationParameterType): Promise; + /** + * @experimental + */ + post(method: "Debugger.pauseOnAsyncCall", params?: Debugger.PauseOnAsyncCallParameterType): Promise; + /** + * Steps over the statement. + */ + post(method: "Debugger.stepOver"): Promise; + /** + * Steps into the function call. + */ + post(method: "Debugger.stepInto", params?: Debugger.StepIntoParameterType): Promise; + /** + * Steps out of the function call. + */ + post(method: "Debugger.stepOut"): Promise; + /** + * Stops on the next JavaScript statement. + */ + post(method: "Debugger.pause"): Promise; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: "Debugger.scheduleStepIntoAsync"): Promise; + /** + * Resumes JavaScript execution. + */ + post(method: "Debugger.resume"): Promise; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: "Debugger.getStackTrace", params?: Debugger.GetStackTraceParameterType): Promise; + /** + * Searches for given string in script content. + */ + post(method: "Debugger.searchInContent", params?: Debugger.SearchInContentParameterType): Promise; + /** + * Edits JavaScript source live. + */ + post(method: "Debugger.setScriptSource", params?: Debugger.SetScriptSourceParameterType): Promise; + /** + * Restarts particular call frame from the beginning. + */ + post(method: "Debugger.restartFrame", params?: Debugger.RestartFrameParameterType): Promise; + /** + * Returns source for the script with given id. + */ + post(method: "Debugger.getScriptSource", params?: Debugger.GetScriptSourceParameterType): Promise; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: "Debugger.setPauseOnExceptions", params?: Debugger.SetPauseOnExceptionsParameterType): Promise; + /** + * Evaluates expression on a given call frame. + */ + post(method: "Debugger.evaluateOnCallFrame", params?: Debugger.EvaluateOnCallFrameParameterType): Promise; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: "Debugger.setVariableValue", params?: Debugger.SetVariableValueParameterType): Promise; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: "Debugger.setReturnValue", params?: Debugger.SetReturnValueParameterType): Promise; + /** + * Enables or disables async call stacks tracking. + */ + post(method: "Debugger.setAsyncCallStackDepth", params?: Debugger.SetAsyncCallStackDepthParameterType): Promise; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: "Debugger.setBlackboxPatterns", params?: Debugger.SetBlackboxPatternsParameterType): Promise; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: "Debugger.setBlackboxedRanges", params?: Debugger.SetBlackboxedRangesParameterType): Promise; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: "Console.enable"): Promise; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: "Console.disable"): Promise; + /** + * Does nothing. + */ + post(method: "Console.clearMessages"): Promise; + post(method: "Profiler.enable"): Promise; + post(method: "Profiler.disable"): Promise; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: "Profiler.setSamplingInterval", params?: Profiler.SetSamplingIntervalParameterType): Promise; + post(method: "Profiler.start"): Promise; + post(method: "Profiler.stop"): Promise; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: "Profiler.startPreciseCoverage", params?: Profiler.StartPreciseCoverageParameterType): Promise; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: "Profiler.stopPreciseCoverage"): Promise; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: "Profiler.takePreciseCoverage"): Promise; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: "Profiler.getBestEffortCoverage"): Promise; + post(method: "HeapProfiler.enable"): Promise; + post(method: "HeapProfiler.disable"): Promise; + post(method: "HeapProfiler.startTrackingHeapObjects", params?: HeapProfiler.StartTrackingHeapObjectsParameterType): Promise; + post(method: "HeapProfiler.stopTrackingHeapObjects", params?: HeapProfiler.StopTrackingHeapObjectsParameterType): Promise; + post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType): Promise; + post(method: "HeapProfiler.collectGarbage"): Promise; + post(method: "HeapProfiler.getObjectByHeapObjectId", params?: HeapProfiler.GetObjectByHeapObjectIdParameterType): Promise; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: "HeapProfiler.addInspectedHeapObject", params?: HeapProfiler.AddInspectedHeapObjectParameterType): Promise; + post(method: "HeapProfiler.getHeapObjectId", params?: HeapProfiler.GetHeapObjectIdParameterType): Promise; + post(method: "HeapProfiler.startSampling", params?: HeapProfiler.StartSamplingParameterType): Promise; + post(method: "HeapProfiler.stopSampling"): Promise; + post(method: "HeapProfiler.getSamplingProfile"): Promise; + /** + * Gets supported tracing categories. + */ + post(method: "NodeTracing.getCategories"): Promise; + /** + * Start trace events collection. + */ + post(method: "NodeTracing.start", params?: NodeTracing.StartParameterType): Promise; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: "NodeTracing.stop"): Promise; + /** + * Sends protocol message over session with given id. + */ + post(method: "NodeWorker.sendMessageToWorker", params?: NodeWorker.SendMessageToWorkerParameterType): Promise; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: "NodeWorker.enable", params?: NodeWorker.EnableParameterType): Promise; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: "NodeWorker.disable"): Promise; + /** + * Detached from the worker with given sessionId. + */ + post(method: "NodeWorker.detach", params?: NodeWorker.DetachParameterType): Promise; + /** + * Disables network tracking, prevents network events from being sent to the client. + */ + post(method: "Network.disable"): Promise; + /** + * Enables network tracking, network events will now be delivered to the client. + */ + post(method: "Network.enable"): Promise; + /** + * Returns post data sent with the request. Returns an error when no data was sent with the request. + */ + post(method: "Network.getRequestPostData", params?: Network.GetRequestPostDataParameterType): Promise; + /** + * Returns content served for the given request. + */ + post(method: "Network.getResponseBody", params?: Network.GetResponseBodyParameterType): Promise; + /** + * Enables streaming of the response for the given requestId. + * If enabled, the dataReceived event contains the data that was received during streaming. + * @experimental + */ + post(method: "Network.streamResourceContent", params?: Network.StreamResourceContentParameterType): Promise; + /** + * Fetches the resource and returns the content. + */ + post(method: "Network.loadNetworkResource", params?: Network.LoadNetworkResourceParameterType): Promise; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.enable"): Promise; + /** + * Disable NodeRuntime events + */ + post(method: "NodeRuntime.disable"): Promise; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.notifyWhenWaitingForDisconnect", params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType): Promise; + post(method: "Target.setAutoAttach", params?: Target.SetAutoAttachParameterType): Promise; + /** + * Read a chunk of the stream + */ + post(method: "IO.read", params?: IO.ReadParameterType): Promise; + post(method: "IO.close", params?: IO.CloseParameterType): Promise; + + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + addListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + addListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + addListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + addListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + addListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + addListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + addListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + addListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + addListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "inspectorNotification", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextCreated", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextsCleared"): boolean; + emit(event: "Runtime.exceptionThrown", message: InspectorNotification): boolean; + emit(event: "Runtime.exceptionRevoked", message: InspectorNotification): boolean; + emit(event: "Runtime.consoleAPICalled", message: InspectorNotification): boolean; + emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptParsed", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptFailedToParse", message: InspectorNotification): boolean; + emit(event: "Debugger.breakpointResolved", message: InspectorNotification): boolean; + emit(event: "Debugger.paused", message: InspectorNotification): boolean; + emit(event: "Debugger.resumed"): boolean; + emit(event: "Console.messageAdded", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileStarted", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileFinished", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.addHeapSnapshotChunk", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.resetProfiles"): boolean; + emit(event: "HeapProfiler.reportHeapSnapshotProgress", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.lastSeenObjectId", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.heapStatsUpdate", message: InspectorNotification): boolean; + emit(event: "NodeTracing.dataCollected", message: InspectorNotification): boolean; + emit(event: "NodeTracing.tracingComplete"): boolean; + emit(event: "NodeWorker.attachedToWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.detachedFromWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification): boolean; + emit(event: "Network.requestWillBeSent", message: InspectorNotification): boolean; + emit(event: "Network.responseReceived", message: InspectorNotification): boolean; + emit(event: "Network.loadingFailed", message: InspectorNotification): boolean; + emit(event: "Network.loadingFinished", message: InspectorNotification): boolean; + emit(event: "Network.dataReceived", message: InspectorNotification): boolean; + emit(event: "NodeRuntime.waitingForDisconnect"): boolean; + emit(event: "NodeRuntime.waitingForDebugger"): boolean; + emit(event: "Target.targetCreated", message: InspectorNotification): boolean; + emit(event: "Target.attachedToTarget", message: InspectorNotification): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + on(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.resetProfiles", listener: () => void): this; + on(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + on(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + on(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + on(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + on(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + on(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + on(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + on(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + once(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.resetProfiles", listener: () => void): this; + once(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + once(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + once(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + once(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + once(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + once(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + once(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + once(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + prependListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependOnceListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependOnceListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependOnceListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependOnceListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + prependOnceListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + } +} diff --git a/node_modules/@types/node/module.d.ts b/node_modules/@types/node/module.d.ts new file mode 100644 index 0000000..b48948e --- /dev/null +++ b/node_modules/@types/node/module.d.ts @@ -0,0 +1,891 @@ +/** + * @since v0.3.7 + */ +declare module "module" { + import { URL } from "node:url"; + class Module { + constructor(id: string, parent?: Module); + } + interface Module extends NodeJS.Module {} + namespace Module { + export { Module }; + } + namespace Module { + /** + * A list of the names of all modules provided by Node.js. Can be used to verify + * if a module is maintained by a third party or not. + * + * Note: the list doesn't contain prefix-only modules like `node:test`. + * @since v9.3.0, v8.10.0, v6.13.0 + */ + const builtinModules: readonly string[]; + /** + * @since v12.2.0 + * @param path Filename to be used to construct the require + * function. Must be a file URL object, file URL string, or absolute path + * string. + */ + function createRequire(path: string | URL): NodeJS.Require; + namespace constants { + /** + * The following constants are returned as the `status` field in the object returned by + * {@link enableCompileCache} to indicate the result of the attempt to enable the + * [module compile cache](https://nodejs.org/docs/latest-v22.x/api/module.html#module-compile-cache). + * @since v22.8.0 + */ + namespace compileCacheStatus { + /** + * Node.js has enabled the compile cache successfully. The directory used to store the + * compile cache will be returned in the `directory` field in the + * returned object. + */ + const ENABLED: number; + /** + * The compile cache has already been enabled before, either by a previous call to + * {@link enableCompileCache}, or by the `NODE_COMPILE_CACHE=dir` + * environment variable. The directory used to store the + * compile cache will be returned in the `directory` field in the + * returned object. + */ + const ALREADY_ENABLED: number; + /** + * Node.js fails to enable the compile cache. This can be caused by the lack of + * permission to use the specified directory, or various kinds of file system errors. + * The detail of the failure will be returned in the `message` field in the + * returned object. + */ + const FAILED: number; + /** + * Node.js cannot enable the compile cache because the environment variable + * `NODE_DISABLE_COMPILE_CACHE=1` has been set. + */ + const DISABLED: number; + } + } + interface EnableCompileCacheResult { + /** + * One of the {@link constants.compileCacheStatus} + */ + status: number; + /** + * If Node.js cannot enable the compile cache, this contains + * the error message. Only set if `status` is `module.constants.compileCacheStatus.FAILED`. + */ + message?: string; + /** + * If the compile cache is enabled, this contains the directory + * where the compile cache is stored. Only set if `status` is + * `module.constants.compileCacheStatus.ENABLED` or + * `module.constants.compileCacheStatus.ALREADY_ENABLED`. + */ + directory?: string; + } + /** + * Enable [module compile cache](https://nodejs.org/docs/latest-v22.x/api/module.html#module-compile-cache) + * in the current Node.js instance. + * + * If `cacheDir` is not specified, Node.js will either use the directory specified by the + * `NODE_COMPILE_CACHE=dir` environment variable if it's set, or use + * `path.join(os.tmpdir(), 'node-compile-cache')` otherwise. For general use cases, it's + * recommended to call `module.enableCompileCache()` without specifying the `cacheDir`, + * so that the directory can be overridden by the `NODE_COMPILE_CACHE` environment + * variable when necessary. + * + * Since compile cache is supposed to be a quiet optimization that is not required for the + * application to be functional, this method is designed to not throw any exception when the + * compile cache cannot be enabled. Instead, it will return an object containing an error + * message in the `message` field to aid debugging. + * If compile cache is enabled successfully, the `directory` field in the returned object + * contains the path to the directory where the compile cache is stored. The `status` + * field in the returned object would be one of the `module.constants.compileCacheStatus` + * values to indicate the result of the attempt to enable the + * [module compile cache](https://nodejs.org/docs/latest-v22.x/api/module.html#module-compile-cache). + * + * This method only affects the current Node.js instance. To enable it in child worker threads, + * either call this method in child worker threads too, or set the + * `process.env.NODE_COMPILE_CACHE` value to compile cache directory so the behavior can + * be inherited into the child workers. The directory can be obtained either from the + * `directory` field returned by this method, or with {@link getCompileCacheDir}. + * @since v22.8.0 + * @param cacheDir Optional path to specify the directory where the compile cache + * will be stored/retrieved. + */ + function enableCompileCache(cacheDir?: string): EnableCompileCacheResult; + /** + * Flush the [module compile cache](https://nodejs.org/docs/latest-v22.x/api/module.html#module-compile-cache) + * accumulated from modules already loaded + * in the current Node.js instance to disk. This returns after all the flushing + * file system operations come to an end, no matter they succeed or not. If there + * are any errors, this will fail silently, since compile cache misses should not + * interfere with the actual operation of the application. + * @since v22.10.0 + */ + function flushCompileCache(): void; + /** + * @since v22.8.0 + * @return Path to the [module compile cache](https://nodejs.org/docs/latest-v22.x/api/module.html#module-compile-cache) + * directory if it is enabled, or `undefined` otherwise. + */ + function getCompileCacheDir(): string | undefined; + /** + * ```text + * /path/to/project + * ├ packages/ + * ├ bar/ + * ├ bar.js + * └ package.json // name = '@foo/bar' + * └ qux/ + * ├ node_modules/ + * └ some-package/ + * └ package.json // name = 'some-package' + * ├ qux.js + * └ package.json // name = '@foo/qux' + * ├ main.js + * └ package.json // name = '@foo' + * ``` + * ```js + * // /path/to/project/packages/bar/bar.js + * import { findPackageJSON } from 'node:module'; + * + * findPackageJSON('..', import.meta.url); + * // '/path/to/project/package.json' + * // Same result when passing an absolute specifier instead: + * findPackageJSON(new URL('../', import.meta.url)); + * findPackageJSON(import.meta.resolve('../')); + * + * findPackageJSON('some-package', import.meta.url); + * // '/path/to/project/packages/bar/node_modules/some-package/package.json' + * // When passing an absolute specifier, you might get a different result if the + * // resolved module is inside a subfolder that has nested `package.json`. + * findPackageJSON(import.meta.resolve('some-package')); + * // '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json' + * + * findPackageJSON('@foo/qux', import.meta.url); + * // '/path/to/project/packages/qux/package.json' + * ``` + * @since v22.14.0 + * @param specifier The specifier for the module whose `package.json` to + * retrieve. When passing a _bare specifier_, the `package.json` at the root of + * the package is returned. When passing a _relative specifier_ or an _absolute specifier_, + * the closest parent `package.json` is returned. + * @param base The absolute location (`file:` URL string or FS path) of the + * containing module. For CJS, use `__filename` (not `__dirname`!); for ESM, use + * `import.meta.url`. You do not need to pass it if `specifier` is an _absolute specifier_. + * @returns A path if the `package.json` is found. When `startLocation` + * is a package, the package's root `package.json`; when a relative or unresolved, the closest + * `package.json` to the `startLocation`. + */ + function findPackageJSON(specifier: string | URL, base?: string | URL): string | undefined; + /** + * @since v18.6.0, v16.17.0 + */ + function isBuiltin(moduleName: string): boolean; + interface RegisterOptions { + /** + * If you want to resolve `specifier` relative to a + * base URL, such as `import.meta.url`, you can pass that URL here. This + * property is ignored if the `parentURL` is supplied as the second argument. + * @default 'data:' + */ + parentURL?: string | URL | undefined; + /** + * Any arbitrary, cloneable JavaScript value to pass into the + * {@link initialize} hook. + */ + data?: Data | undefined; + /** + * [Transferable objects](https://nodejs.org/docs/latest-v22.x/api/worker_threads.html#portpostmessagevalue-transferlist) + * to be passed into the `initialize` hook. + */ + transferList?: any[] | undefined; + } + /* eslint-disable @definitelytyped/no-unnecessary-generics */ + /** + * Register a module that exports hooks that customize Node.js module + * resolution and loading behavior. See + * [Customization hooks](https://nodejs.org/docs/latest-v22.x/api/module.html#customization-hooks). + * + * This feature requires `--allow-worker` if used with the + * [Permission Model](https://nodejs.org/docs/latest-v22.x/api/permissions.html#permission-model). + * @since v20.6.0, v18.19.0 + * @param specifier Customization hooks to be registered; this should be + * the same string that would be passed to `import()`, except that if it is + * relative, it is resolved relative to `parentURL`. + * @param parentURL f you want to resolve `specifier` relative to a base + * URL, such as `import.meta.url`, you can pass that URL here. + */ + function register( + specifier: string | URL, + parentURL?: string | URL, + options?: RegisterOptions, + ): void; + function register(specifier: string | URL, options?: RegisterOptions): void; + interface RegisterHooksOptions { + /** + * See [load hook](https://nodejs.org/docs/latest-v22.x/api/module.html#loadurl-context-nextload). + * @default undefined + */ + load?: LoadHookSync | undefined; + /** + * See [resolve hook](https://nodejs.org/docs/latest-v22.x/api/module.html#resolvespecifier-context-nextresolve). + * @default undefined + */ + resolve?: ResolveHookSync | undefined; + } + interface ModuleHooks { + /** + * Deregister the hook instance. + */ + deregister(): void; + } + /** + * Register [hooks](https://nodejs.org/docs/latest-v22.x/api/module.html#customization-hooks) + * that customize Node.js module resolution and loading behavior. + * @since v22.15.0 + * @experimental + */ + function registerHooks(options: RegisterHooksOptions): ModuleHooks; + interface StripTypeScriptTypesOptions { + /** + * Possible values are: + * * `'strip'` Only strip type annotations without performing the transformation of TypeScript features. + * * `'transform'` Strip type annotations and transform TypeScript features to JavaScript. + * @default 'strip' + */ + mode?: "strip" | "transform" | undefined; + /** + * Only when `mode` is `'transform'`, if `true`, a source map + * will be generated for the transformed code. + * @default false + */ + sourceMap?: boolean | undefined; + /** + * Specifies the source url used in the source map. + */ + sourceUrl?: string | undefined; + } + /** + * `module.stripTypeScriptTypes()` removes type annotations from TypeScript code. It + * can be used to strip type annotations from TypeScript code before running it + * with `vm.runInContext()` or `vm.compileFunction()`. + * By default, it will throw an error if the code contains TypeScript features + * that require transformation such as `Enums`, + * see [type-stripping](https://nodejs.org/docs/latest-v22.x/api/typescript.md#type-stripping) for more information. + * When mode is `'transform'`, it also transforms TypeScript features to JavaScript, + * see [transform TypeScript features](https://nodejs.org/docs/latest-v22.x/api/typescript.md#typescript-features) for more information. + * When mode is `'strip'`, source maps are not generated, because locations are preserved. + * If `sourceMap` is provided, when mode is `'strip'`, an error will be thrown. + * + * _WARNING_: The output of this function should not be considered stable across Node.js versions, + * due to changes in the TypeScript parser. + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = 'const a: number = 1;'; + * const strippedCode = stripTypeScriptTypes(code); + * console.log(strippedCode); + * // Prints: const a = 1; + * ``` + * + * If `sourceUrl` is provided, it will be used appended as a comment at the end of the output: + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = 'const a: number = 1;'; + * const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' }); + * console.log(strippedCode); + * // Prints: const a = 1\n\n//# sourceURL=source.ts; + * ``` + * + * When `mode` is `'transform'`, the code is transformed to JavaScript: + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = ` + * namespace MathUtil { + * export const add = (a: number, b: number) => a + b; + * }`; + * const strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true }); + * console.log(strippedCode); + * // Prints: + * // var MathUtil; + * // (function(MathUtil) { + * // MathUtil.add = (a, b)=>a + b; + * // })(MathUtil || (MathUtil = {})); + * // # sourceMappingURL=data:application/json;base64, ... + * ``` + * @since v22.13.0 + * @param code The code to strip type annotations from. + * @returns The code with type annotations stripped. + */ + function stripTypeScriptTypes(code: string, options?: StripTypeScriptTypesOptions): string; + /* eslint-enable @definitelytyped/no-unnecessary-generics */ + /** + * The `module.syncBuiltinESMExports()` method updates all the live bindings for + * builtin `ES Modules` to match the properties of the `CommonJS` exports. It + * does not add or remove exported names from the `ES Modules`. + * + * ```js + * import fs from 'node:fs'; + * import assert from 'node:assert'; + * import { syncBuiltinESMExports } from 'node:module'; + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('node:fs').then((esmFS) => { + * // It syncs the existing readFile property with the new value + * assert.strictEqual(esmFS.readFile, newAPI); + * // readFileSync has been deleted from the required fs + * assert.strictEqual('readFileSync' in fs, false); + * // syncBuiltinESMExports() does not remove readFileSync from esmFS + * assert.strictEqual('readFileSync' in esmFS, true); + * // syncBuiltinESMExports() does not add names + * assert.strictEqual(esmFS.newAPI, undefined); + * }); + * ``` + * @since v12.12.0 + */ + function syncBuiltinESMExports(): void; + interface ImportAttributes extends NodeJS.Dict { + type?: string | undefined; + } + type ModuleFormat = + | "builtin" + | "commonjs" + | "commonjs-typescript" + | "json" + | "module" + | "module-typescript" + | "wasm"; + type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray; + /** + * The `initialize` hook provides a way to define a custom function that runs in + * the hooks thread when the hooks module is initialized. Initialization happens + * when the hooks module is registered via {@link register}. + * + * This hook can receive data from a {@link register} invocation, including + * ports and other transferable objects. The return value of `initialize` can be a + * `Promise`, in which case it will be awaited before the main application thread + * execution resumes. + */ + type InitializeHook = (data: Data) => void | Promise; + interface ResolveHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + /** + * The module importing this one, or undefined if this is the Node.js entry point + */ + parentURL: string | undefined; + } + interface ResolveFnOutput { + /** + * A hint to the load hook (it might be ignored); can be an intermediary value. + */ + format?: string | null | undefined; + /** + * The import attributes to use when caching the module (optional; if excluded the input will be used) + */ + importAttributes?: ImportAttributes | undefined; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The absolute URL to which this input resolves + */ + url: string; + } + /** + * The `resolve` hook chain is responsible for telling Node.js where to find and + * how to cache a given `import` statement or expression, or `require` call. It can + * optionally return a format (such as `'module'`) as a hint to the `load` hook. If + * a format is specified, the `load` hook is ultimately responsible for providing + * the final `format` value (and it is free to ignore the hint provided by + * `resolve`); if `resolve` provides a `format`, a custom `load` hook is required + * even if only to pass the value to the Node.js default `load` hook. + */ + type ResolveHook = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: Partial, + ) => ResolveFnOutput | Promise, + ) => ResolveFnOutput | Promise; + type ResolveHookSync = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: Partial, + ) => ResolveFnOutput, + ) => ResolveFnOutput; + interface LoadHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * The format optionally supplied by the `resolve` hook chain (can be an intermediary value). + */ + format: string | null | undefined; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + } + interface LoadFnOutput { + format: string | null | undefined; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The source for Node.js to evaluate + */ + source?: ModuleSource | undefined; + } + /** + * The `load` hook provides a way to define a custom method of determining how a + * URL should be interpreted, retrieved, and parsed. It is also in charge of + * validating the import attributes. + */ + type LoadHook = ( + url: string, + context: LoadHookContext, + nextLoad: ( + url: string, + context?: Partial, + ) => LoadFnOutput | Promise, + ) => LoadFnOutput | Promise; + type LoadHookSync = ( + url: string, + context: LoadHookContext, + nextLoad: ( + url: string, + context?: Partial, + ) => LoadFnOutput, + ) => LoadFnOutput; + interface SourceMapsSupport { + /** + * If the source maps support is enabled + */ + enabled: boolean; + /** + * If the support is enabled for files in `node_modules`. + */ + nodeModules: boolean; + /** + * If the support is enabled for generated code from `eval` or `new Function`. + */ + generatedCode: boolean; + } + /** + * This method returns whether the [Source Map v3](https://tc39.es/ecma426/) support for stack + * traces is enabled. + * @since v22.14.0 + */ + function getSourceMapsSupport(): SourceMapsSupport; + /** + * `path` is the resolved path for the file for which a corresponding source map + * should be fetched. + * @since v13.7.0, v12.17.0 + * @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise. + */ + function findSourceMap(path: string): SourceMap | undefined; + interface SetSourceMapsSupportOptions { + /** + * If enabling the support for files in `node_modules`. + * @default false + */ + nodeModules?: boolean | undefined; + /** + * If enabling the support for generated code from `eval` or `new Function`. + * @default false + */ + generatedCode?: boolean | undefined; + } + /** + * This function enables or disables the [Source Map v3](https://tc39.es/ecma426/) support for + * stack traces. + * + * It provides same features as launching Node.js process with commandline options + * `--enable-source-maps`, with additional options to alter the support for files + * in `node_modules` or generated codes. + * + * Only source maps in JavaScript files that are loaded after source maps has been + * enabled will be parsed and loaded. Preferably, use the commandline options + * `--enable-source-maps` to avoid losing track of source maps of modules loaded + * before this API call. + * @since v22.14.0 + */ + function setSourceMapsSupport(enabled: boolean, options?: SetSourceMapsSupportOptions): void; + interface SourceMapConstructorOptions { + /** + * @since v21.0.0, v20.5.0 + */ + lineLengths?: readonly number[] | undefined; + } + interface SourceMapPayload { + file: string; + version: number; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + sourceRoot: string; + } + interface SourceMapping { + generatedLine: number; + generatedColumn: number; + originalSource: string; + originalLine: number; + originalColumn: number; + } + interface SourceOrigin { + /** + * The name of the range in the source map, if one was provided + */ + name: string | undefined; + /** + * The file name of the original source, as reported in the SourceMap + */ + fileName: string; + /** + * The 1-indexed lineNumber of the corresponding call site in the original source + */ + lineNumber: number; + /** + * The 1-indexed columnNumber of the corresponding call site in the original source + */ + columnNumber: number; + } + /** + * @since v13.7.0, v12.17.0 + */ + class SourceMap { + constructor(payload: SourceMapPayload, options?: SourceMapConstructorOptions); + /** + * Getter for the payload used to construct the `SourceMap` instance. + */ + readonly payload: SourceMapPayload; + /** + * Given a line offset and column offset in the generated source + * file, returns an object representing the SourceMap range in the + * original file if found, or an empty object if not. + * + * The object returned contains the following keys: + * + * The returned value represents the raw range as it appears in the + * SourceMap, based on zero-indexed offsets, _not_ 1-indexed line and + * column numbers as they appear in Error messages and CallSite + * objects. + * + * To get the corresponding 1-indexed line and column numbers from a + * lineNumber and columnNumber as they are reported by Error stacks + * and CallSite objects, use `sourceMap.findOrigin(lineNumber, columnNumber)` + * @param lineOffset The zero-indexed line number offset in the generated source + * @param columnOffset The zero-indexed column number offset in the generated source + */ + findEntry(lineOffset: number, columnOffset: number): SourceMapping | {}; + /** + * Given a 1-indexed `lineNumber` and `columnNumber` from a call site in the generated source, + * find the corresponding call site location in the original source. + * + * If the `lineNumber` and `columnNumber` provided are not found in any source map, + * then an empty object is returned. + * @param lineNumber The 1-indexed line number of the call site in the generated source + * @param columnNumber The 1-indexed column number of the call site in the generated source + */ + findOrigin(lineNumber: number, columnNumber: number): SourceOrigin | {}; + } + function runMain(main?: string): void; + function wrap(script: string): string; + } + global { + interface ImportMeta { + /** + * The directory name of the current module. + * + * This is the same as the `path.dirname()` of the `import.meta.filename`. + * + * > **Caveat**: only present on `file:` modules. + * @since v21.2.0, v20.11.0 + */ + dirname: string; + /** + * The full absolute path and filename of the current module, with + * symlinks resolved. + * + * This is the same as the `url.fileURLToPath()` of the `import.meta.url`. + * + * > **Caveat** only local modules support this property. Modules not using the + * > `file:` protocol will not provide it. + * @since v21.2.0, v20.11.0 + */ + filename: string; + /** + * The absolute `file:` URL of the module. + * + * This is defined exactly the same as it is in browsers providing the URL of the + * current module file. + * + * This enables useful patterns such as relative file loading: + * + * ```js + * import { readFileSync } from 'node:fs'; + * const buffer = readFileSync(new URL('./data.proto', import.meta.url)); + * ``` + */ + url: string; + /** + * `import.meta.resolve` is a module-relative resolution function scoped to + * each module, returning the URL string. + * + * ```js + * const dependencyAsset = import.meta.resolve('component-lib/asset.css'); + * // file:///app/node_modules/component-lib/asset.css + * import.meta.resolve('./dep.js'); + * // file:///app/dep.js + * ``` + * + * All features of the Node.js module resolution are supported. Dependency + * resolutions are subject to the permitted exports resolutions within the package. + * + * **Caveats**: + * + * * This can result in synchronous file-system operations, which + * can impact performance similarly to `require.resolve`. + * * This feature is not available within custom loaders (it would + * create a deadlock). + * @since v13.9.0, v12.16.0 + * @param specifier The module specifier to resolve relative to the + * current module. + * @param parent An optional absolute parent module URL to resolve from. + * **Default:** `import.meta.url` + * @returns The absolute URL string that the specifier would resolve to. + */ + resolve(specifier: string, parent?: string | URL): string; + /** + * `true` when the current module is the entry point of the current process; `false` otherwise. + * + * Equivalent to `require.main === module` in CommonJS. + * + * Analogous to Python's `__name__ == "__main__"`. + * + * ```js + * export function foo() { + * return 'Hello, world'; + * } + * + * function main() { + * const message = foo(); + * console.log(message); + * } + * + * if (import.meta.main) main(); + * // `foo` can be imported from another module without possible side-effects from `main` + * ``` + * @since v22.18.0 + * @experimental + */ + main: boolean; + } + namespace NodeJS { + interface Module { + /** + * The module objects required for the first time by this one. + * @since v0.1.16 + */ + children: Module[]; + /** + * The `module.exports` object is created by the `Module` system. Sometimes this is + * not acceptable; many want their module to be an instance of some class. To do + * this, assign the desired export object to `module.exports`. + * @since v0.1.16 + */ + exports: any; + /** + * The fully resolved filename of the module. + * @since v0.1.16 + */ + filename: string; + /** + * The identifier for the module. Typically this is the fully resolved + * filename. + * @since v0.1.16 + */ + id: string; + /** + * `true` if the module is running during the Node.js preload + * phase. + * @since v15.4.0, v14.17.0 + */ + isPreloading: boolean; + /** + * Whether or not the module is done loading, or is in the process of + * loading. + * @since v0.1.16 + */ + loaded: boolean; + /** + * The module that first required this one, or `null` if the current module is the + * entry point of the current process, or `undefined` if the module was loaded by + * something that is not a CommonJS module (e.g. REPL or `import`). + * @since v0.1.16 + * @deprecated Please use `require.main` and `module.children` instead. + */ + parent: Module | null | undefined; + /** + * The directory name of the module. This is usually the same as the + * `path.dirname()` of the `module.id`. + * @since v11.14.0 + */ + path: string; + /** + * The search paths for the module. + * @since v0.4.0 + */ + paths: string[]; + /** + * The `module.require()` method provides a way to load a module as if + * `require()` was called from the original module. + * @since v0.5.1 + */ + require(id: string): any; + } + interface Require { + /** + * Used to import modules, `JSON`, and local files. + * @since v0.1.13 + */ + (id: string): any; + /** + * Modules are cached in this object when they are required. By deleting a key + * value from this object, the next `require` will reload the module. + * This does not apply to + * [native addons](https://nodejs.org/docs/latest-v22.x/api/addons.html), + * for which reloading will result in an error. + * @since v0.3.0 + */ + cache: Dict; + /** + * Instruct `require` on how to handle certain file extensions. + * @since v0.3.0 + * @deprecated + */ + extensions: RequireExtensions; + /** + * The `Module` object representing the entry script loaded when the Node.js + * process launched, or `undefined` if the entry point of the program is not a + * CommonJS module. + * @since v0.1.17 + */ + main: Module | undefined; + /** + * @since v0.3.0 + */ + resolve: RequireResolve; + } + /** @deprecated */ + interface RequireExtensions extends Dict<(module: Module, filename: string) => any> { + ".js": (module: Module, filename: string) => any; + ".json": (module: Module, filename: string) => any; + ".node": (module: Module, filename: string) => any; + } + interface RequireResolveOptions { + /** + * Paths to resolve module location from. If present, these + * paths are used instead of the default resolution paths, with the exception + * of + * [GLOBAL\_FOLDERS](https://nodejs.org/docs/latest-v22.x/api/modules.html#loading-from-the-global-folders) + * like `$HOME/.node_modules`, which are + * always included. Each of these paths is used as a starting point for + * the module resolution algorithm, meaning that the `node_modules` hierarchy + * is checked from this location. + * @since v8.9.0 + */ + paths?: string[] | undefined; + } + interface RequireResolve { + /** + * Use the internal `require()` machinery to look up the location of a module, + * but rather than loading the module, just return the resolved filename. + * + * If the module can not be found, a `MODULE_NOT_FOUND` error is thrown. + * @since v0.3.0 + * @param request The module path to resolve. + */ + (request: string, options?: RequireResolveOptions): string; + /** + * Returns an array containing the paths searched during resolution of `request` or + * `null` if the `request` string references a core module, for example `http` or + * `fs`. + * @since v8.9.0 + * @param request The module path whose lookup paths are being retrieved. + */ + paths(request: string): string[] | null; + } + } + /** + * The directory name of the current module. This is the same as the + * `path.dirname()` of the `__filename`. + * @since v0.1.27 + */ + var __dirname: string; + /** + * The file name of the current module. This is the current module file's absolute + * path with symlinks resolved. + * + * For a main program this is not necessarily the same as the file name used in the + * command line. + * @since v0.0.1 + */ + var __filename: string; + /** + * The `exports` variable is available within a module's file-level scope, and is + * assigned the value of `module.exports` before the module is evaluated. + * @since v0.1.16 + */ + var exports: NodeJS.Module["exports"]; + /** + * A reference to the current module. + * @since v0.1.16 + */ + var module: NodeJS.Module; + /** + * @since v0.1.13 + */ + var require: NodeJS.Require; + // Global-scope aliases for backwards compatibility with @types/node <13.0.x + /** @deprecated Use `NodeJS.Module` instead. */ + interface NodeModule extends NodeJS.Module {} + /** @deprecated Use `NodeJS.Require` instead. */ + interface NodeRequire extends NodeJS.Require {} + /** @deprecated Use `NodeJS.RequireResolve` instead. */ + interface RequireResolve extends NodeJS.RequireResolve {} + } + export = Module; +} +declare module "node:module" { + import module = require("module"); + export = module; +} diff --git a/node_modules/@types/node/net.d.ts b/node_modules/@types/node/net.d.ts new file mode 100644 index 0000000..41cc319 --- /dev/null +++ b/node_modules/@types/node/net.d.ts @@ -0,0 +1,1076 @@ +/** + * > Stability: 2 - Stable + * + * The `node:net` module provides an asynchronous network API for creating stream-based + * TCP or `IPC` servers ({@link createServer}) and clients + * ({@link createConnection}). + * + * It can be accessed using: + * + * ```js + * import net from 'node:net'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/net.js) + */ +declare module "net" { + import { NonSharedBuffer } from "node:buffer"; + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import * as dns from "node:dns"; + type LookupFunction = ( + hostname: string, + options: dns.LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | dns.LookupAddress[], family?: number) => void, + ) => void; + interface AddressInfo { + address: string; + family: string; + port: number; + } + interface SocketConstructorOpts { + fd?: number | undefined; + allowHalfOpen?: boolean | undefined; + onread?: OnReadOpts | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + signal?: AbortSignal | undefined; + } + interface OnReadOpts { + buffer: Uint8Array | (() => Uint8Array); + /** + * This function is called for every chunk of incoming data. + * Two arguments are passed to it: the number of bytes written to `buffer` and a reference to `buffer`. + * Return `false` from this function to implicitly `pause()` the socket. + */ + callback(bytesWritten: number, buffer: Uint8Array): boolean; + } + // TODO: remove empty ConnectOpts placeholder at next major @types/node version. + /** @deprecated */ + interface ConnectOpts {} + interface TcpSocketConnectOpts { + port: number; + host?: string | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + hints?: number | undefined; + family?: number | undefined; + lookup?: LookupFunction | undefined; + noDelay?: boolean | undefined; + keepAlive?: boolean | undefined; + keepAliveInitialDelay?: number | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamily?: boolean | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamilyAttemptTimeout?: number | undefined; + blockList?: BlockList | undefined; + } + interface IpcSocketConnectOpts { + path: string; + } + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + type SocketReadyState = "opening" | "open" | "readOnly" | "writeOnly" | "closed"; + /** + * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint + * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also + * an `EventEmitter`. + * + * A `net.Socket` can be created by the user and used directly to interact with + * a server. For example, it is returned by {@link createConnection}, + * so the user can use it to talk to the server. + * + * It can also be created by Node.js and passed to the user when a connection + * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use + * it to interact with the client. + * @since v0.3.4 + */ + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + /** + * Destroys the socket after all data is written. If the `finish` event was already emitted the socket is destroyed immediately. + * If the socket is still writable it implicitly calls `socket.end()`. + * @since v0.3.4 + */ + destroySoon(): void; + /** + * Sends data on the socket. The second parameter specifies the encoding in the + * case of a string. It defaults to UTF8 encoding. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. + * + * The optional `callback` parameter will be executed when the data is finally + * written out, which may not be immediately. + * + * See `Writable` stream `write()` method for more + * information. + * @since v0.1.90 + */ + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + /** + * Sends data on the socket, with an explicit encoding for string data. + * @see {@link Socket.write} for full details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + */ + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + /** + * Initiate a connection on a given socket. + * + * Possible signatures: + * + * * `socket.connect(options[, connectListener])` + * * `socket.connect(path[, connectListener])` for `IPC` connections. + * * `socket.connect(port[, host][, connectListener])` for TCP connections. + * * Returns: `net.Socket` The socket itself. + * + * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, + * instead of a `'connect'` event, an `'error'` event will be emitted with + * the error passed to the `'error'` listener. + * The last parameter `connectListener`, if supplied, will be added as a listener + * for the `'connect'` event **once**. + * + * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined + * behavior. + */ + connect(options: SocketConnectOpts, connectionListener?: () => void): this; + connect(port: number, host: string, connectionListener?: () => void): this; + connect(port: number, connectionListener?: () => void): this; + connect(path: string, connectionListener?: () => void): this; + /** + * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. + * @since v0.1.90 + * @return The socket itself. + */ + setEncoding(encoding?: BufferEncoding): this; + /** + * Pauses the reading of data. That is, `'data'` events will not be emitted. + * Useful to throttle back an upload. + * @return The socket itself. + */ + pause(): this; + /** + * Close the TCP connection by sending an RST packet and destroy the stream. + * If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected. + * Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. + * If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error. + * @since v18.3.0, v16.17.0 + */ + resetAndDestroy(): this; + /** + * Resumes reading after a call to `socket.pause()`. + * @return The socket itself. + */ + resume(): this; + /** + * Sets the socket to timeout after `timeout` milliseconds of inactivity on + * the socket. By default `net.Socket` do not have a timeout. + * + * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to + * end the connection. + * + * ```js + * socket.setTimeout(3000); + * socket.on('timeout', () => { + * console.log('socket timeout'); + * socket.end(); + * }); + * ``` + * + * If `timeout` is 0, then the existing idle timeout is disabled. + * + * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. + * @since v0.1.90 + * @return The socket itself. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Enable/disable the use of Nagle's algorithm. + * + * When a TCP connection is created, it will have Nagle's algorithm enabled. + * + * Nagle's algorithm delays data before it is sent via the network. It attempts + * to optimize throughput at the expense of latency. + * + * Passing `true` for `noDelay` or not passing an argument will disable Nagle's + * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's + * algorithm. + * @since v0.1.90 + * @param [noDelay=true] + * @return The socket itself. + */ + setNoDelay(noDelay?: boolean): this; + /** + * Enable/disable keep-alive functionality, and optionally set the initial + * delay before the first keepalive probe is sent on an idle socket. + * + * Set `initialDelay` (in milliseconds) to set the delay between the last + * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default + * (or previous) setting. + * + * Enabling the keep-alive functionality will set the following socket options: + * + * * `SO_KEEPALIVE=1` + * * `TCP_KEEPIDLE=initialDelay` + * * `TCP_KEEPCNT=10` + * * `TCP_KEEPINTVL=1` + * @since v0.1.92 + * @param [enable=false] + * @param [initialDelay=0] + * @return The socket itself. + */ + setKeepAlive(enable?: boolean, initialDelay?: number): this; + /** + * Returns the bound `address`, the address `family` name and `port` of the + * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + * @since v0.1.90 + */ + address(): AddressInfo | {}; + /** + * Calling `unref()` on a socket will allow the program to exit if this is the only + * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + unref(): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior). + * If the socket is `ref`ed calling `ref` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + ref(): this; + /** + * This property is only present if the family autoselection algorithm is enabled in `socket.connect(options)` + * and it is an array of the addresses that have been attempted. + * + * Each address is a string in the form of `$IP:$PORT`. + * If the connection was successful, then the last address is the one that the socket is currently connected to. + * @since v19.4.0 + */ + readonly autoSelectFamilyAttemptedAddresses: string[]; + /** + * This property shows the number of characters buffered for writing. The buffer + * may contain strings whose length after encoding is not yet known. So this number + * is only an approximation of the number of bytes in the buffer. + * + * `net.Socket` has the property that `socket.write()` always works. This is to + * help users get up and running quickly. The computer cannot always keep up + * with the amount of data that is written to a socket. The network connection + * simply might be too slow. Node.js will internally queue up the data written to a + * socket and send it out over the wire when it is possible. + * + * The consequence of this internal buffering is that memory may grow. + * Users who experience large or growing `bufferSize` should attempt to + * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. + * @since v0.3.8 + * @deprecated Since v14.6.0 - Use `writableLength` instead. + */ + readonly bufferSize: number; + /** + * The amount of received bytes. + * @since v0.5.3 + */ + readonly bytesRead: number; + /** + * The amount of bytes sent. + * @since v0.5.3 + */ + readonly bytesWritten: number; + /** + * If `true`, `socket.connect(options[, connectListener])` was + * called and has not yet finished. It will stay `true` until the socket becomes + * connected, then it is set to `false` and the `'connect'` event is emitted. Note + * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. + * @since v6.1.0 + */ + readonly connecting: boolean; + /** + * This is `true` if the socket is not connected yet, either because `.connect()`has not yet been called or because it is still in the process of connecting + * (see `socket.connecting`). + * @since v11.2.0, v10.16.0 + */ + readonly pending: boolean; + /** + * See `writable.destroyed` for further details. + */ + readonly destroyed: boolean; + /** + * The string representation of the local IP address the remote client is + * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client + * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. + * @since v0.9.6 + */ + readonly localAddress?: string; + /** + * The numeric representation of the local port. For example, `80` or `21`. + * @since v0.9.6 + */ + readonly localPort?: number; + /** + * The string representation of the local IP family. `'IPv4'` or `'IPv6'`. + * @since v18.8.0, v16.18.0 + */ + readonly localFamily?: string; + /** + * This property represents the state of the connection as a string. + * + * * If the stream is connecting `socket.readyState` is `opening`. + * * If the stream is readable and writable, it is `open`. + * * If the stream is readable and not writable, it is `readOnly`. + * * If the stream is not readable and writable, it is `writeOnly`. + * @since v0.5.0 + */ + readonly readyState: SocketReadyState; + /** + * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remoteAddress: string | undefined; + /** + * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.11.14 + */ + readonly remoteFamily: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remotePort: number | undefined; + /** + * The socket timeout in milliseconds as set by `socket.setTimeout()`. + * It is `undefined` if a timeout has not been set. + * @since v10.7.0 + */ + readonly timeout?: number; + /** + * Half-closes the socket. i.e., it sends a FIN packet. It is possible the + * server will still send some data. + * + * See `writable.end()` for further details. + * @since v0.1.90 + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(callback?: () => void): this; + /** + * Half-closes the socket, with one final chunk of data. + * @see {@link Socket.end} for full details. + * @since v0.1.90 + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(buffer: Uint8Array | string, callback?: () => void): this; + /** + * Half-closes the socket, with one final chunk of data. + * @see {@link Socket.end} for full details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. connectionAttempt + * 4. connectionAttemptFailed + * 5. connectionAttemptTimeout + * 6. data + * 7. drain + * 8. end + * 9. error + * 10. lookup + * 11. ready + * 12. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (hadError: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + addListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + addListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + addListener(event: "data", listener: (data: NonSharedBuffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "timeout", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", hadError: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "connectionAttempt", ip: string, port: number, family: number): boolean; + emit(event: "connectionAttemptFailed", ip: string, port: number, family: number, error: Error): boolean; + emit(event: "connectionAttemptTimeout", ip: string, port: number, family: number): boolean; + emit(event: "data", data: NonSharedBuffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "ready"): boolean; + emit(event: "timeout"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (hadError: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + on( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + on(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this; + on(event: "data", listener: (data: NonSharedBuffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + on(event: "ready", listener: () => void): this; + on(event: "timeout", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (hadError: boolean) => void): this; + once(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + once( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + once(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: NonSharedBuffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + once(event: "ready", listener: () => void): this; + once(event: "timeout", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (hadError: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + prependListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + prependListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependListener(event: "data", listener: (data: NonSharedBuffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (hadError: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener( + event: "connectionAttempt", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + prependOnceListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener(event: "data", listener: (data: NonSharedBuffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + interface ListenOptions extends Abortable { + backlog?: number | undefined; + exclusive?: boolean | undefined; + host?: string | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + reusePort?: boolean | undefined; + path?: string | undefined; + port?: number | undefined; + readableAll?: boolean | undefined; + writableAll?: boolean | undefined; + } + interface ServerOpts { + /** + * Indicates whether half-opened TCP connections are allowed. + * @default false + */ + allowHalfOpen?: boolean | undefined; + /** + * Indicates whether the socket should be paused on incoming connections. + * @default false + */ + pauseOnConnect?: boolean | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default false + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * Optionally overrides all `net.Socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * @default See [stream.getDefaultHighWaterMark()](https://nodejs.org/docs/latest-v22.x/api/stream.html#streamgetdefaulthighwatermarkobjectmode). + * @since v18.17.0, v20.1.0 + */ + highWaterMark?: number | undefined; + /** + * `blockList` can be used for disabling inbound + * access to specific IP addresses, IP ranges, or IP subnets. This does not + * work if the server is behind a reverse proxy, NAT, etc. because the address + * checked against the block list is the address of the proxy, or the one + * specified by the NAT. + * @since v22.13.0 + */ + blockList?: BlockList | undefined; + } + interface DropArgument { + localAddress?: string; + localPort?: number; + localFamily?: string; + remoteAddress?: string; + remotePort?: number; + remoteFamily?: string; + } + /** + * This class is used to create a TCP or `IPC` server. + * @since v0.1.90 + */ + class Server extends EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); + /** + * Start a server listening for connections. A `net.Server` can be a TCP or + * an `IPC` server depending on what it listens to. + * + * Possible signatures: + * + * * `server.listen(handle[, backlog][, callback])` + * * `server.listen(options[, callback])` + * * `server.listen(path[, backlog][, callback])` for `IPC` servers + * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + * + * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` + * event. + * + * All `listen()` methods can take a `backlog` parameter to specify the maximum + * length of the queue of pending connections. The actual length will be determined + * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn` on Linux. The default value of this parameter is 511 (not 512). + * + * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for + * details). + * + * The `server.listen()` method can be called again if and only if there was an + * error during the first `server.listen()` call or `server.close()` has been + * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + * + * One of the most common errors raised when listening is `EADDRINUSE`. + * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry + * after a certain amount of time: + * + * ```js + * server.on('error', (e) => { + * if (e.code === 'EADDRINUSE') { + * console.error('Address in use, retrying...'); + * setTimeout(() => { + * server.close(); + * server.listen(PORT, HOST); + * }, 1000); + * } + * }); + * ``` + */ + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, hostname?: string, listeningListener?: () => void): this; + listen(port?: number, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, listeningListener?: () => void): this; + listen(path: string, backlog?: number, listeningListener?: () => void): this; + listen(path: string, listeningListener?: () => void): this; + listen(options: ListenOptions, listeningListener?: () => void): this; + listen(handle: any, backlog?: number, listeningListener?: () => void): this; + listen(handle: any, listeningListener?: () => void): this; + /** + * Stops the server from accepting new connections and keeps existing + * connections. This function is asynchronous, the server is finally closed + * when all connections are ended and the server emits a `'close'` event. + * The optional `callback` will be called once the `'close'` event occurs. Unlike + * that event, it will be called with an `Error` as its only argument if the server + * was not open when it was closed. + * @since v0.1.90 + * @param callback Called when the server is closed. + */ + close(callback?: (err?: Error) => void): this; + /** + * Returns the bound `address`, the address `family` name, and `port` of the server + * as reported by the operating system if listening on an IP socket + * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. + * + * For a server listening on a pipe or Unix domain socket, the name is returned + * as a string. + * + * ```js + * const server = net.createServer((socket) => { + * socket.end('goodbye\n'); + * }).on('error', (err) => { + * // Handle errors here. + * throw err; + * }); + * + * // Grab an arbitrary unused port. + * server.listen(() => { + * console.log('opened server on', server.address()); + * }); + * ``` + * + * `server.address()` returns `null` before the `'listening'` event has been + * emitted or after calling `server.close()`. + * @since v0.1.90 + */ + address(): AddressInfo | string | null; + /** + * Asynchronously get the number of concurrent connections on the server. Works + * when sockets were sent to forks. + * + * Callback should take two arguments `err` and `count`. + * @since v0.9.7 + */ + getConnections(cb: (error: Error | null, count: number) => void): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will _not_ let the program exit if it's the only server left (the default behavior). + * If the server is `ref`ed calling `ref()` again will have no effect. + * @since v0.9.1 + */ + ref(): this; + /** + * Calling `unref()` on a server will allow the program to exit if this is the only + * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + */ + unref(): this; + /** + * Set this property to reject connections when the server's connection count gets + * high. + * + * It is not recommended to use this option once a socket has been sent to a child + * with `child_process.fork()`. + * @since v0.2.0 + */ + maxConnections: number; + connections: number; + /** + * Indicates whether or not the server is listening for connections. + * @since v5.7.0 + */ + readonly listening: boolean; + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + * 5. drop + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "drop", listener: (data?: DropArgument) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "drop", data?: DropArgument): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "drop", listener: (data?: DropArgument) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "drop", listener: (data?: DropArgument) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "drop", listener: (data?: DropArgument) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "drop", listener: (data?: DropArgument) => void): this; + /** + * Calls {@link Server.close()} and returns a promise that fulfills when the server has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } + type IPVersion = "ipv4" | "ipv6"; + /** + * The `BlockList` object can be used with some network APIs to specify rules for + * disabling inbound or outbound access to specific IP addresses, IP ranges, or + * IP subnets. + * @since v15.0.0, v14.18.0 + */ + class BlockList { + /** + * Adds a rule to block the given IP address. + * @since v15.0.0, v14.18.0 + * @param address An IPv4 or IPv6 address. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addAddress(address: string, type?: IPVersion): void; + addAddress(address: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). + * @since v15.0.0, v14.18.0 + * @param start The starting IPv4 or IPv6 address in the range. + * @param end The ending IPv4 or IPv6 address in the range. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addRange(start: string, end: string, type?: IPVersion): void; + addRange(start: SocketAddress, end: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses specified as a subnet mask. + * @since v15.0.0, v14.18.0 + * @param net The network IPv4 or IPv6 address. + * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addSubnet(net: SocketAddress, prefix: number): void; + addSubnet(net: string, prefix: number, type?: IPVersion): void; + /** + * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. + * + * ```js + * const blockList = new net.BlockList(); + * blockList.addAddress('123.123.123.123'); + * blockList.addRange('10.0.0.1', '10.0.0.10'); + * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); + * + * console.log(blockList.check('123.123.123.123')); // Prints: true + * console.log(blockList.check('10.0.0.3')); // Prints: true + * console.log(blockList.check('222.111.111.222')); // Prints: false + * + * // IPv6 notation for IPv4 addresses works: + * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true + * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true + * ``` + * @since v15.0.0, v14.18.0 + * @param address The IP address to check + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + check(address: SocketAddress): boolean; + check(address: string, type?: IPVersion): boolean; + /** + * The list of rules added to the blocklist. + * @since v15.0.0, v14.18.0 + */ + rules: readonly string[]; + /** + * Returns `true` if the `value` is a `net.BlockList`. + * @since v22.13.0 + * @param value Any JS value + */ + static isBlockList(value: unknown): value is BlockList; + /** + * ```js + * const blockList = new net.BlockList(); + * const data = [ + * 'Subnet: IPv4 192.168.1.0/24', + * 'Address: IPv4 10.0.0.5', + * 'Range: IPv4 192.168.2.1-192.168.2.10', + * 'Range: IPv4 10.0.0.1-10.0.0.10', + * ]; + * blockList.fromJSON(data); + * blockList.fromJSON(JSON.stringify(data)); + * ``` + * @since v22.19.0 + * @experimental + */ + fromJSON(data: string | readonly string[]): void; + /** + * @since v22.19.0 + * @experimental + */ + toJSON(): readonly string[]; + } + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + /** + * Creates a new TCP or `IPC` server. + * + * If `allowHalfOpen` is set to `true`, when the other end of the socket + * signals the end of transmission, the server will only send back the end of + * transmission when `socket.end()` is explicitly called. For example, in the + * context of TCP, when a FIN packed is received, a FIN packed is sent + * back only when `socket.end()` is explicitly called. Until then the + * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. + * + * If `pauseOnConnect` is set to `true`, then the socket associated with each + * incoming connection will be paused, and no data will be read from its handle. + * This allows connections to be passed between processes without any data being + * read by the original process. To begin reading data from a paused socket, call `socket.resume()`. + * + * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. + * + * Here is an example of a TCP echo server which listens for connections + * on port 8124: + * + * ```js + * import net from 'node:net'; + * const server = net.createServer((c) => { + * // 'connection' listener. + * console.log('client connected'); + * c.on('end', () => { + * console.log('client disconnected'); + * }); + * c.write('hello\r\n'); + * c.pipe(c); + * }); + * server.on('error', (err) => { + * throw err; + * }); + * server.listen(8124, () => { + * console.log('server bound'); + * }); + * ``` + * + * Test this by using `telnet`: + * + * ```bash + * telnet localhost 8124 + * ``` + * + * To listen on the socket `/tmp/echo.sock`: + * + * ```js + * server.listen('/tmp/echo.sock', () => { + * console.log('server bound'); + * }); + * ``` + * + * Use `nc` to connect to a Unix domain socket server: + * + * ```bash + * nc -U /tmp/echo.sock + * ``` + * @since v0.5.0 + * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. + */ + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; + /** + * Aliases to {@link createConnection}. + * + * Possible signatures: + * + * * {@link connect} + * * {@link connect} for `IPC` connections. + * * {@link connect} for TCP connections. + */ + function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; + function connect(port: number, host?: string, connectionListener?: () => void): Socket; + function connect(path: string, connectionListener?: () => void): Socket; + /** + * A factory function, which creates a new {@link Socket}, + * immediately initiates connection with `socket.connect()`, + * then returns the `net.Socket` that starts the connection. + * + * When the connection is established, a `'connect'` event will be emitted + * on the returned socket. The last parameter `connectListener`, if supplied, + * will be added as a listener for the `'connect'` event **once**. + * + * Possible signatures: + * + * * {@link createConnection} + * * {@link createConnection} for `IPC` connections. + * * {@link createConnection} for TCP connections. + * + * The {@link connect} function is an alias to this function. + */ + function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; + function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; + function createConnection(path: string, connectionListener?: () => void): Socket; + /** + * Gets the current default value of the `autoSelectFamily` option of `socket.connect(options)`. + * The initial default value is `true`, unless the command line option`--no-network-family-autoselection` is provided. + * @since v19.4.0 + */ + function getDefaultAutoSelectFamily(): boolean; + /** + * Sets the default value of the `autoSelectFamily` option of `socket.connect(options)`. + * @param value The new default value. + * The initial default value is `true`, unless the command line option + * `--no-network-family-autoselection` is provided. + * @since v19.4.0 + */ + function setDefaultAutoSelectFamily(value: boolean): void; + /** + * Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * The initial default value is `250` or the value specified via the command line option `--network-family-autoselection-attempt-timeout`. + * @returns The current default value of the `autoSelectFamilyAttemptTimeout` option. + * @since v19.8.0, v18.8.0 + */ + function getDefaultAutoSelectFamilyAttemptTimeout(): number; + /** + * Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * @param value The new default value, which must be a positive number. If the number is less than `10`, the value `10` is used instead. The initial default value is `250` or the value specified via the command line + * option `--network-family-autoselection-attempt-timeout`. + * @since v19.8.0, v18.8.0 + */ + function setDefaultAutoSelectFamilyAttemptTimeout(value: number): void; + /** + * Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4 + * address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`. + * + * ```js + * net.isIP('::1'); // returns 6 + * net.isIP('127.0.0.1'); // returns 4 + * net.isIP('127.000.000.001'); // returns 0 + * net.isIP('127.0.0.1/24'); // returns 0 + * net.isIP('fhqwhgads'); // returns 0 + * ``` + * @since v0.3.0 + */ + function isIP(input: string): number; + /** + * Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no + * leading zeroes. Otherwise, returns `false`. + * + * ```js + * net.isIPv4('127.0.0.1'); // returns true + * net.isIPv4('127.000.000.001'); // returns false + * net.isIPv4('127.0.0.1/24'); // returns false + * net.isIPv4('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv4(input: string): boolean; + /** + * Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`. + * + * ```js + * net.isIPv6('::1'); // returns true + * net.isIPv6('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv6(input: string): boolean; + interface SocketAddressInitOptions { + /** + * The network address as either an IPv4 or IPv6 string. + * @default 127.0.0.1 + */ + address?: string | undefined; + /** + * @default `'ipv4'` + */ + family?: IPVersion | undefined; + /** + * An IPv6 flow-label used only if `family` is `'ipv6'`. + * @default 0 + */ + flowlabel?: number | undefined; + /** + * An IP port. + * @default 0 + */ + port?: number | undefined; + } + /** + * @since v15.14.0, v14.18.0 + */ + class SocketAddress { + constructor(options: SocketAddressInitOptions); + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly address: string; + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly family: IPVersion; + /** + * @since v15.14.0, v14.18.0 + */ + readonly port: number; + /** + * @since v15.14.0, v14.18.0 + */ + readonly flowlabel: number; + /** + * @since v22.13.0 + * @param input An input string containing an IP address and optional port, + * e.g. `123.1.2.3:1234` or `[1::1]:1234`. + * @returns Returns a `SocketAddress` if parsing was successful. + * Otherwise returns `undefined`. + */ + static parse(input: string): SocketAddress | undefined; + } +} +declare module "node:net" { + export * from "net"; +} diff --git a/node_modules/@types/node/os.d.ts b/node_modules/@types/node/os.d.ts new file mode 100644 index 0000000..a40bd77 --- /dev/null +++ b/node_modules/@types/node/os.d.ts @@ -0,0 +1,506 @@ +/** + * The `node:os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * import os from 'node:os'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/os.js) + */ +declare module "os" { + import { NonSharedBuffer } from "buffer"; + interface CpuInfo { + model: string; + speed: number; + times: { + /** The number of milliseconds the CPU has spent in user mode. */ + user: number; + /** The number of milliseconds the CPU has spent in nice mode. */ + nice: number; + /** The number of milliseconds the CPU has spent in sys mode. */ + sys: number; + /** The number of milliseconds the CPU has spent in idle mode. */ + idle: number; + /** The number of milliseconds the CPU has spent in irq mode. */ + irq: number; + }; + } + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + scopeid?: number; + } + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + } + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T | null; + homedir: T; + } + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + /** + * Returns the host name of the operating system as a string. + * @since v0.3.3 + */ + function hostname(): string; + /** + * Returns an array containing the 1, 5, and 15 minute load averages. + * + * The load average is a measure of system activity calculated by the operating + * system and expressed as a fractional number. + * + * The load average is a Unix-specific concept. On Windows, the return value is + * always `[0, 0, 0]`. + * @since v0.3.3 + */ + function loadavg(): number[]; + /** + * Returns the system uptime in number of seconds. + * @since v0.3.3 + */ + function uptime(): number; + /** + * Returns the amount of free system memory in bytes as an integer. + * @since v0.3.3 + */ + function freemem(): number; + /** + * Returns the total amount of system memory in bytes as an integer. + * @since v0.3.3 + */ + function totalmem(): number; + /** + * Returns an array of objects containing information about each logical CPU core. + * The array will be empty if no CPU information is available, such as if the `/proc` file system is unavailable. + * + * The properties included on each object include: + * + * ```js + * [ + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 252020, + * nice: 0, + * sys: 30340, + * idle: 1070356870, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 306960, + * nice: 0, + * sys: 26980, + * idle: 1071569080, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 248450, + * nice: 0, + * sys: 21750, + * idle: 1070919370, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 256880, + * nice: 0, + * sys: 19430, + * idle: 1070905480, + * irq: 20, + * }, + * }, + * ] + * ``` + * + * `nice` values are POSIX-only. On Windows, the `nice` values of all processors + * are always 0. + * + * `os.cpus().length` should not be used to calculate the amount of parallelism + * available to an application. Use {@link availableParallelism} for this purpose. + * @since v0.3.3 + */ + function cpus(): CpuInfo[]; + /** + * Returns an estimate of the default amount of parallelism a program should use. + * Always returns a value greater than zero. + * + * This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism). + * @since v19.4.0, v18.14.0 + */ + function availableParallelism(): number; + /** + * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it + * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. + * + * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information + * about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. + * @since v0.3.3 + */ + function type(): string; + /** + * Returns the operating system as a string. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See + * [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v0.3.3 + */ + function release(): string; + /** + * Returns an object containing network interfaces that have been assigned a + * network address. + * + * Each key on the returned object identifies a network interface. The associated + * value is an array of objects that each describe an assigned network address. + * + * The properties available on the assigned network address object include: + * + * ```js + * { + * lo: [ + * { + * address: '127.0.0.1', + * netmask: '255.0.0.0', + * family: 'IPv4', + * mac: '00:00:00:00:00:00', + * internal: true, + * cidr: '127.0.0.1/8' + * }, + * { + * address: '::1', + * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', + * family: 'IPv6', + * mac: '00:00:00:00:00:00', + * scopeid: 0, + * internal: true, + * cidr: '::1/128' + * } + * ], + * eth0: [ + * { + * address: '192.168.1.108', + * netmask: '255.255.255.0', + * family: 'IPv4', + * mac: '01:02:03:0a:0b:0c', + * internal: false, + * cidr: '192.168.1.108/24' + * }, + * { + * address: 'fe80::a00:27ff:fe4e:66a1', + * netmask: 'ffff:ffff:ffff:ffff::', + * family: 'IPv6', + * mac: '01:02:03:0a:0b:0c', + * scopeid: 1, + * internal: false, + * cidr: 'fe80::a00:27ff:fe4e:66a1/64' + * } + * ] + * } + * ``` + * @since v0.6.0 + */ + function networkInterfaces(): NodeJS.Dict; + /** + * Returns the string path of the current user's home directory. + * + * On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it + * uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. + * + * On Windows, it uses the `USERPROFILE` environment variable if defined. + * Otherwise it uses the path to the profile directory of the current user. + * @since v2.3.0 + */ + function homedir(): string; + interface UserInfoOptions { + encoding?: BufferEncoding | "buffer" | undefined; + } + interface UserInfoOptionsWithBufferEncoding extends UserInfoOptions { + encoding: "buffer"; + } + interface UserInfoOptionsWithStringEncoding extends UserInfoOptions { + encoding?: BufferEncoding | undefined; + } + /** + * Returns information about the currently effective user. On POSIX platforms, + * this is typically a subset of the password file. The returned object includes + * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and `gid` fields are `-1`, and `shell` is `null`. + * + * The value of `homedir` returned by `os.userInfo()` is provided by the operating + * system. This differs from the result of `os.homedir()`, which queries + * environment variables for the home directory before falling back to the + * operating system response. + * + * Throws a [`SystemError`](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-systemerror) if a user has no `username` or `homedir`. + * @since v6.0.0 + */ + function userInfo(options?: UserInfoOptionsWithStringEncoding): UserInfo; + function userInfo(options: UserInfoOptionsWithBufferEncoding): UserInfo; + function userInfo(options: UserInfoOptions): UserInfo; + type SignalConstants = { + [key in NodeJS.Signals]: number; + }; + namespace constants { + const UV_UDP_REUSEADDR: number; + namespace signals {} + const signals: SignalConstants; + namespace errno { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EDQUOT: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const EMULTIHOP: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ESTALE: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + } + namespace dlopen { + const RTLD_LAZY: number; + const RTLD_NOW: number; + const RTLD_GLOBAL: number; + const RTLD_LOCAL: number; + const RTLD_DEEPBIND: number; + } + namespace priority { + const PRIORITY_LOW: number; + const PRIORITY_BELOW_NORMAL: number; + const PRIORITY_NORMAL: number; + const PRIORITY_ABOVE_NORMAL: number; + const PRIORITY_HIGH: number; + const PRIORITY_HIGHEST: number; + } + } + const devNull: string; + /** + * The operating system-specific end-of-line marker. + * * `\n` on POSIX + * * `\r\n` on Windows + */ + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, + * and `'x64'`. + * + * The return value is equivalent to [process.arch](https://nodejs.org/docs/latest-v22.x/api/process.html#processarch). + * @since v0.5.0 + */ + function arch(): string; + /** + * Returns a string identifying the kernel version. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v13.11.0, v12.17.0 + */ + function version(): string; + /** + * Returns a string identifying the operating system platform for which + * the Node.js binary was compiled. The value is set at compile time. + * Possible values are `'aix'`, `'darwin'`, `'freebsd'`, `'linux'`, `'openbsd'`, `'sunos'`, and `'win32'`. + * + * The return value is equivalent to `process.platform`. + * + * The value `'android'` may also be returned if Node.js is built on the Android + * operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.5.0 + */ + function platform(): NodeJS.Platform; + /** + * Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`, `mips`, `mips64`, `ppc64`, `ppc64le`, `s390`, `s390x`, `i386`, `i686`, `x86_64`. + * + * On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v18.9.0, v16.18.0 + */ + function machine(): string; + /** + * Returns the operating system's default directory for temporary files as a + * string. + * @since v0.9.9 + */ + function tmpdir(): string; + /** + * Returns a string identifying the endianness of the CPU for which the Node.js + * binary was compiled. + * + * Possible values are `'BE'` for big endian and `'LE'` for little endian. + * @since v0.9.4 + */ + function endianness(): "BE" | "LE"; + /** + * Returns the scheduling priority for the process specified by `pid`. If `pid` is + * not provided or is `0`, the priority of the current process is returned. + * @since v10.10.0 + * @param [pid=0] The process ID to retrieve scheduling priority for. + */ + function getPriority(pid?: number): number; + /** + * Attempts to set the scheduling priority for the process specified by `pid`. If `pid` is not provided or is `0`, the process ID of the current process is used. + * + * The `priority` input must be an integer between `-20` (high priority) and `19` (low priority). Due to differences between Unix priority levels and Windows + * priority classes, `priority` is mapped to one of six priority constants in `os.constants.priority`. When retrieving a process priority level, this range + * mapping may cause the return value to be slightly different on Windows. To avoid + * confusion, set `priority` to one of the priority constants. + * + * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user + * privileges. Otherwise the set priority will be silently reduced to `PRIORITY_HIGH`. + * @since v10.10.0 + * @param [pid=0] The process ID to set scheduling priority for. + * @param priority The scheduling priority to assign to the process. + */ + function setPriority(priority: number): void; + function setPriority(pid: number, priority: number): void; +} +declare module "node:os" { + export * from "os"; +} diff --git a/node_modules/@types/node/package.json b/node_modules/@types/node/package.json new file mode 100644 index 0000000..046a589 --- /dev/null +++ b/node_modules/@types/node/package.json @@ -0,0 +1,145 @@ +{ + "name": "@types/node", + "version": "22.19.19", + "description": "TypeScript definitions for node", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "license": "MIT", + "contributors": [ + { + "name": "Microsoft TypeScript", + "githubUsername": "Microsoft", + "url": "https://github.com/Microsoft" + }, + { + "name": "Alberto Schiabel", + "githubUsername": "jkomyno", + "url": "https://github.com/jkomyno" + }, + { + "name": "Andrew Makarov", + "githubUsername": "r3nya", + "url": "https://github.com/r3nya" + }, + { + "name": "Benjamin Toueg", + "githubUsername": "btoueg", + "url": "https://github.com/btoueg" + }, + { + "name": "David Junger", + "githubUsername": "touffy", + "url": "https://github.com/touffy" + }, + { + "name": "Mohsen Azimi", + "githubUsername": "mohsen1", + "url": "https://github.com/mohsen1" + }, + { + "name": "Nikita Galkin", + "githubUsername": "galkin", + "url": "https://github.com/galkin" + }, + { + "name": "Sebastian Silbermann", + "githubUsername": "eps1lon", + "url": "https://github.com/eps1lon" + }, + { + "name": "Wilco Bakker", + "githubUsername": "WilcoBakker", + "url": "https://github.com/WilcoBakker" + }, + { + "name": "Marcin Kopacz", + "githubUsername": "chyzwar", + "url": "https://github.com/chyzwar" + }, + { + "name": "Trivikram Kamat", + "githubUsername": "trivikr", + "url": "https://github.com/trivikr" + }, + { + "name": "Junxiao Shi", + "githubUsername": "yoursunny", + "url": "https://github.com/yoursunny" + }, + { + "name": "Ilia Baryshnikov", + "githubUsername": "qwelias", + "url": "https://github.com/qwelias" + }, + { + "name": "ExE Boss", + "githubUsername": "ExE-Boss", + "url": "https://github.com/ExE-Boss" + }, + { + "name": "Piotr Błażejewicz", + "githubUsername": "peterblazejewicz", + "url": "https://github.com/peterblazejewicz" + }, + { + "name": "Anna Henningsen", + "githubUsername": "addaleax", + "url": "https://github.com/addaleax" + }, + { + "name": "Victor Perin", + "githubUsername": "victorperin", + "url": "https://github.com/victorperin" + }, + { + "name": "NodeJS Contributors", + "githubUsername": "NodeJS", + "url": "https://github.com/NodeJS" + }, + { + "name": "Linus Unnebäck", + "githubUsername": "LinusU", + "url": "https://github.com/LinusU" + }, + { + "name": "wafuwafu13", + "githubUsername": "wafuwafu13", + "url": "https://github.com/wafuwafu13" + }, + { + "name": "Matteo Collina", + "githubUsername": "mcollina", + "url": "https://github.com/mcollina" + }, + { + "name": "Dmitry Semigradsky", + "githubUsername": "Semigradsky", + "url": "https://github.com/Semigradsky" + }, + { + "name": "René", + "githubUsername": "Renegade334", + "url": "https://github.com/Renegade334" + } + ], + "main": "", + "types": "index.d.ts", + "typesVersions": { + "<=5.6": { + "*": [ + "ts5.6/*" + ] + } + }, + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "dependencies": { + "undici-types": "~6.21.0" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "d4b6708cebe51e35cb2a49a7977a1d13cce88e81ad8d260e2602e6a0dad4037b", + "typeScriptVersion": "5.3" +} \ No newline at end of file diff --git a/node_modules/@types/node/path.d.ts b/node_modules/@types/node/path.d.ts new file mode 100644 index 0000000..b83d8f5 --- /dev/null +++ b/node_modules/@types/node/path.d.ts @@ -0,0 +1,200 @@ +declare module "path/posix" { + import path = require("path"); + export = path; +} +declare module "path/win32" { + import path = require("path"); + export = path; +} +/** + * The `node:path` module provides utilities for working with file and directory + * paths. It can be accessed using: + * + * ```js + * import path from 'node:path'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/path.js) + */ +declare module "path" { + namespace path { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string | undefined; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string | undefined; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string | undefined; + /** + * The file extension (if any) such as '.html' + */ + ext?: string | undefined; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string | undefined; + } + interface PlatformPath { + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. If the path is a zero-length string, '.' is returned, representing the current working directory. + * + * @param path string path to normalize. + * @throws {TypeError} if `path` is not a string. + */ + normalize(path: string): string; + /** + * Join all arguments together and normalize the resulting path. + * + * @param paths paths to join. + * @throws {TypeError} if any of the path segments is not a string. + */ + join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param paths A sequence of paths or path segments. + * @throws {TypeError} if any of the arguments is not a string. + */ + resolve(...paths: string[]): string; + /** + * The `path.matchesGlob()` method determines if `path` matches the `pattern`. + * @param path The path to glob-match against. + * @param pattern The glob to check the path against. + * @returns Whether or not the `path` matched the `pattern`. + * @throws {TypeError} if `path` or `pattern` are not strings. + * @since v22.5.0 + */ + matchesGlob(path: string, pattern: string): boolean; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * If the given {path} is a zero-length string, `false` will be returned. + * + * @param path path to test. + * @throws {TypeError} if `path` is not a string. + */ + isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to} based on the current working directory. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @throws {TypeError} if either `from` or `to` is not a string. + */ + relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + dirname(path: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param path the path to evaluate. + * @param suffix optionally, an extension to remove from the result. + * @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string. + */ + basename(path: string, suffix?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + extname(path: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + readonly sep: "\\" | "/"; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + readonly delimiter: ";" | ":"; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param path path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + parse(path: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathObject path to evaluate. + */ + format(pathObject: FormatInputPathObject): string; + /** + * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. + * If path is not a string, path will be returned without modifications. + * This method is meaningful only on Windows system. + * On POSIX systems, the method is non-operational and always returns path without modifications. + */ + toNamespacedPath(path: string): string; + /** + * Posix specific pathing. + * Same as parent object on posix. + */ + readonly posix: PlatformPath; + /** + * Windows specific pathing. + * Same as parent object on windows + */ + readonly win32: PlatformPath; + } + } + const path: path.PlatformPath; + export = path; +} +declare module "node:path" { + import path = require("path"); + export = path; +} +declare module "node:path/posix" { + import path = require("path/posix"); + export = path; +} +declare module "node:path/win32" { + import path = require("path/win32"); + export = path; +} diff --git a/node_modules/@types/node/perf_hooks.d.ts b/node_modules/@types/node/perf_hooks.d.ts new file mode 100644 index 0000000..ad0785d --- /dev/null +++ b/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,968 @@ +/** + * This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for + * Node.js-specific performance measurements. + * + * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): + * + * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) + * * [Performance Timeline](https://w3c.github.io/performance-timeline/) + * * [User Timing](https://www.w3.org/TR/user-timing/) + * * [Resource Timing](https://www.w3.org/TR/resource-timing-2/) + * + * ```js + * import { PerformanceObserver, performance } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((items) => { + * console.log(items.getEntries()[0].duration); + * performance.clearMarks(); + * }); + * obs.observe({ type: 'measure' }); + * performance.measure('Start to Now'); + * + * performance.mark('A'); + * doSomeLongRunningProcess(() => { + * performance.measure('A to Now', 'A'); + * + * performance.mark('B'); + * performance.measure('A to B', 'A', 'B'); + * }); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/perf_hooks.js) + */ +declare module "perf_hooks" { + import { AsyncResource } from "node:async_hooks"; + type EntryType = + | "dns" // Node.js only + | "function" // Node.js only + | "gc" // Node.js only + | "http2" // Node.js only + | "http" // Node.js only + | "mark" // available on the Web + | "measure" // available on the Web + | "net" // Node.js only + | "node" // Node.js only + | "resource"; // available on the Web + interface NodeGCPerformanceDetail { + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.kind` property identifies + * the type of garbage collection operation that occurred. + * See perf_hooks.constants for valid values. + */ + readonly kind: number; + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` + * property contains additional information about garbage collection operation. + * See perf_hooks.constants for valid values. + */ + readonly flags: number; + } + /** + * The constructor of this class is not exposed to users directly. + * @since v8.5.0 + */ + class PerformanceEntry { + protected constructor(); + /** + * The total number of milliseconds elapsed for this entry. This value will not + * be meaningful for all Performance Entry types. + * @since v8.5.0 + */ + readonly duration: number; + /** + * The name of the performance entry. + * @since v8.5.0 + */ + readonly name: string; + /** + * The high resolution millisecond timestamp marking the starting time of the + * Performance Entry. + * @since v8.5.0 + */ + readonly startTime: number; + /** + * The type of the performance entry. It may be one of: + * + * * `'node'` (Node.js only) + * * `'mark'` (available on the Web) + * * `'measure'` (available on the Web) + * * `'gc'` (Node.js only) + * * `'function'` (Node.js only) + * * `'http2'` (Node.js only) + * * `'http'` (Node.js only) + * @since v8.5.0 + */ + readonly entryType: EntryType; + toJSON(): any; + } + /** + * Exposes marks created via the `Performance.mark()` method. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMark extends PerformanceEntry { + readonly detail: any; + readonly duration: 0; + readonly entryType: "mark"; + } + /** + * Exposes measures created via the `Performance.measure()` method. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMeasure extends PerformanceEntry { + readonly detail: any; + readonly entryType: "measure"; + } + interface UVMetrics { + /** + * Number of event loop iterations. + */ + readonly loopCount: number; + /** + * Number of events that have been processed by the event handler. + */ + readonly events: number; + /** + * Number of events that were waiting to be processed when the event provider was called. + */ + readonly eventsWaiting: number; + } + // TODO: PerformanceNodeEntry is missing + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Provides timing details for Node.js itself. The constructor of this class + * is not exposed to users. + * @since v8.5.0 + */ + class PerformanceNodeTiming extends PerformanceEntry { + readonly entryType: "node"; + /** + * The high resolution millisecond timestamp at which the Node.js process + * completed bootstrapping. If bootstrapping has not yet finished, the property + * has the value of -1. + * @since v8.5.0 + */ + readonly bootstrapComplete: number; + /** + * The high resolution millisecond timestamp at which the Node.js environment was + * initialized. + * @since v8.5.0 + */ + readonly environment: number; + /** + * The high resolution millisecond timestamp of the amount of time the event loop + * has been idle within the event loop's event provider (e.g. `epoll_wait`). This + * does not take CPU usage into consideration. If the event loop has not yet + * started (e.g., in the first tick of the main script), the property has the + * value of 0. + * @since v14.10.0, v12.19.0 + */ + readonly idleTime: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * exited. If the event loop has not yet exited, the property has the value of -1\. + * It can only have a value of not -1 in a handler of the `'exit'` event. + * @since v8.5.0 + */ + readonly loopExit: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * started. If the event loop has not yet started (e.g., in the first tick of the + * main script), the property has the value of -1. + * @since v8.5.0 + */ + readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + * @since v8.5.0 + */ + readonly nodeStart: number; + /** + * This is a wrapper to the `uv_metrics_info` function. + * It returns the current set of event loop metrics. + * + * It is recommended to use this property inside a function whose execution was + * scheduled using `setImmediate` to avoid collecting metrics before finishing all + * operations scheduled during the current loop iteration. + * @since v22.8.0, v20.18.0 + */ + readonly uvMetricsInfo: UVMetrics; + /** + * The high resolution millisecond timestamp at which the V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + /** + * @param utilization1 The result of a previous call to `eventLoopUtilization()`. + * @param utilization2 The result of a previous call to `eventLoopUtilization()` prior to `utilization1`. + */ + type EventLoopUtilityFunction = ( + utilization1?: EventLoopUtilization, + utilization2?: EventLoopUtilization, + ) => EventLoopUtilization; + interface MarkOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * An optional timestamp to be used as the mark time. + * @default `performance.now()` + */ + startTime?: number | undefined; + } + interface MeasureOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown; + /** + * Duration between start and end times. + */ + duration?: number | undefined; + /** + * Timestamp to be used as the end time, or a string identifying a previously recorded mark. + */ + end?: number | string | undefined; + /** + * Timestamp to be used as the start time, or a string identifying a previously recorded mark. + */ + start?: number | string | undefined; + } + interface TimerifyOptions { + /** + * A histogram object created using `perf_hooks.createHistogram()` that will record runtime + * durations in nanoseconds. + */ + histogram?: RecordableHistogram | undefined; + } + interface Performance { + /** + * If `name` is not provided, removes all `PerformanceMark` objects from the Performance Timeline. + * If `name` is provided, removes only the named mark. + * @since v8.5.0 + */ + clearMarks(name?: string): void; + /** + * If `name` is not provided, removes all `PerformanceMeasure` objects from the Performance Timeline. + * If `name` is provided, removes only the named measure. + * @since v16.7.0 + */ + clearMeasures(name?: string): void; + /** + * If `name` is not provided, removes all `PerformanceResourceTiming` objects from the Resource Timeline. + * If `name` is provided, removes only the named resource. + * @since v18.2.0, v16.17.0 + */ + clearResourceTimings(name?: string): void; + /** + * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. + * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). + * No other CPU idle time is taken into consideration. + */ + eventLoopUtilization: EventLoopUtilityFunction; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. + * If you are only interested in performance entries of certain types or that have certain names, see + * `performance.getEntriesByType()` and `performance.getEntriesByName()`. + * @since v16.7.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.name` is equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to `type`. + * @param name + * @param type + * @since v16.7.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.entryType` is equal to `type`. + * @param type + * @since v16.7.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + /** + * Creates a new `PerformanceMark` entry in the Performance Timeline. + * A `PerformanceMark` is a subclass of `PerformanceEntry` whose `performanceEntry.entryType` is always `'mark'`, + * and whose `performanceEntry.duration` is always `0`. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * + * The created `PerformanceMark` entry is put in the global Performance Timeline and can be queried with + * `performance.getEntries`, `performance.getEntriesByName`, and `performance.getEntriesByType`. When the observation is + * performed, the entries should be cleared from the global Performance Timeline manually with `performance.clearMarks`. + * @param name + */ + mark(name: string, options?: MarkOptions): PerformanceMark; + /** + * Creates a new `PerformanceResourceTiming` entry in the Resource Timeline. + * A `PerformanceResourceTiming` is a subclass of `PerformanceEntry` whose `performanceEntry.entryType` is always `'resource'`. + * Performance resources are used to mark moments in the Resource Timeline. + * @param timingInfo [Fetch Timing Info](https://fetch.spec.whatwg.org/#fetch-timing-info) + * @param requestedUrl The resource url + * @param initiatorType The initiator name, e.g: 'fetch' + * @param global + * @param cacheMode The cache mode must be an empty string ('') or 'local' + * @param bodyInfo [Fetch Response Body Info](https://fetch.spec.whatwg.org/#response-body-info) + * @param responseStatus The response's status code + * @param deliveryType The delivery type. Default: ''. + * @since v18.2.0, v16.17.0 + */ + markResourceTiming( + timingInfo: object, + requestedUrl: string, + initiatorType: string, + global: object, + cacheMode: "" | "local", + bodyInfo: object, + responseStatus: number, + deliveryType?: string, + ): PerformanceResourceTiming; + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + * @return The PerformanceMeasure entry that was created + */ + measure(name: string, startMark?: string, endMark?: string): PerformanceMeasure; + measure(name: string, options: MeasureOptions): PerformanceMeasure; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * An instance of the `PerformanceNodeTiming` class that provides performance metrics for specific Node.js operational milestones. + * @since v8.5.0 + */ + readonly nodeTiming: PerformanceNodeTiming; + /** + * Returns the current high resolution millisecond timestamp, where 0 represents the start of the current `node` process. + * @since v8.5.0 + */ + now(): number; + /** + * Sets the global performance resource timing buffer size to the specified number of "resource" type performance entry objects. + * + * By default the max buffer size is set to 250. + * @since v18.8.0 + */ + setResourceTimingBufferSize(maxSize: number): void; + /** + * The [`timeOrigin`](https://w3c.github.io/hr-time/#dom-performance-timeorigin) specifies the high resolution millisecond timestamp + * at which the current `node` process began, measured in Unix time. + * @since v8.5.0 + */ + readonly timeOrigin: number; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Wraps a function within a new function that measures the running time of the wrapped function. + * A `PerformanceObserver` must be subscribed to the `'function'` event type in order for the timing details to be accessed. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * function someFunction() { + * console.log('hello world'); + * } + * + * const wrapped = performance.timerify(someFunction); + * + * const obs = new PerformanceObserver((list) => { + * console.log(list.getEntries()[0].duration); + * + * performance.clearMarks(); + * performance.clearMeasures(); + * obs.disconnect(); + * }); + * obs.observe({ entryTypes: ['function'] }); + * + * // A performance timeline entry will be created + * wrapped(); + * ``` + * + * If the wrapped function returns a promise, a finally handler will be attached to the promise and the duration will be reported + * once the finally handler is invoked. + * @param fn + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + /** + * An object which is JSON representation of the performance object. It is similar to + * [`window.performance.toJSON`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/toJSON) in browsers. + * @since v16.1.0 + */ + toJSON(): any; + } + class PerformanceObserverEntryList { + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime`. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0, + * * detail: null + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is + * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ entryTypes: ['mark', 'measure'] }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType` is equal to `type`. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0, + * * detail: null + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + } + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + /** + * @since v8.5.0 + */ + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + /** + * Disconnects the `PerformanceObserver` instance from all notifications. + * @since v8.5.0 + */ + disconnect(): void; + /** + * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes` or `options.type`: + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((list, observer) => { + * // Called once asynchronously. `list` contains three items. + * }); + * obs.observe({ type: 'mark' }); + * + * for (let n = 0; n < 3; n++) + * performance.mark(`test${n}`); + * ``` + * @since v8.5.0 + */ + observe( + options: + | { + entryTypes: readonly EntryType[]; + buffered?: boolean | undefined; + } + | { + type: EntryType; + buffered?: boolean | undefined; + }, + ): void; + /** + * @since v16.0.0 + * @returns Current list of entries stored in the performance observer, emptying it out. + */ + takeRecords(): PerformanceEntry[]; + } + /** + * Provides detailed network timing data regarding the loading of an application's resources. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceResourceTiming extends PerformanceEntry { + readonly entryType: "resource"; + protected constructor(); + /** + * The high resolution millisecond timestamp at immediately before dispatching the `fetch` + * request. If the resource is not intercepted by a worker the property will always return 0. + * @since v18.2.0, v16.17.0 + */ + readonly workerStart: number; + /** + * The high resolution millisecond timestamp that represents the start time of the fetch which + * initiates the redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectStart: number; + /** + * The high resolution millisecond timestamp that will be created immediately after receiving + * the last byte of the response of the last redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectEnd: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts to fetch the resource. + * @since v18.2.0, v16.17.0 + */ + readonly fetchStart: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts the domain name lookup + * for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after the Node.js finished + * the domain name lookup for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts to + * establish the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js finishes + * establishing the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts the + * handshake process to secure the current connection. + * @since v18.2.0, v16.17.0 + */ + readonly secureConnectionStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js receives the + * first byte of the response from the server. + * @since v18.2.0, v16.17.0 + */ + readonly requestStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js receives the + * last byte of the resource or immediately before the transport connection is closed, whichever comes first. + * @since v18.2.0, v16.17.0 + */ + readonly responseEnd: number; + /** + * A number representing the size (in octets) of the fetched resource. The size includes the response header + * fields plus the response payload body. + * @since v18.2.0, v16.17.0 + */ + readonly transferSize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the payload body, before + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly encodedBodySize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the message body, after + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly decodedBodySize: number; + /** + * Returns a `object` that is the JSON representation of the `PerformanceResourceTiming` object + * @since v18.2.0, v16.17.0 + */ + toJSON(): any; + } + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + const NODE_PERFORMANCE_GC_FLAGS_NO: number; + const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; + const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; + const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; + const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; + } + const performance: Performance; + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number | undefined; + } + interface Histogram { + /** + * The number of samples recorded by the histogram. + * @since v17.4.0, v16.14.0 + */ + readonly count: number; + /** + * The number of samples recorded by the histogram. + * v17.4.0, v16.14.0 + */ + readonly countBigInt: bigint; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event + * loop delay threshold. + * @since v11.10.0 + */ + readonly exceeds: number; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold. + * @since v17.4.0, v16.14.0 + */ + readonly exceedsBigInt: bigint; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The maximum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly maxBigInt: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The minimum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly minBigInt: bigint; + /** + * Returns the value at the given percentile. + * @since v11.10.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentile(percentile: number): number; + /** + * Returns the value at the given percentile. + * @since v17.4.0, v16.14.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentileBigInt(percentile: number): bigint; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v17.4.0, v16.14.0 + */ + readonly percentilesBigInt: Map; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + } + interface IntervalHistogram extends Histogram { + /** + * Enables the update interval timer. Returns `true` if the timer was + * started, `false` if it was already started. + * @since v11.10.0 + */ + enable(): boolean; + /** + * Disables the update interval timer. Returns `true` if the timer was + * stopped, `false` if it was already stopped. + * @since v11.10.0 + */ + disable(): boolean; + } + interface RecordableHistogram extends Histogram { + /** + * @since v15.9.0, v14.18.0 + * @param val The amount to record in the histogram. + */ + record(val: number | bigint): void; + /** + * Calculates the amount of time (in nanoseconds) that has passed since the + * previous call to `recordDelta()` and records that amount in the histogram. + * @since v15.9.0, v14.18.0 + */ + recordDelta(): void; + /** + * Adds the values from `other` to this histogram. + * @since v17.4.0, v16.14.0 + */ + add(other: RecordableHistogram): void; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Creates an `IntervalHistogram` object that samples and reports the event loop + * delay over time. The delays will be reported in nanoseconds. + * + * Using a timer to detect approximate event loop delay works because the + * execution of timers is tied specifically to the lifecycle of the libuv + * event loop. That is, a delay in the loop will cause a delay in the execution + * of the timer, and those delays are specifically what this API is intended to + * detect. + * + * ```js + * import { monitorEventLoopDelay } from 'node:perf_hooks'; + * const h = monitorEventLoopDelay({ resolution: 20 }); + * h.enable(); + * // Do something. + * h.disable(); + * console.log(h.min); + * console.log(h.max); + * console.log(h.mean); + * console.log(h.stddev); + * console.log(h.percentiles); + * console.log(h.percentile(50)); + * console.log(h.percentile(99)); + * ``` + * @since v11.10.0 + */ + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + interface CreateHistogramOptions { + /** + * The minimum recordable value. Must be an integer value greater than 0. + * @default 1 + */ + lowest?: number | bigint | undefined; + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + highest?: number | bigint | undefined; + /** + * The number of accuracy digits. Must be a number between 1 and 5. + * @default 3 + */ + figures?: number | undefined; + } + /** + * Returns a `RecordableHistogram`. + * @since v15.9.0, v14.18.0 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; + import { + performance as _performance, + PerformanceEntry as _PerformanceEntry, + PerformanceMark as _PerformanceMark, + PerformanceMeasure as _PerformanceMeasure, + PerformanceObserver as _PerformanceObserver, + PerformanceObserverEntryList as _PerformanceObserverEntryList, + PerformanceResourceTiming as _PerformanceResourceTiming, + } from "perf_hooks"; + global { + /** + * `PerformanceEntry` is a global reference for `import { PerformanceEntry } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performanceentry + * @since v19.0.0 + */ + var PerformanceEntry: typeof globalThis extends { + onmessage: any; + PerformanceEntry: infer T; + } ? T + : typeof _PerformanceEntry; + /** + * `PerformanceMark` is a global reference for `import { PerformanceMark } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performancemark + * @since v19.0.0 + */ + var PerformanceMark: typeof globalThis extends { + onmessage: any; + PerformanceMark: infer T; + } ? T + : typeof _PerformanceMark; + /** + * `PerformanceMeasure` is a global reference for `import { PerformanceMeasure } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performancemeasure + * @since v19.0.0 + */ + var PerformanceMeasure: typeof globalThis extends { + onmessage: any; + PerformanceMeasure: infer T; + } ? T + : typeof _PerformanceMeasure; + /** + * `PerformanceObserver` is a global reference for `import { PerformanceObserver } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performanceobserver + * @since v19.0.0 + */ + var PerformanceObserver: typeof globalThis extends { + onmessage: any; + PerformanceObserver: infer T; + } ? T + : typeof _PerformanceObserver; + /** + * `PerformanceObserverEntryList` is a global reference for `import { PerformanceObserverEntryList } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performanceobserverentrylist + * @since v19.0.0 + */ + var PerformanceObserverEntryList: typeof globalThis extends { + onmessage: any; + PerformanceObserverEntryList: infer T; + } ? T + : typeof _PerformanceObserverEntryList; + /** + * `PerformanceResourceTiming` is a global reference for `import { PerformanceResourceTiming } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performanceresourcetiming + * @since v19.0.0 + */ + var PerformanceResourceTiming: typeof globalThis extends { + onmessage: any; + PerformanceResourceTiming: infer T; + } ? T + : typeof _PerformanceResourceTiming; + /** + * `performance` is a global reference for `import { performance } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performance + * @since v16.0.0 + */ + var performance: typeof globalThis extends { + onmessage: any; + performance: infer T; + } ? T + : typeof _performance; + } +} +declare module "node:perf_hooks" { + export * from "perf_hooks"; +} diff --git a/node_modules/@types/node/process.d.ts b/node_modules/@types/node/process.d.ts new file mode 100644 index 0000000..1073839 --- /dev/null +++ b/node_modules/@types/node/process.d.ts @@ -0,0 +1,2084 @@ +declare module "process" { + import { Control, MessageOptions, SendHandle } from "node:child_process"; + import { PathLike } from "node:fs"; + import * as tty from "node:tty"; + import { Worker } from "node:worker_threads"; + + interface BuiltInModule { + "assert": typeof import("assert"); + "node:assert": typeof import("node:assert"); + "assert/strict": typeof import("assert/strict"); + "node:assert/strict": typeof import("node:assert/strict"); + "async_hooks": typeof import("async_hooks"); + "node:async_hooks": typeof import("node:async_hooks"); + "buffer": typeof import("buffer"); + "node:buffer": typeof import("node:buffer"); + "child_process": typeof import("child_process"); + "node:child_process": typeof import("node:child_process"); + "cluster": typeof import("cluster"); + "node:cluster": typeof import("node:cluster"); + "console": typeof import("console"); + "node:console": typeof import("node:console"); + "constants": typeof import("constants"); + "node:constants": typeof import("node:constants"); + "crypto": typeof import("crypto"); + "node:crypto": typeof import("node:crypto"); + "dgram": typeof import("dgram"); + "node:dgram": typeof import("node:dgram"); + "diagnostics_channel": typeof import("diagnostics_channel"); + "node:diagnostics_channel": typeof import("node:diagnostics_channel"); + "dns": typeof import("dns"); + "node:dns": typeof import("node:dns"); + "dns/promises": typeof import("dns/promises"); + "node:dns/promises": typeof import("node:dns/promises"); + "domain": typeof import("domain"); + "node:domain": typeof import("node:domain"); + "events": typeof import("events"); + "node:events": typeof import("node:events"); + "fs": typeof import("fs"); + "node:fs": typeof import("node:fs"); + "fs/promises": typeof import("fs/promises"); + "node:fs/promises": typeof import("node:fs/promises"); + "http": typeof import("http"); + "node:http": typeof import("node:http"); + "http2": typeof import("http2"); + "node:http2": typeof import("node:http2"); + "https": typeof import("https"); + "node:https": typeof import("node:https"); + "inspector": typeof import("inspector"); + "node:inspector": typeof import("node:inspector"); + "inspector/promises": typeof import("inspector/promises"); + "node:inspector/promises": typeof import("node:inspector/promises"); + "module": typeof import("module"); + "node:module": typeof import("node:module"); + "net": typeof import("net"); + "node:net": typeof import("node:net"); + "os": typeof import("os"); + "node:os": typeof import("node:os"); + "path": typeof import("path"); + "node:path": typeof import("node:path"); + "path/posix": typeof import("path/posix"); + "node:path/posix": typeof import("node:path/posix"); + "path/win32": typeof import("path/win32"); + "node:path/win32": typeof import("node:path/win32"); + "perf_hooks": typeof import("perf_hooks"); + "node:perf_hooks": typeof import("node:perf_hooks"); + "process": typeof import("process"); + "node:process": typeof import("node:process"); + "punycode": typeof import("punycode"); + "node:punycode": typeof import("node:punycode"); + "querystring": typeof import("querystring"); + "node:querystring": typeof import("node:querystring"); + "readline": typeof import("readline"); + "node:readline": typeof import("node:readline"); + "readline/promises": typeof import("readline/promises"); + "node:readline/promises": typeof import("node:readline/promises"); + "repl": typeof import("repl"); + "node:repl": typeof import("node:repl"); + "node:sea": typeof import("node:sea"); + "node:sqlite": typeof import("node:sqlite"); + "stream": typeof import("stream"); + "node:stream": typeof import("node:stream"); + "stream/consumers": typeof import("stream/consumers"); + "node:stream/consumers": typeof import("node:stream/consumers"); + "stream/promises": typeof import("stream/promises"); + "node:stream/promises": typeof import("node:stream/promises"); + "stream/web": typeof import("stream/web"); + "node:stream/web": typeof import("node:stream/web"); + "string_decoder": typeof import("string_decoder"); + "node:string_decoder": typeof import("node:string_decoder"); + "node:test": typeof import("node:test"); + "node:test/reporters": typeof import("node:test/reporters"); + "timers": typeof import("timers"); + "node:timers": typeof import("node:timers"); + "timers/promises": typeof import("timers/promises"); + "node:timers/promises": typeof import("node:timers/promises"); + "tls": typeof import("tls"); + "node:tls": typeof import("node:tls"); + "trace_events": typeof import("trace_events"); + "node:trace_events": typeof import("node:trace_events"); + "tty": typeof import("tty"); + "node:tty": typeof import("node:tty"); + "url": typeof import("url"); + "node:url": typeof import("node:url"); + "util": typeof import("util"); + "node:util": typeof import("node:util"); + "sys": typeof import("util"); + "node:sys": typeof import("node:util"); + "util/types": typeof import("util/types"); + "node:util/types": typeof import("node:util/types"); + "v8": typeof import("v8"); + "node:v8": typeof import("node:v8"); + "vm": typeof import("vm"); + "node:vm": typeof import("node:vm"); + "wasi": typeof import("wasi"); + "node:wasi": typeof import("node:wasi"); + "worker_threads": typeof import("worker_threads"); + "node:worker_threads": typeof import("node:worker_threads"); + "zlib": typeof import("zlib"); + "node:zlib": typeof import("node:zlib"); + } + global { + var process: NodeJS.Process; + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } + interface MemoryUsage { + /** + * Resident Set Size, is the amount of space occupied in the main memory device (that is a subset of the total allocated memory) for the + * process, including all C++ and JavaScript objects and code. + */ + rss: number; + /** + * Refers to V8's memory usage. + */ + heapTotal: number; + /** + * Refers to V8's memory usage. + */ + heapUsed: number; + external: number; + /** + * Refers to memory allocated for `ArrayBuffer`s and `SharedArrayBuffer`s, including all Node.js Buffers. This is also included + * in the external value. When Node.js is used as an embedded library, this value may be `0` because allocations for `ArrayBuffer`s + * may not be tracked in that case. + */ + arrayBuffers: number; + } + interface CpuUsage { + user: number; + system: number; + } + interface ProcessRelease { + name: string; + sourceUrl?: string | undefined; + headersUrl?: string | undefined; + libUrl?: string | undefined; + lts?: string | undefined; + } + interface ProcessFeatures { + /** + * A boolean value that is `true` if the current Node.js build is caching builtin modules. + * @since v12.0.0 + */ + readonly cached_builtins: boolean; + /** + * A boolean value that is `true` if the current Node.js build is a debug build. + * @since v0.5.5 + */ + readonly debug: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes the inspector. + * @since v11.10.0 + */ + readonly inspector: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for IPv6. + * + * Since all Node.js builds have IPv6 support, this value is always `true`. + * @since v0.5.3 + * @deprecated This property is always true, and any checks based on it are redundant. + */ + readonly ipv6: boolean; + /** + * A boolean value that is `true` if the current Node.js build supports + * [loading ECMAScript modules using `require()`](https://nodejs.org/docs/latest-v22.x/api/modules.md#loading-ecmascript-modules-using-require). + * @since v22.10.0 + */ + readonly require_module: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for TLS. + * @since v0.5.3 + */ + readonly tls: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for ALPN in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional ALPN support. + * This value is therefore identical to that of `process.features.tls`. + * @since v4.8.0 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_alpn: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for OCSP in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional OCSP support. + * This value is therefore identical to that of `process.features.tls`. + * @since v0.11.13 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_ocsp: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for SNI in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional SNI support. + * This value is therefore identical to that of `process.features.tls`. + * @since v0.5.3 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_sni: boolean; + /** + * A value that is `"strip"` by default, + * `"transform"` if Node.js is run with `--experimental-transform-types`, and `false` if + * Node.js is run with `--no-experimental-strip-types`. + * @since v22.10.0 + */ + readonly typescript: "strip" | "transform" | false; + /** + * A boolean value that is `true` if the current Node.js build includes support for libuv. + * + * Since it's not possible to build Node.js without libuv, this value is always `true`. + * @since v0.5.3 + * @deprecated This property is always true, and any checks based on it are redundant. + */ + readonly uv: boolean; + } + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + type Platform = + | "aix" + | "android" + | "darwin" + | "freebsd" + | "haiku" + | "linux" + | "openbsd" + | "sunos" + | "win32" + | "cygwin" + | "netbsd"; + type Architecture = + | "arm" + | "arm64" + | "ia32" + | "loong64" + | "mips" + | "mipsel" + | "ppc" + | "ppc64" + | "riscv64" + | "s390" + | "s390x" + | "x64"; + type Signals = + | "SIGABRT" + | "SIGALRM" + | "SIGBUS" + | "SIGCHLD" + | "SIGCONT" + | "SIGFPE" + | "SIGHUP" + | "SIGILL" + | "SIGINT" + | "SIGIO" + | "SIGIOT" + | "SIGKILL" + | "SIGPIPE" + | "SIGPOLL" + | "SIGPROF" + | "SIGPWR" + | "SIGQUIT" + | "SIGSEGV" + | "SIGSTKFLT" + | "SIGSTOP" + | "SIGSYS" + | "SIGTERM" + | "SIGTRAP" + | "SIGTSTP" + | "SIGTTIN" + | "SIGTTOU" + | "SIGUNUSED" + | "SIGURG" + | "SIGUSR1" + | "SIGUSR2" + | "SIGVTALRM" + | "SIGWINCH" + | "SIGXCPU" + | "SIGXFSZ" + | "SIGBREAK" + | "SIGLOST" + | "SIGINFO"; + type UncaughtExceptionOrigin = "uncaughtException" | "unhandledRejection"; + type MultipleResolveType = "resolve" | "reject"; + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void; + /** + * Most of the time the unhandledRejection will be an Error, but this should not be relied upon + * as *anything* can be thrown/rejected, it is therefore unsafe to assume that the value is an Error. + */ + type UnhandledRejectionListener = (reason: unknown, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: unknown, sendHandle: SendHandle) => void; + type SignalsListener = (signal: Signals) => void; + type MultipleResolveListener = ( + type: MultipleResolveType, + promise: Promise, + value: unknown, + ) => void; + type WorkerListener = (worker: Worker) => void; + interface Socket extends ReadWriteStream { + isTTY?: true | undefined; + } + // Alias for compatibility + interface ProcessEnv extends Dict {} + interface HRTime { + /** + * This is the legacy version of {@link process.hrtime.bigint()} + * before bigint was introduced in JavaScript. + * + * The `process.hrtime()` method returns the current high-resolution real time in a `[seconds, nanoseconds]` tuple `Array`, + * where `nanoseconds` is the remaining part of the real time that can't be represented in second precision. + * + * `time` is an optional parameter that must be the result of a previous `process.hrtime()` call to diff with the current time. + * If the parameter passed in is not a tuple `Array`, a TypeError will be thrown. + * Passing in a user-defined array instead of the result of a previous call to `process.hrtime()` will lead to undefined behavior. + * + * These times are relative to an arbitrary time in the past, + * and not related to the time of day and therefore not subject to clock drift. + * The primary use is for measuring performance between intervals: + * ```js + * const { hrtime } = require('node:process'); + * const NS_PER_SEC = 1e9; + * const time = hrtime(); + * // [ 1800216, 25 ] + * + * setTimeout(() => { + * const diff = hrtime(time); + * // [ 1, 552 ] + * + * console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`); + * // Benchmark took 1000000552 nanoseconds + * }, 1000); + * ``` + * @since 0.7.6 + * @legacy Use {@link process.hrtime.bigint()} instead. + * @param time The result of a previous call to `process.hrtime()` + */ + (time?: [number, number]): [number, number]; + /** + * The `bigint` version of the {@link process.hrtime()} method returning the current high-resolution real time in nanoseconds as a `bigint`. + * + * Unlike {@link process.hrtime()}, it does not support an additional time argument since the difference can just be computed directly by subtraction of the two `bigint`s. + * ```js + * import { hrtime } from 'node:process'; + * + * const start = hrtime.bigint(); + * // 191051479007711n + * + * setTimeout(() => { + * const end = hrtime.bigint(); + * // 191052633396993n + * + * console.log(`Benchmark took ${end - start} nanoseconds`); + * // Benchmark took 1154389282 nanoseconds + * }, 1000); + * ``` + * @since v10.7.0 + */ + bigint(): bigint; + } + interface ProcessPermission { + /** + * Verifies that the process is able to access the given scope and reference. + * If no reference is provided, a global scope is assumed, for instance, `process.permission.has('fs.read')` + * will check if the process has ALL file system read permissions. + * + * The reference has a meaning based on the provided scope. For example, the reference when the scope is File System means files and folders. + * + * The available scopes are: + * + * * `fs` - All File System + * * `fs.read` - File System read operations + * * `fs.write` - File System write operations + * * `child` - Child process spawning operations + * * `worker` - Worker thread spawning operation + * + * ```js + * // Check if the process has permission to read the README file + * process.permission.has('fs.read', './README.md'); + * // Check if the process has read permission operations + * process.permission.has('fs.read'); + * ``` + * @since v20.0.0 + */ + has(scope: string, reference?: string): boolean; + } + interface ProcessReport { + /** + * Write reports in a compact format, single-line JSON, more easily consumable by log processing systems + * than the default multi-line format designed for human consumption. + * @since v13.12.0, v12.17.0 + */ + compact: boolean; + /** + * Directory where the report is written. + * The default value is the empty string, indicating that reports are written to the current + * working directory of the Node.js process. + */ + directory: string; + /** + * Filename where the report is written. If set to the empty string, the output filename will be comprised + * of a timestamp, PID, and sequence number. The default value is the empty string. + */ + filename: string; + /** + * Returns a JavaScript Object representation of a diagnostic report for the running process. + * The report's JavaScript stack trace is taken from `err`, if present. + */ + getReport(err?: Error): object; + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @default false + */ + reportOnSignal: boolean; + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + /** + * If true, a diagnostic report is generated without the environment variables. + * @default false + */ + excludeEnv: boolean; + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from `err`, if present. + * + * If the value of filename is set to `'stdout'` or `'stderr'`, the report is written + * to the stdout or stderr of the process respectively. + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param err A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string, err?: Error): string; + writeReport(err?: Error): string; + } + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string | undefined; + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string | undefined; + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function | undefined; + /** + * Additional text to include with the error. + */ + detail?: string | undefined; + } + interface ProcessConfig { + readonly target_defaults: { + readonly cflags: any[]; + readonly default_configuration: string; + readonly defines: string[]; + readonly include_dirs: string[]; + readonly libraries: string[]; + }; + readonly variables: { + readonly clang: number; + readonly host_arch: string; + readonly node_install_npm: boolean; + readonly node_install_waf: boolean; + readonly node_prefix: string; + readonly node_shared_openssl: boolean; + readonly node_shared_v8: boolean; + readonly node_shared_zlib: boolean; + readonly node_use_dtrace: boolean; + readonly node_use_etw: boolean; + readonly node_use_openssl: boolean; + readonly target_arch: string; + readonly v8_no_strict_aliasing: number; + readonly v8_use_snapshot: boolean; + readonly visibility: string; + }; + } + interface Process extends EventEmitter { + /** + * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is + * a `Writable` stream. + * + * For example, to copy `process.stdin` to `process.stdout`: + * + * ```js + * import { stdin, stdout } from 'node:process'; + * + * stdin.pipe(stdout); + * ``` + * + * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is + * a `Writable` stream. + * + * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stderr: WriteStream & { + fd: 2; + }; + /** + * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is + * a `Readable` stream. + * + * For details of how to read from `stdin` see `readable.read()`. + * + * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that + * is compatible with scripts written for Node.js prior to v0.10\. + * For more information see `Stream compatibility`. + * + * In "old" streams mode the `stdin` stream is paused by default, so one + * must call `process.stdin.resume()` to read from it. Note also that calling `process.stdin.resume()` itself would switch stream to "old" mode. + */ + stdin: ReadStream & { + fd: 0; + }; + /** + * The `process.argv` property returns an array containing the command-line + * arguments passed when the Node.js process was launched. The first element will + * be {@link execPath}. See `process.argv0` if access to the original value + * of `argv[0]` is needed. The second element will be the path to the JavaScript + * file being executed. The remaining elements will be any additional command-line + * arguments. + * + * For example, assuming the following script for `process-args.js`: + * + * ```js + * import { argv } from 'node:process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```bash + * node process-args.js one two=three four + * ``` + * + * Would generate the output: + * + * ```text + * 0: /usr/local/bin/node + * 1: /Users/mjr/work/node/process-args.js + * 2: one + * 3: two=three + * 4: four + * ``` + * @since v0.1.27 + */ + argv: string[]; + /** + * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. + * + * ```console + * $ bash -c 'exec -a customArgv0 ./node' + * > process.argv[0] + * '/Volumes/code/external/node/out/Release/node' + * > process.argv0 + * 'customArgv0' + * ``` + * @since v6.4.0 + */ + argv0: string; + /** + * The `process.execArgv` property returns the set of Node.js-specific command-line + * options passed when the Node.js process was launched. These options do not + * appear in the array returned by the {@link argv} property, and do not + * include the Node.js executable, the name of the script, or any options following + * the script name. These options are useful in order to spawn child processes with + * the same execution environment as the parent. + * + * ```bash + * node --icu-data-dir=./foo --require ./bar.js script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ["--icu-data-dir=./foo", "--require", "./bar.js"] + * ``` + * + * And `process.argv`: + * + * ```js + * ['/usr/local/bin/node', 'script.js', '--version'] + * ``` + * + * Refer to `Worker constructor` for the detailed behavior of worker + * threads with this property. + * @since v0.7.7 + */ + execArgv: string[]; + /** + * The `process.execPath` property returns the absolute pathname of the executable + * that started the Node.js process. Symbolic links, if any, are resolved. + * + * ```js + * '/usr/local/bin/node' + * ``` + * @since v0.1.100 + */ + execPath: string; + /** + * The `process.abort()` method causes the Node.js process to exit immediately and + * generate a core file. + * + * This feature is not available in `Worker` threads. + * @since v0.7.0 + */ + abort(): never; + /** + * The `process.chdir()` method changes the current working directory of the + * Node.js process or throws an exception if doing so fails (for instance, if + * the specified `directory` does not exist). + * + * ```js + * import { chdir, cwd } from 'node:process'; + * + * console.log(`Starting directory: ${cwd()}`); + * try { + * chdir('/tmp'); + * console.log(`New directory: ${cwd()}`); + * } catch (err) { + * console.error(`chdir: ${err}`); + * } + * ``` + * + * This feature is not available in `Worker` threads. + * @since v0.1.17 + */ + chdir(directory: string): void; + /** + * The `process.cwd()` method returns the current working directory of the Node.js + * process. + * + * ```js + * import { cwd } from 'node:process'; + * + * console.log(`Current directory: ${cwd()}`); + * ``` + * @since v0.1.8 + */ + cwd(): string; + /** + * The port used by the Node.js debugger when enabled. + * + * ```js + * import process from 'node:process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * The `process.dlopen()` method allows dynamically loading shared objects. It is primarily used by `require()` to load C++ Addons, and + * should not be used directly, except in special cases. In other words, `require()` should be preferred over `process.dlopen()` + * unless there are specific reasons such as custom dlopen flags or loading from ES modules. + * + * The `flags` argument is an integer that allows to specify dlopen behavior. See the `[os.constants.dlopen](https://nodejs.org/docs/latest-v22.x/api/os.html#dlopen-constants)` + * documentation for details. + * + * An important requirement when calling `process.dlopen()` is that the `module` instance must be passed. Functions exported by the C++ Addon + * are then accessible via `module.exports`. + * + * The example below shows how to load a C++ Addon, named `local.node`, that exports a `foo` function. All the symbols are loaded before the call returns, by passing the `RTLD_NOW` constant. + * In this example the constant is assumed to be available. + * + * ```js + * import { dlopen } from 'node:process'; + * import { constants } from 'node:os'; + * import { fileURLToPath } from 'node:url'; + * + * const module = { exports: {} }; + * dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)), + * constants.dlopen.RTLD_NOW); + * module.exports.foo(); + * ``` + */ + dlopen(module: object, filename: string, flags?: number): void; + /** + * The `process.emitWarning()` method can be used to emit custom or application + * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string. + * emitWarning('Something happened!'); + * // Emits: (node: 56338) Warning: Something happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string and a type. + * emitWarning('Something Happened!', 'CustomWarning'); + * // Emits: (node:56338) CustomWarning: Something Happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * emitWarning('Something happened!', 'CustomWarning', 'WARN001'); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ```js + * + * In each of the previous examples, an `Error` object is generated internally by `process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'node:process'; + * + * process.on('warning', (warning) => { + * console.warn(warning.name); // 'Warning' + * console.warn(warning.message); // 'Something happened!' + * console.warn(warning.code); // 'MY_WARNING' + * console.warn(warning.stack); // Stack trace + * console.warn(warning.detail); // 'This is some additional information' + * }); + * ``` + * + * If `warning` is passed as an `Error` object, it will be passed through to the `'warning'` event handler + * unmodified (and the optional `type`, `code` and `ctor` arguments will be ignored): + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using an Error object. + * const myWarning = new Error('Something happened!'); + * // Use the Error name property to specify the type name + * myWarning.name = 'CustomWarning'; + * myWarning.code = 'WARN001'; + * + * emitWarning(myWarning); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ``` + * + * A `TypeError` is thrown if `warning` is anything other than a string or `Error` object. + * + * While process warnings use `Error` objects, the process warning mechanism is not a replacement for normal error handling mechanisms. + * + * The following additional handling is implemented if the warning `type` is `'DeprecationWarning'`: + * * If the `--throw-deprecation` command-line flag is used, the deprecation warning is thrown as an exception rather than being emitted as an event. + * * If the `--no-deprecation` command-line flag is used, the deprecation warning is suppressed. + * * If the `--trace-deprecation` command-line flag is used, the deprecation warning is printed to `stderr` along with the full stack trace. + * @since v8.0.0 + * @param warning The warning to emit. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + /** + * The `process.env` property returns an object containing the user environment. + * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). + * + * An example of this object looks like: + * + * ```js + * { + * TERM: 'xterm-256color', + * SHELL: '/usr/local/bin/bash', + * USER: 'maciej', + * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', + * PWD: '/Users/maciej', + * EDITOR: 'vim', + * SHLVL: '1', + * HOME: '/Users/maciej', + * LOGNAME: 'maciej', + * _: '/usr/local/bin/node' + * } + * ``` + * + * It is possible to modify this object, but such modifications will not be + * reflected outside the Node.js process, or (unless explicitly requested) + * to other `Worker` threads. + * In other words, the following example would not work: + * + * ```bash + * node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'node:process'; + * + * env.foo = 'bar'; + * console.log(env.foo); + * ``` + * + * Assigning a property on `process.env` will implicitly convert the value + * to a string. **This behavior is deprecated.** Future versions of Node.js may + * throw an error when the value is not a string, number, or boolean. + * + * ```js + * import { env } from 'node:process'; + * + * env.test = null; + * console.log(env.test); + * // => 'null' + * env.test = undefined; + * console.log(env.test); + * // => 'undefined' + * ``` + * + * Use `delete` to delete a property from `process.env`. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * delete env.TEST; + * console.log(env.TEST); + * // => undefined + * ``` + * + * On Windows operating systems, environment variables are case-insensitive. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * console.log(env.test); + * // => 1 + * ``` + * + * Unless explicitly specified when creating a `Worker` instance, + * each `Worker` thread has its own copy of `process.env`, based on its + * parent thread's `process.env`, or whatever was specified as the `env` option + * to the `Worker` constructor. Changes to `process.env` will not be visible + * across `Worker` threads, and only the main thread can make changes that + * are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner + * unlike the main thread. + * @since v0.1.27 + */ + env: ProcessEnv; + /** + * The `process.exit()` method instructs Node.js to terminate the process + * synchronously with an exit status of `code`. If `code` is omitted, exit uses + * either the 'success' code `0` or the value of `process.exitCode` if it has been + * set. Node.js will not terminate until all the `'exit'` event listeners are + * called. + * + * To exit with a 'failure' code: + * + * ```js + * import { exit } from 'node:process'; + * + * exit(1); + * ``` + * + * The shell that executed Node.js should see the exit code as `1`. + * + * Calling `process.exit()` will force the process to exit as quickly as possible + * even if there are still asynchronous operations pending that have not yet + * completed fully, including I/O operations to `process.stdout` and `process.stderr`. + * + * In most situations, it is not actually necessary to call `process.exit()` explicitly. The Node.js process will exit on its own _if there is no additional_ + * _work pending_ in the event loop. The `process.exitCode` property can be set to + * tell the process which exit code to use when the process exits gracefully. + * + * For instance, the following example illustrates a _misuse_ of the `process.exit()` method that could lead to data printed to stdout being + * truncated and lost: + * + * ```js + * import { exit } from 'node:process'; + * + * // This is an example of what *not* to do: + * if (someConditionNotMet()) { + * printUsageToStdout(); + * exit(1); + * } + * ``` + * + * The reason this is problematic is because writes to `process.stdout` in Node.js + * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js + * event loop. Calling `process.exit()`, however, forces the process to exit _before_ those additional writes to `stdout` can be performed. + * + * Rather than calling `process.exit()` directly, the code _should_ set the `process.exitCode` and allow the process to exit naturally by avoiding + * scheduling any additional work for the event loop: + * + * ```js + * import process from 'node:process'; + * + * // How to properly set the exit code while letting + * // the process exit gracefully. + * if (someConditionNotMet()) { + * printUsageToStdout(); + * process.exitCode = 1; + * } + * ``` + * + * If it is necessary to terminate the Node.js process due to an error condition, + * throwing an _uncaught_ error and allowing the process to terminate accordingly + * is safer than calling `process.exit()`. + * + * In `Worker` threads, this function stops the current thread rather + * than the current process. + * @since v0.1.13 + * @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed. + */ + exit(code?: number | string | null): never; + /** + * A number which will be the process exit code, when the process either + * exits gracefully, or is exited via {@link exit} without specifying + * a code. + * + * Specifying a code to {@link exit} will override any + * previous setting of `process.exitCode`. + * @default undefined + * @since v0.11.8 + */ + exitCode: number | string | null | undefined; + finalization: { + /** + * This function registers a callback to be called when the process emits the `exit` event if the `ref` object was not garbage collected. + * If the object `ref` was garbage collected before the `exit` event is emitted, the callback will be removed from the finalization registry, and it will not be called on process exit. + * + * Inside the callback you can release the resources allocated by the `ref` object. + * Be aware that all limitations applied to the `beforeExit` event are also applied to the callback function, + * this means that there is a possibility that the callback will not be called under special circumstances. + * + * The idea of ​​this function is to help you free up resources when the starts process exiting, but also let the object be garbage collected if it is no longer being used. + * @param ref The reference to the resource that is being tracked. + * @param callback The callback function to be called when the resource is finalized. + * @since v22.5.0 + * @experimental + */ + register(ref: T, callback: (ref: T, event: "exit") => void): void; + /** + * This function behaves exactly like the `register`, except that the callback will be called when the process emits the `beforeExit` event if `ref` object was not garbage collected. + * + * Be aware that all limitations applied to the `beforeExit` event are also applied to the callback function, this means that there is a possibility that the callback will not be called under special circumstances. + * @param ref The reference to the resource that is being tracked. + * @param callback The callback function to be called when the resource is finalized. + * @since v22.5.0 + * @experimental + */ + registerBeforeExit(ref: T, callback: (ref: T, event: "beforeExit") => void): void; + /** + * This function remove the register of the object from the finalization registry, so the callback will not be called anymore. + * @param ref The reference to the resource that was registered previously. + * @since v22.5.0 + * @experimental + */ + unregister(ref: object): void; + }; + /** + * The `process.getActiveResourcesInfo()` method returns an array of strings containing + * the types of the active resources that are currently keeping the event loop alive. + * + * ```js + * import { getActiveResourcesInfo } from 'node:process'; + * import { setTimeout } from 'node:timers'; + + * console.log('Before:', getActiveResourcesInfo()); + * setTimeout(() => {}, 1000); + * console.log('After:', getActiveResourcesInfo()); + * // Prints: + * // Before: [ 'TTYWrap', 'TTYWrap', 'TTYWrap' ] + * // After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ] + * ``` + * @since v17.3.0, v16.14.0 + */ + getActiveResourcesInfo(): string[]; + /** + * Provides a way to load built-in modules in a globally available function. + * @param id ID of the built-in module being requested. + */ + getBuiltinModule(id: ID): BuiltInModule[ID]; + getBuiltinModule(id: string): object | undefined; + /** + * The `process.getgid()` method returns the numerical group identity of the + * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid) { + * console.log(`Current gid: ${process.getgid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.31 + */ + getgid?: () => number; + /** + * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a + * numeric ID or a group name + * string. If a group name is specified, this method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid && process.setgid) { + * console.log(`Current gid: ${process.getgid()}`); + * try { + * process.setgid(501); + * console.log(`New gid: ${process.getgid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.31 + * @param id The group name or ID + */ + setgid?: (id: number | string) => void; + /** + * The `process.getuid()` method returns the numeric user identity of the process. + * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid) { + * console.log(`Current uid: ${process.getuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.28 + */ + getuid?: () => number; + /** + * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a + * numeric ID or a username string. + * If a username is specified, the method blocks while resolving the associated + * numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid && process.setuid) { + * console.log(`Current uid: ${process.getuid()}`); + * try { + * process.setuid(501); + * console.log(`New uid: ${process.getuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.28 + */ + setuid?: (id: number | string) => void; + /** + * The `process.geteuid()` method returns the numerical effective user identity of + * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + geteuid?: () => number; + /** + * The `process.seteuid()` method sets the effective user identity of the process. + * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username + * string. If a username is specified, the method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid && process.seteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * try { + * process.seteuid(501); + * console.log(`New uid: ${process.geteuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A user name or ID + */ + seteuid?: (id: number | string) => void; + /** + * The `process.getegid()` method returns the numerical effective group identity + * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid) { + * console.log(`Current gid: ${process.getegid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + getegid?: () => number; + /** + * The `process.setegid()` method sets the effective group identity of the process. + * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group + * name string. If a group name is specified, this method blocks while resolving + * the associated a numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid && process.setegid) { + * console.log(`Current gid: ${process.getegid()}`); + * try { + * process.setegid(501); + * console.log(`New gid: ${process.getegid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A group name or ID + */ + setegid?: (id: number | string) => void; + /** + * The `process.getgroups()` method returns an array with the supplementary group + * IDs. POSIX leaves it unspecified if the effective group ID is included but + * Node.js ensures it always is. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups) { + * console.log(process.getgroups()); // [ 16, 21, 297 ] + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.9.4 + */ + getgroups?: () => number[]; + /** + * The `process.setgroups()` method sets the supplementary group IDs for the + * Node.js process. This is a privileged operation that requires the Node.js + * process to have `root` or the `CAP_SETGID` capability. + * + * The `groups` array can contain numeric group IDs, group names, or both. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups && process.setgroups) { + * try { + * process.setgroups([501]); + * console.log(process.getgroups()); // new groups + * } catch (err) { + * console.log(`Failed to set groups: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.9.4 + */ + setgroups?: (groups: ReadonlyArray) => void; + /** + * The `process.setUncaughtExceptionCaptureCallback()` function sets a function + * that will be invoked when an uncaught exception occurs, which will receive the + * exception value itself as its first argument. + * + * If such a function is set, the `'uncaughtException'` event will + * not be emitted. If `--abort-on-uncaught-exception` was passed from the + * command line or set through `v8.setFlagsFromString()`, the process will + * not abort. Actions configured to take place on exceptions such as report + * generations will be affected too + * + * To unset the capture function, `process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * method with a non-`null` argument while another capture function is set will + * throw an error. + * + * Using this function is mutually exclusive with using the deprecated `domain` built-in module. + * @since v9.3.0 + */ + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + /** + * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. + * @since v9.3.0 + */ + hasUncaughtExceptionCaptureCallback(): boolean; + /** + * The `process.sourceMapsEnabled` property returns whether the [Source Map v3](https://sourcemaps.info/spec.html) support for stack traces is enabled. + * @since v20.7.0 + * @experimental + */ + readonly sourceMapsEnabled: boolean; + /** + * This function enables or disables the [Source Map v3](https://sourcemaps.info/spec.html) support for + * stack traces. + * + * It provides same features as launching Node.js process with commandline options `--enable-source-maps`. + * + * Only source maps in JavaScript files that are loaded after source maps has been + * enabled will be parsed and loaded. + * @since v16.6.0, v14.18.0 + * @experimental + */ + setSourceMapsEnabled(value: boolean): void; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'node:process'; + * + * console.log(`Version: ${version}`); + * // Version: v14.8.0 + * ``` + * + * To get the version string without the prepended _v_, use`process.versions.node`. + * @since v0.1.3 + */ + readonly version: string; + /** + * The `process.versions` property returns an object listing the version strings of + * Node.js and its dependencies. `process.versions.modules` indicates the current + * ABI version, which is increased whenever a C++ API changes. Node.js will refuse + * to load modules that were compiled against a different module ABI version. + * + * ```js + * import { versions } from 'node:process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '20.2.0', + * acorn: '8.8.2', + * ada: '2.4.0', + * ares: '1.19.0', + * base64: '0.5.0', + * brotli: '1.0.9', + * cjs_module_lexer: '1.2.2', + * cldr: '43.0', + * icu: '73.1', + * llhttp: '8.1.0', + * modules: '115', + * napi: '8', + * nghttp2: '1.52.0', + * nghttp3: '0.7.0', + * ngtcp2: '0.8.1', + * openssl: '3.0.8+quic', + * simdutf: '3.2.9', + * tz: '2023c', + * undici: '5.22.0', + * unicode: '15.0', + * uv: '1.44.2', + * uvwasi: '0.0.16', + * v8: '11.3.244.8-node.9', + * zlib: '1.2.13' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns a frozen `Object` containing the + * JavaScript representation of the configure options used to compile the current + * Node.js executable. This is the same as the `config.gypi` file that was produced + * when running the `./configure` script. + * + * An example of the possible output looks like: + * + * ```js + * { + * target_defaults: + * { cflags: [], + * default_configuration: 'Release', + * defines: [], + * include_dirs: [], + * libraries: [] }, + * variables: + * { + * host_arch: 'x64', + * napi_build_version: 5, + * node_install_npm: 'true', + * node_prefix: '', + * node_shared_cares: 'false', + * node_shared_http_parser: 'false', + * node_shared_libuv: 'false', + * node_shared_zlib: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * @since v0.7.7 + */ + readonly config: ProcessConfig; + /** + * The `process.kill()` method sends the `signal` to the process identified by`pid`. + * + * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. + * + * This method will throw an error if the target `pid` does not exist. As a special + * case, a signal of `0` can be used to test for the existence of a process. + * Windows platforms will throw an error if the `pid` is used to kill a process + * group. + * + * Even though the name of this function is `process.kill()`, it is really just a + * signal sender, like the `kill` system call. The signal sent may do something + * other than kill the target process. + * + * ```js + * import process, { kill } from 'node:process'; + * + * process.on('SIGHUP', () => { + * console.log('Got SIGHUP signal.'); + * }); + * + * setTimeout(() => { + * console.log('Exiting.'); + * process.exit(0); + * }, 100); + * + * kill(process.pid, 'SIGHUP'); + * ``` + * + * When `SIGUSR1` is received by a Node.js process, Node.js will start the + * debugger. See `Signal Events`. + * @since v0.0.6 + * @param pid A process ID + * @param [signal='SIGTERM'] The signal to send, either as a string or number. + */ + kill(pid: number, signal?: string | number): true; + /** + * Loads the environment configuration from a `.env` file into `process.env`. If + * the file is not found, error will be thrown. + * + * To load a specific .env file by specifying its path, use the following code: + * + * ```js + * import { loadEnvFile } from 'node:process'; + * + * loadEnvFile('./development.env') + * ``` + * @since v20.12.0 + * @param path The path to the .env file + */ + loadEnvFile(path?: PathLike): void; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'node:process'; + * + * console.log(`This process is pid ${pid}`); + * ``` + * @since v0.1.15 + */ + readonly pid: number; + /** + * The `process.ppid` property returns the PID of the parent of the + * current process. + * + * ```js + * import { ppid } from 'node:process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * The `process.threadCpuUsage()` method returns the user and system CPU time usage of + * the current worker thread, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). + * + * The result of a previous call to `process.threadCpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * @since v22.19.0 + * @param previousValue A previous return value from calling + * `process.threadCpuUsage()` + */ + threadCpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * The `process.title` property returns the current process title (i.e. returns + * the current value of `ps`). Assigning a new value to `process.title` modifies + * the current value of `ps`. + * + * When a new value is assigned, different platforms will impose different maximum + * length restrictions on the title. Usually such restrictions are quite limited. + * For instance, on Linux and macOS, `process.title` is limited to the size of the + * binary name plus the length of the command-line arguments because setting the `process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ` memory but that was potentially insecure and confusing in some (rather obscure) + * cases. + * + * Assigning a value to `process.title` might not result in an accurate label + * within process manager applications such as macOS Activity Monitor or Windows + * Services Manager. + * @since v0.1.104 + */ + title: string; + /** + * The operating system CPU architecture for which the Node.js binary was compiled. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, and `'x64'`. + * + * ```js + * import { arch } from 'node:process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: Architecture; + /** + * The `process.platform` property returns a string identifying the operating + * system platform for which the Node.js binary was compiled. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from 'node:process'; + * + * console.log(`This platform is ${platform}`); + * ``` + * + * The value `'android'` may also be returned if the Node.js is built on the + * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.1.16 + */ + readonly platform: Platform; + /** + * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at + * runtime, `require.main` may still refer to the original main module in + * modules that were required before the change occurred. Generally, it's + * safe to assume that the two refer to the same module. + * + * As with `require.main`, `process.mainModule` will be `undefined` if there + * is no entry script. + * @since v0.1.17 + * @deprecated Since v14.0.0 - Use `main` instead. + */ + mainModule?: Module; + memoryUsage: MemoryUsageFn; + /** + * Gets the amount of memory available to the process (in bytes) based on + * limits imposed by the OS. If there is no such constraint, or the constraint + * is unknown, `0` is returned. + * + * See [`uv_get_constrained_memory`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory) for more + * information. + * @since v19.6.0, v18.15.0 + */ + constrainedMemory(): number; + /** + * Gets the amount of free memory that is still available to the process (in bytes). + * See [`uv_get_available_memory`](https://nodejs.org/docs/latest-v22.x/api/process.html#processavailablememory) for more information. + * @since v20.13.0 + */ + availableMemory(): number; + /** + * The `process.cpuUsage()` method returns the user and system CPU time usage of + * the current process, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). These values measure time + * spent in user and system code respectively, and may end up being greater than + * actual elapsed time if multiple CPU cores are performing work for this process. + * + * The result of a previous call to `process.cpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * + * ```js + * import { cpuUsage } from 'node:process'; + * + * const startUsage = cpuUsage(); + * // { user: 38579, system: 6986 } + * + * // spin the CPU for 500 milliseconds + * const now = Date.now(); + * while (Date.now() - now < 500); + * + * console.log(cpuUsage(startUsage)); + * // { user: 514883, system: 11226 } + * ``` + * @since v6.1.0 + * @param previousValue A previous return value from calling `process.cpuUsage()` + */ + cpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * `process.nextTick()` adds `callback` to the "next tick queue". This queue is + * fully drained after the current operation on the JavaScript stack runs to + * completion and before the event loop is allowed to continue. It's possible to + * create an infinite loop if one were to recursively call `process.nextTick()`. + * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. + * + * ```js + * import { nextTick } from 'node:process'; + * + * console.log('start'); + * nextTick(() => { + * console.log('nextTick callback'); + * }); + * console.log('scheduled'); + * // Output: + * // start + * // scheduled + * // nextTick callback + * ``` + * + * This is important when developing APIs in order to give users the opportunity + * to assign event handlers _after_ an object has been constructed but before any + * I/O has occurred: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function MyThing(options) { + * this.setupOptions(options); + * + * nextTick(() => { + * this.startDoingStuff(); + * }); + * } + * + * const thing = new MyThing(); + * thing.getReadyForStuff(); + * + * // thing.startDoingStuff() gets called now, not before. + * ``` + * + * It is very important for APIs to be either 100% synchronous or 100% + * asynchronous. Consider this example: + * + * ```js + * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! + * function maybeSync(arg, cb) { + * if (arg) { + * cb(); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * + * This API is hazardous because in the following case: + * + * ```js + * const maybeTrue = Math.random() > 0.5; + * + * maybeSync(maybeTrue, () => { + * foo(); + * }); + * + * bar(); + * ``` + * + * It is not clear whether `foo()` or `bar()` will be called first. + * + * The following approach is much better: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function definitelyAsync(arg, cb) { + * if (arg) { + * nextTick(cb); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * @since v0.1.26 + * @param args Additional arguments to pass when invoking the `callback` + */ + nextTick(callback: Function, ...args: any[]): void; + /** + * The process.noDeprecation property indicates whether the --no-deprecation flag is set on the current Node.js process. + * See the documentation for the ['warning' event](https://nodejs.org/docs/latest/api/process.html#event-warning) and the [emitWarning()](https://nodejs.org/docs/latest/api/process.html#processemitwarningwarning-type-code-ctor) method for more information about this flag's behavior. + */ + noDeprecation?: boolean; + /** + * This API is available through the [--permission](https://nodejs.org/api/cli.html#--permission) flag. + * + * `process.permission` is an object whose methods are used to manage permissions for the current process. + * Additional documentation is available in the [Permission Model](https://nodejs.org/api/permissions.html#permission-model). + * @since v20.0.0 + */ + permission: ProcessPermission; + /** + * The `process.release` property returns an `Object` containing metadata related + * to the current release, including URLs for the source tarball and headers-only + * tarball. + * + * `process.release` contains the following properties: + * + * ```js + * { + * name: 'node', + * lts: 'Hydrogen', + * sourceUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib' + * } + * ``` + * + * In custom builds from non-release versions of the source tree, only the `name` property may be present. The additional properties should not be + * relied upon to exist. + * @since v3.0.0 + */ + readonly release: ProcessRelease; + readonly features: ProcessFeatures; + /** + * `process.umask()` returns the Node.js process's file mode creation mask. Child + * processes inherit the mask from the parent process. + * @since v0.1.19 + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential + * security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: string | number): number; + /** + * The `process.uptime()` method returns the number of seconds the current Node.js + * process has been running. + * + * The return value includes fractions of a second. Use `Math.floor()` to get whole + * seconds. + * @since v0.5.0 + */ + uptime(): number; + hrtime: HRTime; + /** + * If the Node.js process was spawned with an IPC channel, the process.channel property is a reference to the IPC channel. + * If no IPC channel exists, this property is undefined. + * @since v7.1.0 + */ + channel?: Control; + /** + * If Node.js is spawned with an IPC channel, the `process.send()` method can be + * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. + * + * If Node.js was not spawned with an IPC channel, `process.send` will be `undefined`. + * + * The message goes through serialization and parsing. The resulting message might + * not be the same as what is originally sent. + * @since v0.5.9 + * @param options used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send?( + message: any, + sendHandle?: SendHandle, + options?: MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + send?( + message: any, + sendHandle: SendHandle, + callback?: (error: Error | null) => void, + ): boolean; + send?( + message: any, + callback: (error: Error | null) => void, + ): boolean; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the + * IPC channel to the parent process, allowing the child process to exit gracefully + * once there are no other connections keeping it alive. + * + * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. + * + * If the Node.js process was not spawned with an IPC channel, `process.disconnect()` will be `undefined`. + * @since v0.7.2 + */ + disconnect(): void; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return `true` so long as the IPC + * channel is connected and will return `false` after `process.disconnect()` is called. + * + * Once `process.connected` is `false`, it is no longer possible to send messages + * over the IPC channel using `process.send()`. + * @since v0.7.2 + */ + connected: boolean; + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. + * + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides `Set.prototype.has` to recognize several different possible flag + * representations. `process.allowedNodeEnvironmentFlags.has()` will + * return `true` in the following cases: + * + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g., `inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags passed through to V8 (as listed in `--v8-options`) may replace + * one or more _non-leading_ dashes for an underscore, or vice-versa; + * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, + * etc. + * * Flags may contain one or more equals (`=`) characters; all + * characters after and including the first equals will be ignored; + * e.g., `--stack-trace-limit=100`. + * * Flags _must_ be allowable within `NODE_OPTIONS`. + * + * When iterating over `process.allowedNodeEnvironmentFlags`, flags will + * appear only _once_; each will begin with one or more dashes. Flags + * passed through to V8 will contain underscores instead of non-leading + * dashes: + * + * ```js + * import { allowedNodeEnvironmentFlags } from 'node:process'; + * + * allowedNodeEnvironmentFlags.forEach((flag) => { + * // -r + * // --inspect-brk + * // --abort_on_uncaught_exception + * // ... + * }); + * ``` + * + * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail + * silently. + * + * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will + * contain what _would have_ been allowable. + * @since v10.10.0 + */ + allowedNodeEnvironmentFlags: ReadonlySet; + /** + * `process.report` is an object whose methods are used to generate diagnostic reports for the current process. + * Additional documentation is available in the [report documentation](https://nodejs.org/docs/latest-v22.x/api/report.html). + * @since v11.8.0 + */ + report: ProcessReport; + /** + * ```js + * import { resourceUsage } from 'node:process'; + * + * console.log(resourceUsage()); + * /* + * Will output: + * { + * userCPUTime: 82872, + * systemCPUTime: 4143, + * maxRSS: 33164, + * sharedMemorySize: 0, + * unsharedDataSize: 0, + * unsharedStackSize: 0, + * minorPageFault: 2469, + * majorPageFault: 0, + * swappedOut: 0, + * fsRead: 0, + * fsWrite: 8, + * ipcSent: 0, + * ipcReceived: 0, + * signalsCount: 0, + * voluntaryContextSwitches: 79, + * involuntaryContextSwitches: 1 + * } + * + * ``` + * @since v12.6.0 + * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. + */ + resourceUsage(): ResourceUsage; + /** + * The initial value of `process.throwDeprecation` indicates whether the `--throw-deprecation` flag is set on the current Node.js process. `process.throwDeprecation` + * is mutable, so whether or not deprecation warnings result in errors may be altered at runtime. See the documentation for the 'warning' event and the emitWarning() + * method for more information. + * + * ```bash + * $ node --throw-deprecation -p "process.throwDeprecation" + * true + * $ node -p "process.throwDeprecation" + * undefined + * $ node + * > process.emitWarning('test', 'DeprecationWarning'); + * undefined + * > (node:26598) DeprecationWarning: test + * > process.throwDeprecation = true; + * true + * > process.emitWarning('test', 'DeprecationWarning'); + * Thrown: + * [DeprecationWarning: test] { name: 'DeprecationWarning' } + * ``` + * @since v0.9.12 + */ + throwDeprecation: boolean; + /** + * The `process.traceDeprecation` property indicates whether the `--trace-deprecation` flag is set on the current Node.js process. See the + * documentation for the `'warning' event` and the `emitWarning() method` for more information about this + * flag's behavior. + * @since v0.8.0 + */ + traceDeprecation: boolean; + /** + * An object is "refable" if it implements the Node.js "Refable protocol". + * Specifically, this means that the object implements the `Symbol.for('nodejs.ref')` + * and `Symbol.for('nodejs.unref')` methods. "Ref'd" objects will keep the Node.js + * event loop alive, while "unref'd" objects will not. Historically, this was + * implemented by using `ref()` and `unref()` methods directly on the objects. + * This pattern, however, is being deprecated in favor of the "Refable protocol" + * in order to better support Web Platform API types whose APIs cannot be modified + * to add `ref()` and `unref()` methods but still need to support that behavior. + * @since v22.14.0 + * @experimental + * @param maybeRefable An object that may be "refable". + */ + ref(maybeRefable: any): void; + /** + * An object is "unrefable" if it implements the Node.js "Refable protocol". + * Specifically, this means that the object implements the `Symbol.for('nodejs.ref')` + * and `Symbol.for('nodejs.unref')` methods. "Ref'd" objects will keep the Node.js + * event loop alive, while "unref'd" objects will not. Historically, this was + * implemented by using `ref()` and `unref()` methods directly on the objects. + * This pattern, however, is being deprecated in favor of the "Refable protocol" + * in order to better support Web Platform API types whose APIs cannot be modified + * to add `ref()` and `unref()` methods but still need to support that behavior. + * @since v22.14.0 + * @experimental + * @param maybeRefable An object that may be "unref'd". + */ + unref(maybeRefable: any): void; + /** + * Replaces the current process with a new process. + * + * This is achieved by using the `execve` POSIX function and therefore no memory or other + * resources from the current process are preserved, except for the standard input, + * standard output and standard error file descriptor. + * + * All other resources are discarded by the system when the processes are swapped, without triggering + * any exit or close events and without running any cleanup handler. + * + * This function will never return, unless an error occurred. + * + * This function is not available on Windows or IBM i. + * @since v22.15.0 + * @experimental + * @param file The name or path of the executable file to run. + * @param args List of string arguments. No argument can contain a null-byte (`\u0000`). + * @param env Environment key-value pairs. + * No key or value can contain a null-byte (`\u0000`). + * **Default:** `process.env`. + */ + execve?(file: string, args?: readonly string[], env?: ProcessEnv): never; + /* EventEmitter */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: "workerMessage", listener: (value: any, source: number) => void): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + addListener(event: "worker", listener: WorkerListener): this; + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "uncaughtExceptionMonitor", error: Error): boolean; + emit(event: "unhandledRejection", reason: unknown, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: unknown, sendHandle: SendHandle): this; + emit(event: "workerMessage", value: any, source: number): this; + emit(event: Signals, signal?: Signals): boolean; + emit( + event: "multipleResolves", + type: MultipleResolveType, + promise: Promise, + value: unknown, + ): this; + emit(event: "worker", listener: WorkerListener): this; + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + on(event: "worker", listener: WorkerListener): this; + on(event: "workerMessage", listener: (value: any, source: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + once(event: "worker", listener: WorkerListener): this; + once(event: "workerMessage", listener: (value: any, source: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: "workerMessage", listener: (value: any, source: number) => void): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependListener(event: "worker", listener: WorkerListener): this; + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: "workerMessage", listener: (value: any, source: number) => void): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependOnceListener(event: "worker", listener: WorkerListener): this; + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: "workerMessage"): ((value: any, source: number) => void)[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + listeners(event: "worker"): WorkerListener[]; + } + } + } + export = process; +} +declare module "node:process" { + import process = require("process"); + export = process; +} diff --git a/node_modules/@types/node/punycode.d.ts b/node_modules/@types/node/punycode.d.ts new file mode 100644 index 0000000..655c47b --- /dev/null +++ b/node_modules/@types/node/punycode.d.ts @@ -0,0 +1,117 @@ +/** + * **The version of the punycode module bundled in Node.js is being deprecated. **In a future major version of Node.js this module will be removed. Users + * currently depending on the `punycode` module should switch to using the + * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL + * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. + * + * The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It + * can be accessed using: + * + * ```js + * import punycode from 'node:punycode'; + * ``` + * + * [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is + * primarily intended for use in Internationalized Domain Names. Because host + * names in URLs are limited to ASCII characters only, Domain Names that contain + * non-ASCII characters must be converted into ASCII using the Punycode scheme. + * For instance, the Japanese character that translates into the English word, `'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent + * to `'example.com'`) is represented by Punycode as the ASCII string `'xn--fsq.com'`. + * + * The `punycode` module provides a simple implementation of the Punycode standard. + * + * The `punycode` module is a third-party dependency used by Node.js and + * made available to developers as a convenience. Fixes or other modifications to + * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. + * @deprecated Since v7.0.0 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/punycode.js) + */ +declare module "punycode" { + /** + * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only + * characters to the equivalent string of Unicode codepoints. + * + * ```js + * punycode.decode('maana-pta'); // 'mañana' + * punycode.decode('--dqo34k'); // '☃-⌘' + * ``` + * @since v0.5.1 + */ + function decode(string: string): string; + /** + * The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. + * + * ```js + * punycode.encode('mañana'); // 'maana-pta' + * punycode.encode('☃-⌘'); // '--dqo34k' + * ``` + * @since v0.5.1 + */ + function encode(string: string): string; + /** + * The `punycode.toUnicode()` method converts a string representing a domain name + * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be + * converted. + * + * ```js + * // decode domain names + * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + * punycode.toUnicode('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toUnicode(domain: string): string; + /** + * The `punycode.toASCII()` method converts a Unicode string representing an + * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the + * domain name will be converted. Calling `punycode.toASCII()` on a string that + * already only contains ASCII characters will have no effect. + * + * ```js + * // encode domain names + * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' + * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' + * punycode.toASCII('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toASCII(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: readonly number[]): string; + } + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} +declare module "node:punycode" { + export * from "punycode"; +} diff --git a/node_modules/@types/node/querystring.d.ts b/node_modules/@types/node/querystring.d.ts new file mode 100644 index 0000000..f0d5257 --- /dev/null +++ b/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,152 @@ +/** + * The `node:querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * import querystring from 'node:querystring'; + * ``` + * + * `querystring` is more performant than `URLSearchParams` but is not a + * standardized API. Use `URLSearchParams` when performance is not critical or + * when compatibility with browser code is desirable. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/querystring.js) + */ +declare module "querystring" { + interface StringifyOptions { + /** + * The function to use when converting URL-unsafe characters to percent-encoding in the query string. + * @default `querystring.escape()` + */ + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + /** + * Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations. + * @default 1000 + */ + maxKeys?: number | undefined; + /** + * The function to use when decoding percent-encoded characters in the query string. + * @default `querystring.unescape()` + */ + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends + NodeJS.Dict< + | string + | number + | boolean + | bigint + | ReadonlyArray + | null + > + {} + /** + * The `querystring.stringify()` method produces a URL query string from a + * given `obj` by iterating through the object's "own properties". + * + * It serializes the following types of values passed in `obj`: [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | + * [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to + * empty strings. + * + * ```js + * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); + * // Returns 'foo=bar&baz=qux&baz=quux&corge=' + * + * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); + * // Returns 'foo:bar;baz:qux' + * ``` + * + * By default, characters requiring percent-encoding within the query string will + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative `encodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkEncodeURIComponent function already exists, + * + * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + * { encodeURIComponent: gbkEncodeURIComponent }); + * ``` + * @since v0.1.25 + * @param obj The object to serialize into a URL query string + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + /** + * The `querystring.parse()` method parses a URL query string (`str`) into a + * collection of key and value pairs. + * + * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + * + * ```json + * { + * "foo": "bar", + * "abc": ["xyz", "123"] + * } + * ``` + * + * The object returned by the `querystring.parse()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * By default, percent-encoded characters within the query string will be assumed + * to use UTF-8 encoding. If an alternative character encoding is used, then an + * alternative `decodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkDecodeURIComponent function already exists... + * + * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, + * { decodeURIComponent: gbkDecodeURIComponent }); + * ``` + * @since v0.1.25 + * @param str The URL query string to parse + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] The substring used to delimit keys and values in the query string. + */ + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + /** + * The `querystring.escape()` method performs URL percent-encoding on the given `str` in a manner that is optimized for the specific requirements of URL + * query strings. + * + * The `querystring.escape()` method is used by `querystring.stringify()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement percent-encoding implementation if + * necessary by assigning `querystring.escape` to an alternative function. + * @since v0.1.25 + */ + function escape(str: string): string; + /** + * The `querystring.unescape()` method performs decoding of URL percent-encoded + * characters on the given `str`. + * + * The `querystring.unescape()` method is used by `querystring.parse()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement decoding implementation if + * necessary by assigning `querystring.unescape` to an alternative function. + * + * By default, the `querystring.unescape()` method will attempt to use the + * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, + * a safer equivalent that does not throw on malformed URLs will be used. + * @since v0.1.25 + */ + function unescape(str: string): string; +} +declare module "node:querystring" { + export * from "querystring"; +} diff --git a/node_modules/@types/node/readline.d.ts b/node_modules/@types/node/readline.d.ts new file mode 100644 index 0000000..338972e --- /dev/null +++ b/node_modules/@types/node/readline.d.ts @@ -0,0 +1,594 @@ +/** + * The `node:readline` module provides an interface for reading data from a [Readable](https://nodejs.org/docs/latest-v22.x/api/stream.html#readable-streams) stream + * (such as [`process.stdin`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdin)) one line at a time. + * + * To use the promise-based APIs: + * + * ```js + * import * as readline from 'node:readline/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as readline from 'node:readline'; + * ``` + * + * The following simple example illustrates the basic use of the `node:readline` module. + * + * ```js + * import * as readline from 'node:readline/promises'; + * import { stdin as input, stdout as output } from 'node:process'; + * + * const rl = readline.createInterface({ input, output }); + * + * const answer = await rl.question('What do you think of Node.js? '); + * + * console.log(`Thank you for your valuable feedback: ${answer}`); + * + * rl.close(); + * ``` + * + * Once this code is invoked, the Node.js application will not terminate until the `readline.Interface` is closed because the interface waits for data to be + * received on the `input` stream. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/readline.js) + */ +declare module "readline" { + import { Abortable, EventEmitter } from "node:events"; + import * as promises from "node:readline/promises"; + export { promises }; + export interface Key { + sequence?: string | undefined; + name?: string | undefined; + ctrl?: boolean | undefined; + meta?: boolean | undefined; + shift?: boolean | undefined; + } + /** + * Instances of the `readline.Interface` class are constructed using the `readline.createInterface()` method. Every instance is associated with a + * single `input` [Readable](https://nodejs.org/docs/latest-v22.x/api/stream.html#readable-streams) stream and a single `output` [Writable](https://nodejs.org/docs/latest-v22.x/api/stream.html#writable-streams) stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v0.1.104 + */ + export class Interface extends EventEmitter implements Disposable { + readonly terminal: boolean; + /** + * The current input data being processed by node. + * + * This can be used when collecting input from a TTY stream to retrieve the + * current value that has been processed thus far, prior to the `line` event + * being emitted. Once the `line` event has been emitted, this property will + * be an empty string. + * + * Be aware that modifying the value during the instance runtime may have + * unintended consequences if `rl.cursor` is not also controlled. + * + * **If not using a TTY stream for input, use the `'line'` event.** + * + * One possible use case would be as follows: + * + * ```js + * const values = ['lorem ipsum', 'dolor sit amet']; + * const rl = readline.createInterface(process.stdin); + * const showResults = debounce(() => { + * console.log( + * '\n', + * values.filter((val) => val.startsWith(rl.line)).join(' '), + * ); + * }, 300); + * process.stdin.on('keypress', (c, k) => { + * showResults(); + * }); + * ``` + * @since v0.1.98 + */ + readonly line: string; + /** + * The cursor position relative to `rl.line`. + * + * This will track where the current cursor lands in the input string, when + * reading input from a TTY stream. The position of cursor determines the + * portion of the input string that will be modified as input is processed, + * as well as the column where the terminal caret will be rendered. + * @since v0.1.98 + */ + readonly cursor: number; + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor(options: ReadLineOptions); + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.0, v14.17.0 + * @return the current prompt string + */ + getPrompt(): string; + /** + * The `rl.setPrompt()` method sets the prompt that will be written to `output` whenever `rl.prompt()` is called. + * @since v0.1.98 + */ + setPrompt(prompt: string): void; + /** + * The `rl.prompt()` method writes the `Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * location at which to provide input. + * + * When called, `rl.prompt()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the prompt is not written. + * @since v0.1.98 + * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. + */ + prompt(preserveCursor?: boolean): void; + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * The `callback` function passed to `rl.question()` does not follow the typical + * pattern of accepting an `Error` object or `null` as the first argument. + * The `callback` is called with the provided answer as the only argument. + * + * An error will be thrown if calling `rl.question()` after `rl.close()`. + * + * Example usage: + * + * ```js + * rl.question('What is your favorite food? ', (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * ``` + * + * Using an `AbortController` to cancel a question. + * + * ```js + * const ac = new AbortController(); + * const signal = ac.signal; + * + * rl.question('What is your favorite food? ', { signal }, (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * setTimeout(() => ac.abort(), 10000); + * ``` + * @since v0.3.3 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @param callback A callback function that is invoked with the user's input in response to the `query`. + */ + question(query: string, callback: (answer: string) => void): void; + question(query: string, options: Abortable, callback: (answer: string) => void): void; + /** + * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed + * later if necessary. + * + * Calling `rl.pause()` does not immediately pause other events (including `'line'`) from being emitted by the `Interface` instance. + * @since v0.3.4 + */ + pause(): this; + /** + * The `rl.resume()` method resumes the `input` stream if it has been paused. + * @since v0.3.4 + */ + resume(): this; + /** + * The `rl.close()` method closes the `Interface` instance and + * relinquishes control over the `input` and `output` streams. When called, + * the `'close'` event will be emitted. + * + * Calling `rl.close()` does not immediately stop other events (including `'line'`) + * from being emitted by the `Interface` instance. + * @since v0.1.98 + */ + close(): void; + /** + * Alias for `rl.close()`. + * @since v22.15.0 + */ + [Symbol.dispose](): void; + /** + * The `rl.write()` method will write either `data` or a key sequence identified + * by `key` to the `output`. The `key` argument is supported only if `output` is + * a `TTY` text terminal. See `TTY keybindings` for a list of key + * combinations. + * + * If `key` is specified, `data` is ignored. + * + * When called, `rl.write()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `data` and `key` are not written. + * + * ```js + * rl.write('Delete this!'); + * // Simulate Ctrl+U to delete the line written previously + * rl.write(null, { ctrl: true, name: 'u' }); + * ``` + * + * The `rl.write()` method will write the data to the `readline` `Interface`'s `input` _as if it were provided by the user_. + * @since v0.1.98 + */ + write(data: string | Buffer, key?: Key): void; + write(data: undefined | null | string | Buffer, key: Key): void; + /** + * Returns the real position of the cursor in relation to the input + * prompt + string. Long input (wrapping) strings, as well as multiple + * line prompts are included in the calculations. + * @since v13.5.0, v12.16.0 + */ + getCursorPos(): CursorPos; + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + * 8. history + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "history", listener: (history: string[]) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "history", history: string[]): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "history", listener: (history: string[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "history", listener: (history: string[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "history", listener: (history: string[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "history", listener: (history: string[]) => void): this; + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + } + export type ReadLine = Interface; // type forwarded for backwards compatibility + export type Completer = (line: string) => CompleterResult; + export type AsyncCompleter = ( + line: string, + callback: (err?: null | Error, result?: CompleterResult) => void, + ) => void; + export type CompleterResult = [string[], string]; + export interface ReadLineOptions { + /** + * The [`Readable`](https://nodejs.org/docs/latest-v22.x/api/stream.html#readable-streams) stream to listen to + */ + input: NodeJS.ReadableStream; + /** + * The [`Writable`](https://nodejs.org/docs/latest-v22.x/api/stream.html#writable-streams) stream to write readline data to. + */ + output?: NodeJS.WritableStream | undefined; + /** + * An optional function used for Tab autocompletion. + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * `true` if the `input` and `output` streams should be treated like a TTY, + * and have ANSI/VT100 escape codes written to it. + * Default: checking `isTTY` on the `output` stream upon instantiation. + */ + terminal?: boolean | undefined; + /** + * Initial list of history lines. + * This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, + * otherwise the history caching mechanism is not initialized at all. + * @default [] + */ + history?: string[] | undefined; + /** + * Maximum number of history lines retained. + * To disable the history set this value to `0`. + * This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, + * otherwise the history caching mechanism is not initialized at all. + * @default 30 + */ + historySize?: number | undefined; + /** + * If `true`, when a new input line added to the history list duplicates an older one, + * this removes the older line from the list. + * @default false + */ + removeHistoryDuplicates?: boolean | undefined; + /** + * The prompt string to use. + * @default "> " + */ + prompt?: string | undefined; + /** + * If the delay between `\r` and `\n` exceeds `crlfDelay` milliseconds, + * both `\r` and `\n` will be treated as separate end-of-line input. + * `crlfDelay` will be coerced to a number no less than `100`. + * It can be set to `Infinity`, in which case + * `\r` followed by `\n` will always be considered a single newline + * (which may be reasonable for [reading files](https://nodejs.org/docs/latest-v22.x/api/readline.html#example-read-file-stream-line-by-line) with `\r\n` line delimiter). + * @default 100 + */ + crlfDelay?: number | undefined; + /** + * The duration `readline` will wait for a character + * (when reading an ambiguous key sequence in milliseconds + * one that can both form a complete key sequence using the input read so far + * and can take additional input to complete a longer key sequence). + * @default 500 + */ + escapeCodeTimeout?: number | undefined; + /** + * The number of spaces a tab is equal to (minimum 1). + * @default 8 + */ + tabSize?: number | undefined; + /** + * Allows closing the interface using an AbortSignal. + * Aborting the signal will internally call `close` on the interface. + */ + signal?: AbortSignal | undefined; + } + /** + * The `readline.createInterface()` method creates a new `readline.Interface` instance. + * + * ```js + * import readline from 'node:readline'; + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readline.Interface` instance is created, the most common case is to + * listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * + * When creating a `readline.Interface` using `stdin` as input, the program + * will not terminate until it receives an [EOF character](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without + * waiting for user input, call `process.stdin.unref()`. + * @since v0.1.98 + */ + export function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + export function createInterface(options: ReadLineOptions): Interface; + /** + * The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. + * + * Optionally, `interface` specifies a `readline.Interface` instance for which + * autocompletion is disabled when copy-pasted input is detected. + * + * If the `stream` is a `TTY`, then it must be in raw mode. + * + * This is automatically called by any readline instance on its `input` if the `input` is a terminal. Closing the `readline` instance does not stop + * the `input` from emitting `'keypress'` events. + * + * ```js + * readline.emitKeypressEvents(process.stdin); + * if (process.stdin.isTTY) + * process.stdin.setRawMode(true); + * ``` + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * import readline from 'node:readline'; + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ', + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * import fs from 'node:fs'; + * import readline from 'node:readline'; + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity, + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * import fs from 'node:fs'; + * import readline from 'node:readline'; + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await` flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * import { once } from 'node:events'; + * import { createReadStream } from 'node:fs'; + * import { createInterface } from 'node:readline'; + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + */ + export function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + export type Direction = -1 | 0 | 1; + export interface CursorPos { + rows: number; + cols: number; + } + /** + * The `readline.clearLine()` method clears current line of given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) stream + * in a specified direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; + /** + * The `readline.clearScreenDown()` method clears the given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) stream from + * the current position of the cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; + /** + * The `readline.cursorTo()` method moves cursor to the specified position in a + * given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; + /** + * The `readline.moveCursor()` method moves the cursor _relative_ to its current + * position in a given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module "node:readline" { + export * from "readline"; +} diff --git a/node_modules/@types/node/readline/promises.d.ts b/node_modules/@types/node/readline/promises.d.ts new file mode 100644 index 0000000..5bc9a0c --- /dev/null +++ b/node_modules/@types/node/readline/promises.d.ts @@ -0,0 +1,161 @@ +/** + * @since v17.0.0 + */ +declare module "readline/promises" { + import { Abortable } from "node:events"; + import { + CompleterResult, + Direction, + Interface as _Interface, + ReadLineOptions as _ReadLineOptions, + } from "node:readline"; + /** + * Instances of the `readlinePromises.Interface` class are constructed using the `readlinePromises.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v17.0.0 + */ + class Interface extends _Interface { + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * If the question is called after `rl.close()`, it returns a rejected promise. + * + * Example usage: + * + * ```js + * const answer = await rl.question('What is your favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * Using an `AbortSignal` to cancel a question. + * + * ```js + * const signal = AbortSignal.timeout(10_000); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * const answer = await rl.question('What is your favorite food? ', { signal }); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * @since v17.0.0 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @return A promise that is fulfilled with the user's input in response to the `query`. + */ + question(query: string): Promise; + question(query: string, options: Abortable): Promise; + } + /** + * @since v17.0.0 + */ + class Readline { + /** + * @param stream A TTY stream. + */ + constructor( + stream: NodeJS.WritableStream, + options?: { + autoCommit?: boolean | undefined; + }, + ); + /** + * The `rl.clearLine()` method adds to the internal list of pending action an + * action that clears current line of the associated `stream` in a specified + * direction identified by `dir`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearLine(dir: Direction): this; + /** + * The `rl.clearScreenDown()` method adds to the internal list of pending action an + * action that clears the associated stream from the current position of the + * cursor down. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearScreenDown(): this; + /** + * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. + * @since v17.0.0 + */ + commit(): Promise; + /** + * The `rl.cursorTo()` method adds to the internal list of pending action an action + * that moves cursor to the specified position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + cursorTo(x: number, y?: number): this; + /** + * The `rl.moveCursor()` method adds to the internal list of pending action an + * action that moves the cursor _relative_ to its current position in the + * associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + moveCursor(dx: number, dy: number): this; + /** + * The `rl.rollback` methods clears the internal list of pending actions without + * sending it to the associated `stream`. + * @since v17.0.0 + * @return this + */ + rollback(): this; + } + type Completer = (line: string) => CompleterResult | Promise; + interface ReadLineOptions extends Omit<_ReadLineOptions, "completer"> { + /** + * An optional function used for Tab autocompletion. + */ + completer?: Completer | undefined; + } + /** + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. + * + * ```js + * import readlinePromises from 'node:readline/promises'; + * const rl = readlinePromises.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readlinePromises.Interface` instance is created, the most common case + * is to listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * @since v17.0.0 + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; +} +declare module "node:readline/promises" { + export * from "readline/promises"; +} diff --git a/node_modules/@types/node/repl.d.ts b/node_modules/@types/node/repl.d.ts new file mode 100644 index 0000000..fb858da --- /dev/null +++ b/node_modules/@types/node/repl.d.ts @@ -0,0 +1,428 @@ +/** + * The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation + * that is available both as a standalone program or includible in other + * applications. It can be accessed using: + * + * ```js + * import repl from 'node:repl'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/repl.js) + */ +declare module "repl" { + import { AsyncCompleter, Completer, Interface } from "node:readline"; + import { Context } from "node:vm"; + import { InspectOptions } from "node:util"; + interface ReplOptions { + /** + * The input prompt to display. + * @default "> " + */ + prompt?: string | undefined; + /** + * The `Readable` stream from which REPL input will be read. + * @default process.stdin + */ + input?: NodeJS.ReadableStream | undefined; + /** + * The `Writable` stream to which REPL output will be written. + * @default process.stdout + */ + output?: NodeJS.WritableStream | undefined; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean | undefined; + /** + * The function to be used when evaluating each given line of input. + * **Default:** an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. See the [custom evaluation functions](https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#custom-evaluation-functions) + * section for more details. + */ + eval?: REPLEval | undefined; + /** + * Defines if the repl prints output previews or not. + * @default `true` Always `false` in case `terminal` is falsy. + */ + preview?: boolean | undefined; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * @default the REPL instance's `terminal` value + */ + useColors?: boolean | undefined; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * @default false + */ + useGlobal?: boolean | undefined; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * @default false + */ + ignoreUndefined?: boolean | undefined; + /** + * The function to invoke to format the output of each command before writing to `output`. + * @default a wrapper for `util.inspect` + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter | undefined; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * @default false + */ + breakEvalOnSigint?: boolean | undefined; + } + type REPLEval = ( + this: REPLServer, + evalCmd: string, + context: Context, + file: string, + cb: (err: Error | null, result: any) => void, + ) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { + options: InspectOptions; + }; + type REPLCommandAction = (this: REPLServer, text: string) => void; + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string | undefined; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + /** + * Instances of `repl.REPLServer` are created using the {@link start} method + * or directly using the JavaScript `new` keyword. + * + * ```js + * import repl from 'node:repl'; + * + * const options = { useColors: true }; + * + * const firstInstance = repl.start(options); + * const secondInstance = new repl.REPLServer(options); + * ``` + * @since v0.1.91 + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * @deprecated since v14.3.0 - Use `input` instead. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * @deprecated since v14.3.0 - Use `output` instead. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly input: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly output: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: NodeJS.ReadOnlyDict; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + /** + * The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands + * to the REPL instance. Such commands are invoked by typing a `.` followed by the `keyword`. The `cmd` is either a `Function` or an `Object` with the following + * properties: + * + * The following example shows two new commands added to the REPL instance: + * + * ```js + * import repl from 'node:repl'; + * + * const replServer = repl.start({ prompt: '> ' }); + * replServer.defineCommand('sayhello', { + * help: 'Say hello', + * action(name) { + * this.clearBufferedCommand(); + * console.log(`Hello, ${name}!`); + * this.displayPrompt(); + * }, + * }); + * replServer.defineCommand('saybye', function saybye() { + * console.log('Goodbye!'); + * this.close(); + * }); + * ``` + * + * The new commands can then be used from within the REPL instance: + * + * ```console + * > .sayhello Node.js User + * Hello, Node.js User! + * > .saybye + * Goodbye! + * ``` + * @since v0.3.0 + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * The `replServer.displayPrompt()` method readies the REPL instance for input + * from the user, printing the configured `prompt` to a new line in the `output` and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the + * 'prompt'. + * + * When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. + * + * The `replServer.displayPrompt` method is primarily intended to be called from + * within the action function for commands registered using the `replServer.defineCommand()` method. + * @since v0.1.91 + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * The `replServer.clearBufferedCommand()` method clears any command that has been + * buffered but not yet executed. This method is primarily intended to be + * called from within the action function for commands registered using the `replServer.defineCommand()` method. + * @since v9.0.0 + */ + clearBufferedCommand(): void; + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command-line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @since v11.10.0 + * @param historyPath the path to the history file + * @param callback called when history writes are ready or upon error + */ + setupHistory(path: string, callback: (err: Error | null, repl: this) => void): void; + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: (context: Context) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: Context): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: (context: Context) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: (context: Context) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: (context: Context) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: (context: Context) => void): this; + } + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + const REPL_MODE_SLOPPY: unique symbol; + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + const REPL_MODE_STRICT: unique symbol; + /** + * The `repl.start()` method creates and starts a {@link REPLServer} instance. + * + * If `options` is a string, then it specifies the input prompt: + * + * ```js + * import repl from 'node:repl'; + * + * // a Unix style prompt + * repl.start('$ '); + * ``` + * @since v0.1.91 + */ + function start(options?: string | ReplOptions): REPLServer; + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + constructor(err: Error); + } +} +declare module "node:repl" { + export * from "repl"; +} diff --git a/node_modules/@types/node/sea.d.ts b/node_modules/@types/node/sea.d.ts new file mode 100644 index 0000000..3013074 --- /dev/null +++ b/node_modules/@types/node/sea.d.ts @@ -0,0 +1,153 @@ +/** + * This feature allows the distribution of a Node.js application conveniently to a + * system that does not have Node.js installed. + * + * Node.js supports the creation of [single executable applications](https://github.com/nodejs/single-executable) by allowing + * the injection of a blob prepared by Node.js, which can contain a bundled script, + * into the `node` binary. During start up, the program checks if anything has been + * injected. If the blob is found, it executes the script in the blob. Otherwise + * Node.js operates as it normally does. + * + * The single executable application feature currently only supports running a + * single embedded script using the `CommonJS` module system. + * + * Users can create a single executable application from their bundled script + * with the `node` binary itself and any tool which can inject resources into the + * binary. + * + * Here are the steps for creating a single executable application using one such + * tool, [postject](https://github.com/nodejs/postject): + * + * 1. Create a JavaScript file: + * ```bash + * echo 'console.log(`Hello, ${process.argv[2]}!`);' > hello.js + * ``` + * 2. Create a configuration file building a blob that can be injected into the + * single executable application (see `Generating single executable preparation blobs` for details): + * ```bash + * echo '{ "main": "hello.js", "output": "sea-prep.blob" }' > sea-config.json + * ``` + * 3. Generate the blob to be injected: + * ```bash + * node --experimental-sea-config sea-config.json + * ``` + * 4. Create a copy of the `node` executable and name it according to your needs: + * * On systems other than Windows: + * ```bash + * cp $(command -v node) hello + * ``` + * * On Windows: + * ```text + * node -e "require('fs').copyFileSync(process.execPath, 'hello.exe')" + * ``` + * The `.exe` extension is necessary. + * 5. Remove the signature of the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --remove-signature hello + * ``` + * * On Windows (optional): + * [signtool](https://learn.microsoft.com/en-us/windows/win32/seccrypto/signtool) can be used from the installed [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/). + * If this step is + * skipped, ignore any signature-related warning from postject. + * ```powershell + * signtool remove /s hello.exe + * ``` + * 6. Inject the blob into the copied binary by running `postject` with + * the following options: + * * `hello` / `hello.exe` \- The name of the copy of the `node` executable + * created in step 4. + * * `NODE_SEA_BLOB` \- The name of the resource / note / section in the binary + * where the contents of the blob will be stored. + * * `sea-prep.blob` \- The name of the blob created in step 1. + * * `--sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2` \- The [fuse](https://www.electronjs.org/docs/latest/tutorial/fuses) used by the Node.js project to detect if a file has been + * injected. + * * `--macho-segment-name NODE_SEA` (only needed on macOS) - The name of the + * segment in the binary where the contents of the blob will be + * stored. + * To summarize, here is the required command for each platform: + * * On Linux: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - PowerShell: + * ```powershell + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ` + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - Command Prompt: + * ```text + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ^ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On macOS: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \ + * --macho-segment-name NODE_SEA + * ``` + * 7. Sign the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --sign - hello + * ``` + * * On Windows (optional): + * A certificate needs to be present for this to work. However, the unsigned + * binary would still be runnable. + * ```powershell + * signtool sign /fd SHA256 hello.exe + * ``` + * 8. Run the binary: + * * On systems other than Windows + * ```console + * $ ./hello world + * Hello, world! + * ``` + * * On Windows + * ```console + * $ .\hello.exe world + * Hello, world! + * ``` + * @since v19.7.0, v18.16.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v22.x/src/node_sea.cc) + */ +declare module "node:sea" { + type AssetKey = string; + /** + * @since v20.12.0 + * @return Whether this script is running inside a single-executable application. + */ + function isSea(): boolean; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAsset(key: AssetKey): ArrayBuffer; + function getAsset(key: AssetKey, encoding: string): string; + /** + * Similar to `sea.getAsset()`, but returns the result in a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob). + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAssetAsBlob(key: AssetKey, options?: { + type: string; + }): Blob; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * + * Unlike `sea.getRawAsset()` or `sea.getAssetAsBlob()`, this method does not + * return a copy. Instead, it returns the raw asset bundled inside the executable. + * + * For now, users should avoid writing to the returned array buffer. If the + * injected section is not marked as writable or not aligned properly, + * writes to the returned array buffer is likely to result in a crash. + * @since v20.12.0 + */ + function getRawAsset(key: AssetKey): ArrayBuffer; +} diff --git a/node_modules/@types/node/sqlite.d.ts b/node_modules/@types/node/sqlite.d.ts new file mode 100644 index 0000000..19d826d --- /dev/null +++ b/node_modules/@types/node/sqlite.d.ts @@ -0,0 +1,721 @@ +/** + * The `node:sqlite` module facilitates working with SQLite databases. + * To access it: + * + * ```js + * import sqlite from 'node:sqlite'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import sqlite from 'sqlite'; + * ``` + * + * The following example shows the basic usage of the `node:sqlite` module to open + * an in-memory database, write data to the database, and then read the data back. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * const database = new DatabaseSync(':memory:'); + * + * // Execute SQL statements from strings. + * database.exec(` + * CREATE TABLE data( + * key INTEGER PRIMARY KEY, + * value TEXT + * ) STRICT + * `); + * // Create a prepared statement to insert data into the database. + * const insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)'); + * // Execute the prepared statement with bound values. + * insert.run(1, 'hello'); + * insert.run(2, 'world'); + * // Create a prepared statement to read data from the database. + * const query = database.prepare('SELECT * FROM data ORDER BY key'); + * // Execute the prepared statement and log the result set. + * console.log(query.all()); + * // Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ] + * ``` + * @since v22.5.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/sqlite.js) + */ +declare module "node:sqlite" { + import { PathLike } from "node:fs"; + type SQLInputValue = null | number | bigint | string | NodeJS.ArrayBufferView; + type SQLOutputValue = null | number | bigint | string | NodeJS.NonSharedUint8Array; + interface DatabaseSyncOptions { + /** + * If `true`, the database is opened by the constructor. When + * this value is `false`, the database must be opened via the `open()` method. + * @since v22.5.0 + * @default true + */ + open?: boolean | undefined; + /** + * If `true`, foreign key constraints + * are enabled. This is recommended but can be disabled for compatibility with + * legacy database schemas. The enforcement of foreign key constraints can be + * enabled and disabled after opening the database using + * [`PRAGMA foreign_keys`](https://www.sqlite.org/pragma.html#pragma_foreign_keys). + * @since v22.10.0 + * @default true + */ + enableForeignKeyConstraints?: boolean | undefined; + /** + * If `true`, SQLite will accept + * [double-quoted string literals](https://www.sqlite.org/quirks.html#dblquote). + * This is not recommended but can be + * enabled for compatibility with legacy database schemas. + * @since v22.10.0 + * @default false + */ + enableDoubleQuotedStringLiterals?: boolean | undefined; + /** + * If `true`, the database is opened in read-only mode. + * If the database does not exist, opening it will fail. + * @since v22.12.0 + * @default false + */ + readOnly?: boolean | undefined; + /** + * If `true`, the `loadExtension` SQL function + * and the `loadExtension()` method are enabled. + * You can call `enableLoadExtension(false)` later to disable this feature. + * @since v22.13.0 + * @default false + */ + allowExtension?: boolean | undefined; + /** + * The [busy timeout](https://sqlite.org/c3ref/busy_timeout.html) in milliseconds. This is the maximum amount of + * time that SQLite will wait for a database lock to be released before + * returning an error. + * @since v22.16.0 + * @default 0 + */ + timeout?: number | undefined; + /** + * If `true`, integer fields are read as JavaScript `BigInt` values. If `false`, + * integer fields are read as JavaScript numbers. + * @since v22.18.0 + * @default false + */ + readBigInts?: boolean | undefined; + /** + * If `true`, query results are returned as arrays instead of objects. + * @since v22.18.0 + * @default false + */ + returnArrays?: boolean | undefined; + /** + * If `true`, allows binding named parameters without the prefix + * character (e.g., `foo` instead of `:foo`). + * @since v22.18.0 + * @default true + */ + allowBareNamedParameters?: boolean | undefined; + /** + * If `true`, unknown named parameters are ignored when binding. + * If `false`, an exception is thrown for unknown named parameters. + * @since v22.18.0 + * @default false + */ + allowUnknownNamedParameters?: boolean | undefined; + } + interface CreateSessionOptions { + /** + * A specific table to track changes for. By default, changes to all tables are tracked. + * @since v22.12.0 + */ + table?: string | undefined; + /** + * Name of the database to track. This is useful when multiple databases have been added using + * [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html). + * @since v22.12.0 + * @default 'main' + */ + db?: string | undefined; + } + interface ApplyChangesetOptions { + /** + * Skip changes that, when targeted table name is supplied to this function, return a truthy value. + * By default, all changes are attempted. + * @since v22.12.0 + */ + filter?: ((tableName: string) => boolean) | undefined; + /** + * A function that determines how to handle conflicts. The function receives one argument, + * which can be one of the following values: + * + * * `SQLITE_CHANGESET_DATA`: A `DELETE` or `UPDATE` change does not contain the expected "before" values. + * * `SQLITE_CHANGESET_NOTFOUND`: A row matching the primary key of the `DELETE` or `UPDATE` change does not exist. + * * `SQLITE_CHANGESET_CONFLICT`: An `INSERT` change results in a duplicate primary key. + * * `SQLITE_CHANGESET_FOREIGN_KEY`: Applying a change would result in a foreign key violation. + * * `SQLITE_CHANGESET_CONSTRAINT`: Applying a change results in a `UNIQUE`, `CHECK`, or `NOT NULL` constraint + * violation. + * + * The function should return one of the following values: + * + * * `SQLITE_CHANGESET_OMIT`: Omit conflicting changes. + * * `SQLITE_CHANGESET_REPLACE`: Replace existing values with conflicting changes (only valid with + `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT` conflicts). + * * `SQLITE_CHANGESET_ABORT`: Abort on conflict and roll back the database. + * + * When an error is thrown in the conflict handler or when any other value is returned from the handler, + * applying the changeset is aborted and the database is rolled back. + * + * **Default**: A function that returns `SQLITE_CHANGESET_ABORT`. + * @since v22.12.0 + */ + onConflict?: ((conflictType: number) => number) | undefined; + } + interface FunctionOptions { + /** + * If `true`, the [`SQLITE_DETERMINISTIC`](https://www.sqlite.org/c3ref/c_deterministic.html) flag is + * set on the created function. + * @default false + */ + deterministic?: boolean | undefined; + /** + * If `true`, the [`SQLITE_DIRECTONLY`](https://www.sqlite.org/c3ref/c_directonly.html) flag is set on + * the created function. + * @default false + */ + directOnly?: boolean | undefined; + /** + * If `true`, integer arguments to `function` + * are converted to `BigInt`s. If `false`, integer arguments are passed as + * JavaScript numbers. + * @default false + */ + useBigIntArguments?: boolean | undefined; + /** + * If `true`, `function` may be invoked with any number of + * arguments (between zero and + * [`SQLITE_MAX_FUNCTION_ARG`](https://www.sqlite.org/limits.html#max_function_arg)). If `false`, + * `function` must be invoked with exactly `function.length` arguments. + * @default false + */ + varargs?: boolean | undefined; + } + interface AggregateOptions extends FunctionOptions { + /** + * The identity value for the aggregation function. This value is used when the aggregation + * function is initialized. When a `Function` is passed the identity will be its return value. + */ + start: T | (() => T); + /** + * The function to call for each row in the aggregation. The + * function receives the current state and the row value. The return value of + * this function should be the new state. + */ + step: (accumulator: T, ...args: SQLOutputValue[]) => T; + /** + * The function to call to get the result of the + * aggregation. The function receives the final state and should return the + * result of the aggregation. + */ + result?: ((accumulator: T) => SQLInputValue) | undefined; + /** + * When this function is provided, the `aggregate` method will work as a window function. + * The function receives the current state and the dropped row value. The return value of this function should be the + * new state. + */ + inverse?: ((accumulator: T, ...args: SQLOutputValue[]) => T) | undefined; + } + /** + * This class represents a single [connection](https://www.sqlite.org/c3ref/sqlite3.html) to a SQLite database. All APIs + * exposed by this class execute synchronously. + * @since v22.5.0 + */ + class DatabaseSync implements Disposable { + /** + * Constructs a new `DatabaseSync` instance. + * @param path The path of the database. + * A SQLite database can be stored in a file or completely [in memory](https://www.sqlite.org/inmemorydb.html). + * To use a file-backed database, the path should be a file path. + * To use an in-memory database, the path should be the special name `':memory:'`. + * @param options Configuration options for the database connection. + */ + constructor(path: PathLike, options?: DatabaseSyncOptions); + /** + * Registers a new aggregate function with the SQLite database. This method is a wrapper around + * [`sqlite3_create_window_function()`](https://www.sqlite.org/c3ref/create_function.html). + * + * When used as a window function, the `result` function will be called multiple times. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * + * const db = new DatabaseSync(':memory:'); + * db.exec(` + * CREATE TABLE t3(x, y); + * INSERT INTO t3 VALUES ('a', 4), + * ('b', 5), + * ('c', 3), + * ('d', 8), + * ('e', 1); + * `); + * + * db.aggregate('sumint', { + * start: 0, + * step: (acc, value) => acc + value, + * }); + * + * db.prepare('SELECT sumint(y) as total FROM t3').get(); // { total: 21 } + * ``` + * @since v22.16.0 + * @param name The name of the SQLite function to create. + * @param options Function configuration settings. + */ + aggregate(name: string, options: AggregateOptions): void; + aggregate(name: string, options: AggregateOptions): void; + /** + * Closes the database connection. An exception is thrown if the database is not + * open. This method is a wrapper around [`sqlite3_close_v2()`](https://www.sqlite.org/c3ref/close.html). + * @since v22.5.0 + */ + close(): void; + /** + * Loads a shared library into the database connection. This method is a wrapper + * around [`sqlite3_load_extension()`](https://www.sqlite.org/c3ref/load_extension.html). It is required to enable the + * `allowExtension` option when constructing the `DatabaseSync` instance. + * @since v22.13.0 + * @param path The path to the shared library to load. + */ + loadExtension(path: string): void; + /** + * Enables or disables the `loadExtension` SQL function, and the `loadExtension()` + * method. When `allowExtension` is `false` when constructing, you cannot enable + * loading extensions for security reasons. + * @since v22.13.0 + * @param allow Whether to allow loading extensions. + */ + enableLoadExtension(allow: boolean): void; + /** + * This method is a wrapper around [`sqlite3_db_filename()`](https://sqlite.org/c3ref/db_filename.html) + * @since v22.16.0 + * @param dbName Name of the database. This can be `'main'` (the default primary database) or any other + * database that has been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) **Default:** `'main'`. + * @returns The location of the database file. When using an in-memory database, + * this method returns null. + */ + location(dbName?: string): string | null; + /** + * This method allows one or more SQL statements to be executed without returning + * any results. This method is useful when executing SQL statements read from a + * file. This method is a wrapper around [`sqlite3_exec()`](https://www.sqlite.org/c3ref/exec.html). + * @since v22.5.0 + * @param sql A SQL string to execute. + */ + exec(sql: string): void; + /** + * This method is used to create SQLite user-defined functions. This method is a + * wrapper around [`sqlite3_create_function_v2()`](https://www.sqlite.org/c3ref/create_function.html). + * @since v22.13.0 + * @param name The name of the SQLite function to create. + * @param options Optional configuration settings for the function. + * @param func The JavaScript function to call when the SQLite + * function is invoked. The return value of this function should be a valid + * SQLite data type: see + * [Type conversion between JavaScript and SQLite](https://nodejs.org/docs/latest-v22.x/api/sqlite.html#type-conversion-between-javascript-and-sqlite). + * The result defaults to `NULL` if the return value is `undefined`. + */ + function( + name: string, + options: FunctionOptions, + func: (...args: SQLOutputValue[]) => SQLInputValue, + ): void; + function(name: string, func: (...args: SQLOutputValue[]) => SQLInputValue): void; + /** + * Whether the database is currently open or not. + * @since v22.15.0 + */ + readonly isOpen: boolean; + /** + * Whether the database is currently within a transaction. This method + * is a wrapper around [`sqlite3_get_autocommit()`](https://sqlite.org/c3ref/get_autocommit.html). + * @since v22.16.0 + */ + readonly isTransaction: boolean; + /** + * Opens the database specified in the `path` argument of the `DatabaseSync`constructor. This method should only be used when the database is not opened via + * the constructor. An exception is thrown if the database is already open. + * @since v22.5.0 + */ + open(): void; + /** + * Compiles a SQL statement into a [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This method is a wrapper + * around [`sqlite3_prepare_v2()`](https://www.sqlite.org/c3ref/prepare.html). + * @since v22.5.0 + * @param sql A SQL string to compile to a prepared statement. + * @return The prepared statement. + */ + prepare(sql: string): StatementSync; + /** + * Creates and attaches a session to the database. This method is a wrapper around + * [`sqlite3session_create()`](https://www.sqlite.org/session/sqlite3session_create.html) and + * [`sqlite3session_attach()`](https://www.sqlite.org/session/sqlite3session_attach.html). + * @param options The configuration options for the session. + * @returns A session handle. + * @since v22.12.0 + */ + createSession(options?: CreateSessionOptions): Session; + /** + * An exception is thrown if the database is not + * open. This method is a wrapper around + * [`sqlite3changeset_apply()`](https://www.sqlite.org/session/sqlite3changeset_apply.html). + * + * ```js + * const sourceDb = new DatabaseSync(':memory:'); + * const targetDb = new DatabaseSync(':memory:'); + * + * sourceDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)'); + * targetDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)'); + * + * const session = sourceDb.createSession(); + * + * const insert = sourceDb.prepare('INSERT INTO data (key, value) VALUES (?, ?)'); + * insert.run(1, 'hello'); + * insert.run(2, 'world'); + * + * const changeset = session.changeset(); + * targetDb.applyChangeset(changeset); + * // Now that the changeset has been applied, targetDb contains the same data as sourceDb. + * ``` + * @param changeset A binary changeset or patchset. + * @param options The configuration options for how the changes will be applied. + * @returns Whether the changeset was applied successfully without being aborted. + * @since v22.12.0 + */ + applyChangeset(changeset: Uint8Array, options?: ApplyChangesetOptions): boolean; + /** + * Closes the database connection. If the database connection is already closed + * then this is a no-op. + * @since v22.15.0 + * @experimental + */ + [Symbol.dispose](): void; + } + /** + * @since v22.12.0 + */ + interface Session { + /** + * Retrieves a changeset containing all changes since the changeset was created. Can be called multiple times. + * An exception is thrown if the database or the session is not open. This method is a wrapper around + * [`sqlite3session_changeset()`](https://www.sqlite.org/session/sqlite3session_changeset.html). + * @returns Binary changeset that can be applied to other databases. + * @since v22.12.0 + */ + changeset(): NodeJS.NonSharedUint8Array; + /** + * Similar to the method above, but generates a more compact patchset. See + * [Changesets and Patchsets](https://www.sqlite.org/sessionintro.html#changesets_and_patchsets) + * in the documentation of SQLite. An exception is thrown if the database or the session is not open. This method is a + * wrapper around + * [`sqlite3session_patchset()`](https://www.sqlite.org/session/sqlite3session_patchset.html). + * @returns Binary patchset that can be applied to other databases. + * @since v22.12.0 + */ + patchset(): NodeJS.NonSharedUint8Array; + /** + * Closes the session. An exception is thrown if the database or the session is not open. This method is a + * wrapper around + * [`sqlite3session_delete()`](https://www.sqlite.org/session/sqlite3session_delete.html). + */ + close(): void; + } + interface StatementColumnMetadata { + /** + * The unaliased name of the column in the origin + * table, or `null` if the column is the result of an expression or subquery. + * This property is the result of [`sqlite3_column_origin_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + column: string | null; + /** + * The unaliased name of the origin database, or + * `null` if the column is the result of an expression or subquery. This + * property is the result of [`sqlite3_column_database_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + database: string | null; + /** + * The name assigned to the column in the result set of a + * `SELECT` statement. This property is the result of + * [`sqlite3_column_name()`](https://www.sqlite.org/c3ref/column_name.html). + */ + name: string; + /** + * The unaliased name of the origin table, or `null` if + * the column is the result of an expression or subquery. This property is the + * result of [`sqlite3_column_table_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + table: string | null; + /** + * The declared data type of the column, or `null` if the + * column is the result of an expression or subquery. This property is the + * result of [`sqlite3_column_decltype()`](https://www.sqlite.org/c3ref/column_decltype.html). + */ + type: string | null; + } + interface StatementResultingChanges { + /** + * The number of rows modified, inserted, or deleted by the most recently completed `INSERT`, `UPDATE`, or `DELETE` statement. + * This field is either a number or a `BigInt` depending on the prepared statement's configuration. + * This property is the result of [`sqlite3_changes64()`](https://www.sqlite.org/c3ref/changes.html). + */ + changes: number | bigint; + /** + * The most recently inserted rowid. + * This field is either a number or a `BigInt` depending on the prepared statement's configuration. + * This property is the result of [`sqlite3_last_insert_rowid()`](https://www.sqlite.org/c3ref/last_insert_rowid.html). + */ + lastInsertRowid: number | bigint; + } + /** + * This class represents a single [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This class cannot be + * instantiated via its constructor. Instead, instances are created via the`database.prepare()` method. All APIs exposed by this class execute + * synchronously. + * + * A prepared statement is an efficient binary representation of the SQL used to + * create it. Prepared statements are parameterizable, and can be invoked multiple + * times with different bound values. Parameters also offer protection against [SQL injection](https://en.wikipedia.org/wiki/SQL_injection) attacks. For these reasons, prepared statements are + * preferred + * over hand-crafted SQL strings when handling user input. + * @since v22.5.0 + */ + class StatementSync { + private constructor(); + /** + * This method executes a prepared statement and returns all results as an array of + * objects. If the prepared statement does not return any results, this method + * returns an empty array. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using + * the values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @return An array of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of + * the row. + */ + all(...anonymousParameters: SQLInputValue[]): Record[]; + all( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): Record[]; + /** + * This method is used to retrieve information about the columns returned by the + * prepared statement. + * @since v22.16.0 + * @returns An array of objects. Each object corresponds to a column + * in the prepared statement, and contains the following properties: + */ + columns(): StatementColumnMetadata[]; + /** + * The source SQL text of the prepared statement with parameter + * placeholders replaced by the values that were used during the most recent + * execution of this prepared statement. This property is a wrapper around + * [`sqlite3_expanded_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html). + * @since v22.5.0 + */ + readonly expandedSQL: string; + /** + * This method executes a prepared statement and returns the first result as an + * object. If the prepared statement does not return any results, this method + * returns `undefined`. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the + * values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @return An object corresponding to the first row returned by executing the prepared statement. The keys and values of the object correspond to the column names and values of the row. If no + * rows were returned from the database then this method returns `undefined`. + */ + get(...anonymousParameters: SQLInputValue[]): Record | undefined; + get( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): Record | undefined; + /** + * This method executes a prepared statement and returns an iterator of + * objects. If the prepared statement does not return any results, this method + * returns an empty iterator. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using + * the values in `namedParameters` and `anonymousParameters`. + * @since v22.13.0 + * @param namedParameters An optional object used to bind named parameters. + * The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @returns An iterable iterator of objects. Each object corresponds to a row + * returned by executing the prepared statement. The keys and values of each + * object correspond to the column names and values of the row. + */ + iterate(...anonymousParameters: SQLInputValue[]): NodeJS.Iterator>; + iterate( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): NodeJS.Iterator>; + /** + * This method executes a prepared statement and returns an object summarizing the + * resulting changes. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the + * values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + */ + run(...anonymousParameters: SQLInputValue[]): StatementResultingChanges; + run( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): StatementResultingChanges; + /** + * The names of SQLite parameters begin with a prefix character. By default,`node:sqlite` requires that this prefix character is present when binding + * parameters. However, with the exception of dollar sign character, these + * prefix characters also require extra quoting when used in object keys. + * + * To improve ergonomics, this method can be used to also allow bare named + * parameters, which do not require the prefix character in JavaScript code. There + * are several caveats to be aware of when enabling bare named parameters: + * + * * The prefix character is still required in SQL. + * * The prefix character is still allowed in JavaScript. In fact, prefixed names + * will have slightly better binding performance. + * * Using ambiguous named parameters, such as `$k` and `@k`, in the same prepared + * statement will result in an exception as it cannot be determined how to bind + * a bare name. + * @since v22.5.0 + * @param enabled Enables or disables support for binding named parameters without the prefix character. + */ + setAllowBareNamedParameters(enabled: boolean): void; + /** + * By default, if an unknown name is encountered while binding parameters, an + * exception is thrown. This method allows unknown named parameters to be ignored. + * @since v22.15.0 + * @param enabled Enables or disables support for unknown named parameters. + */ + setAllowUnknownNamedParameters(enabled: boolean): void; + /** + * When enabled, query results returned by the `all()`, `get()`, and `iterate()` methods will be returned as arrays instead + * of objects. + * @since v22.16.0 + * @param enabled Enables or disables the return of query results as arrays. + */ + setReturnArrays(enabled: boolean): void; + /** + * When reading from the database, SQLite `INTEGER`s are mapped to JavaScript + * numbers by default. However, SQLite `INTEGER`s can store values larger than + * JavaScript numbers are capable of representing. In such cases, this method can + * be used to read `INTEGER` data using JavaScript `BigInt`s. This method has no + * impact on database write operations where numbers and `BigInt`s are both + * supported at all times. + * @since v22.5.0 + * @param enabled Enables or disables the use of `BigInt`s when reading `INTEGER` fields from the database. + */ + setReadBigInts(enabled: boolean): void; + /** + * The source SQL text of the prepared statement. This property is a + * wrapper around [`sqlite3_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html). + * @since v22.5.0 + */ + readonly sourceSQL: string; + } + interface BackupOptions { + /** + * Name of the source database. This can be `'main'` (the default primary database) or any other + * database that have been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) + * @default 'main' + */ + source?: string | undefined; + /** + * Name of the target database. This can be `'main'` (the default primary database) or any other + * database that have been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) + * @default 'main' + */ + target?: string | undefined; + /** + * Number of pages to be transmitted in each batch of the backup. + * @default 100 + */ + rate?: number | undefined; + /** + * Callback function that will be called with the number of pages copied and the total number of + * pages. + */ + progress?: ((progressInfo: BackupProgressInfo) => void) | undefined; + } + interface BackupProgressInfo { + totalPages: number; + remainingPages: number; + } + /** + * This method makes a database backup. This method abstracts the + * [`sqlite3_backup_init()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupinit), + * [`sqlite3_backup_step()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupstep) + * and [`sqlite3_backup_finish()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupfinish) functions. + * + * The backed-up database can be used normally during the backup process. Mutations coming from the same connection - same + * `DatabaseSync` - object will be reflected in the backup right away. However, mutations from other connections will cause + * the backup process to restart. + * + * ```js + * import { backup, DatabaseSync } from 'node:sqlite'; + * + * const sourceDb = new DatabaseSync('source.db'); + * const totalPagesTransferred = await backup(sourceDb, 'backup.db', { + * rate: 1, // Copy one page at a time. + * progress: ({ totalPages, remainingPages }) => { + * console.log('Backup in progress', { totalPages, remainingPages }); + * }, + * }); + * + * console.log('Backup completed', totalPagesTransferred); + * ``` + * @since v22.16.0 + * @param sourceDb The database to backup. The source database must be open. + * @param path The path where the backup will be created. If the file already exists, + * the contents will be overwritten. + * @param options Optional configuration for the backup. The + * following properties are supported: + * @returns A promise that resolves when the backup is completed and rejects if an error occurs. + */ + function backup(sourceDb: DatabaseSync, path: PathLike, options?: BackupOptions): Promise; + /** + * @since v22.13.0 + */ + namespace constants { + /** + * The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is present in the database, but one or more other (non primary-key) fields modified by the update do not contain the expected "before" values. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_DATA: number; + /** + * The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is not present in the database. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_NOTFOUND: number; + /** + * This constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_CONFLICT: number; + /** + * If foreign key handling is enabled, and applying a changeset leaves the database in a state containing foreign key violations, the conflict handler is invoked with this constant exactly once before the changeset is committed. If the conflict handler returns `SQLITE_CHANGESET_OMIT`, the changes, including those that caused the foreign key constraint violation, are committed. Or, if it returns `SQLITE_CHANGESET_ABORT`, the changeset is rolled back. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_FOREIGN_KEY: number; + /** + * Conflicting changes are omitted. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_OMIT: number; + /** + * Conflicting changes replace existing values. Note that this value can only be returned when the type of conflict is either `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT`. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_REPLACE: number; + /** + * Abort when a change encounters a conflict and roll back database. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_ABORT: number; + } +} diff --git a/node_modules/@types/node/stream.d.ts b/node_modules/@types/node/stream.d.ts new file mode 100644 index 0000000..dec1bcc --- /dev/null +++ b/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1687 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `node:stream` module provides an API for implementing the stream interface. + * + * There are many stream objects provided by Node.js. For instance, a [request to an HTTP server](https://nodejs.org/docs/latest-v22.x/api/http.html#class-httpincomingmessage) + * and [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of [`EventEmitter`](https://nodejs.org/docs/latest-v22.x/api/events.html#class-eventemitter). + * + * To access the `node:stream` module: + * + * ```js + * import stream from 'node:stream'; + * ``` + * + * The `node:stream` module is useful for creating new types of stream instances. + * It is usually not necessary to use the `node:stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/stream.js) + */ +declare module "stream" { + import { Abortable, EventEmitter } from "node:events"; + import { Blob as NodeBlob } from "node:buffer"; + import * as streamPromises from "node:stream/promises"; + import * as streamWeb from "node:stream/web"; + + type ComposeFnParam = (source: any) => void; + + class Stream extends EventEmitter { + pipe( + destination: T, + options?: { + end?: boolean | undefined; + }, + ): T; + compose( + stream: T | ComposeFnParam | Iterable | AsyncIterable, + options?: { signal: AbortSignal }, + ): T; + } + namespace Stream { + export { Stream, streamPromises as promises }; + } + namespace Stream { + interface StreamOptions extends Abortable { + emitClose?: boolean | undefined; + highWaterMark?: number | undefined; + objectMode?: boolean | undefined; + construct?: ((this: T, callback: (error?: Error | null) => void) => void) | undefined; + destroy?: ((this: T, error: Error | null, callback: (error?: Error | null) => void) => void) | undefined; + autoDestroy?: boolean | undefined; + } + interface ReadableOptions extends StreamOptions { + encoding?: BufferEncoding | undefined; + read?: ((this: T, size: number) => void) | undefined; + } + interface ArrayOptions { + /** + * The maximum concurrent invocations of `fn` to call on the stream at once. + * @default 1 + */ + concurrency?: number | undefined; + /** Allows destroying the stream if the signal is aborted. */ + signal?: AbortSignal | undefined; + } + /** + * @since v0.9.4 + */ + class Readable extends Stream implements NodeJS.ReadableStream { + /** + * A utility method for creating Readable Streams out of iterators. + * @since v12.3.0, v10.17.0 + * @param iterable Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed. + * @param options Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * A utility method for creating a `Readable` from a web `ReadableStream`. + * @since v17.0.0 + */ + static fromWeb( + readableStream: streamWeb.ReadableStream, + options?: Pick, + ): Readable; + /** + * A utility method for creating a web `ReadableStream` from a `Readable`. + * @since v17.0.0 + */ + static toWeb( + streamReadable: Readable, + options?: { + strategy?: streamWeb.QueuingStrategy | undefined; + }, + ): streamWeb.ReadableStream; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call {@link read}, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + * @since v11.4.0 + */ + readable: boolean; + /** + * Returns whether `'data'` has been emitted. + * @since v16.7.0, v14.18.0 + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding` property can be set using the {@link setEncoding} method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when [`'end'`](https://nodejs.org/docs/latest-v22.x/api/stream.html#event-end) event is emitted. + * @since v12.9.0 + */ + readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the [Three states](https://nodejs.org/docs/latest-v22.x/api/stream.html#three-states) section. + * @since v9.4.0 + */ + readonly readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + * @since v9.3.0 + */ + readonly readableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be read. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + * @since v12.3.0 + */ + readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + constructor(opts?: ReadableOptions); + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + /** + * The `readable.read()` method reads data out of the internal buffer and + * returns it. If no data is available to be read, `null` is returned. By default, + * the data is returned as a `Buffer` object unless an encoding has been + * specified using the `readable.setEncoding()` method or the stream is operating + * in object mode. + * + * The optional `size` argument specifies a specific number of bytes to read. If + * `size` bytes are not available to be read, `null` will be returned _unless_ the + * stream has ended, in which case all of the data remaining in the internal buffer + * will be returned. + * + * If the `size` argument is not specified, all of the data contained in the + * internal buffer will be returned. + * + * The `size` argument must be less than or equal to 1 GiB. + * + * The `readable.read()` method should only be called on `Readable` streams + * operating in paused mode. In flowing mode, `readable.read()` is called + * automatically until the internal buffer is fully drained. + * + * ```js + * const readable = getReadableStreamSomehow(); + * + * // 'readable' may be triggered multiple times as data is buffered in + * readable.on('readable', () => { + * let chunk; + * console.log('Stream is readable (new data received in buffer)'); + * // Use a loop to make sure we read all currently available data + * while (null !== (chunk = readable.read())) { + * console.log(`Read ${chunk.length} bytes of data...`); + * } + * }); + * + * // 'end' will be triggered once when there is no more data available + * readable.on('end', () => { + * console.log('Reached end of stream.'); + * }); + * ``` + * + * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks + * are not concatenated. A `while` loop is necessary to consume all data + * currently in the buffer. When reading a large file `.read()` may return `null`, + * having consumed all buffered content so far, but there is still more data to + * come not yet buffered. In this case a new `'readable'` event will be emitted + * when there is more data in the buffer. Finally the `'end'` event will be + * emitted when there is no more data to come. + * + * Therefore to read a file's whole contents from a `readable`, it is necessary + * to collect chunks across multiple `'readable'` events: + * + * ```js + * const chunks = []; + * + * readable.on('readable', () => { + * let chunk; + * while (null !== (chunk = readable.read())) { + * chunks.push(chunk); + * } + * }); + * + * readable.on('end', () => { + * const content = chunks.join(''); + * }); + * ``` + * + * A `Readable` stream in object mode will always return a single item from + * a call to `readable.read(size)`, regardless of the value of the `size` argument. + * + * If the `readable.read()` method returns a chunk of data, a `'data'` event will + * also be emitted. + * + * Calling {@link read} after the `'end'` event has + * been emitted will return `null`. No runtime error will be raised. + * @since v0.9.4 + * @param size Optional argument to specify how much data to read. + */ + read(size?: number): any; + /** + * The `readable.setEncoding()` method sets the character encoding for + * data read from the `Readable` stream. + * + * By default, no encoding is assigned and stream data will be returned as `Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer` objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling `readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * string format. + * + * The `Readable` stream will properly handle multi-byte characters delivered + * through the stream that would otherwise become improperly decoded if simply + * pulled from the stream as `Buffer` objects. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.setEncoding('utf8'); + * readable.on('data', (chunk) => { + * assert.equal(typeof chunk, 'string'); + * console.log('Got %d characters of string data:', chunk.length); + * }); + * ``` + * @since v0.9.4 + * @param encoding The encoding to use. + */ + setEncoding(encoding: BufferEncoding): this; + /** + * The `readable.pause()` method will cause a stream in flowing mode to stop + * emitting `'data'` events, switching out of flowing mode. Any data that + * becomes available will remain in the internal buffer. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.on('data', (chunk) => { + * console.log(`Received ${chunk.length} bytes of data.`); + * readable.pause(); + * console.log('There will be no additional data for 1 second.'); + * setTimeout(() => { + * console.log('Now data will start flowing again.'); + * readable.resume(); + * }, 1000); + * }); + * ``` + * + * The `readable.pause()` method has no effect if there is a `'readable'` event listener. + * @since v0.9.4 + */ + pause(): this; + /** + * The `readable.resume()` method causes an explicitly paused `Readable` stream to + * resume emitting `'data'` events, switching the stream into flowing mode. + * + * The `readable.resume()` method can be used to fully consume the data from a + * stream without actually processing any of that data: + * + * ```js + * getReadableStreamSomehow() + * .resume() + * .on('end', () => { + * console.log('Reached the end, but did not read anything.'); + * }); + * ``` + * + * The `readable.resume()` method has no effect if there is a `'readable'` event listener. + * @since v0.9.4 + */ + resume(): this; + /** + * The `readable.isPaused()` method returns the current operating state of the `Readable`. + * This is used primarily by the mechanism that underlies the `readable.pipe()` method. + * In most typical cases, there will be no reason to use this method directly. + * + * ```js + * const readable = new stream.Readable(); + * + * readable.isPaused(); // === false + * readable.pause(); + * readable.isPaused(); // === true + * readable.resume(); + * readable.isPaused(); // === false + * ``` + * @since v0.11.14 + */ + isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * import fs from 'node:fs'; + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @since v0.9.4 + * @param destination Optional specific stream to unpipe + */ + unpipe(destination?: NodeJS.WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * import { StringDecoder } from 'node:string_decoder'; + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.includes('\n\n')) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * return; + * } + * // Still reading the header. + * header += str; + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @since v0.9.11 + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must + * be a {string}, {Buffer}, {TypedArray}, {DataView} or `null`. For object mode streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ + unshift(chunk: any, encoding?: BufferEncoding): void; + /** + * Prior to Node.js 0.10, streams did not implement the entire `node:stream` module API as it is currently defined. (See `Compatibility` for more + * information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the `readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * import { OldReader } from './old-api-module.js'; + * import { Readable } from 'node:stream'; + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @since v0.9.4 + * @param stream An "old style" readable stream + */ + wrap(stream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + /** + * The iterator created by this method gives users the option to cancel the destruction + * of the stream if the `for await...of` loop is exited by `return`, `break`, or `throw`, + * or if the iterator should destroy the stream if the stream emitted an error during iteration. + * @since v16.3.0 + * @param options.destroyOnReturn When set to `false`, calling `return` on the async iterator, + * or exiting a `for await...of` iteration using a `break`, `return`, or `throw` will not destroy the stream. + * **Default: `true`**. + */ + iterator(options?: { destroyOnReturn?: boolean }): NodeJS.AsyncIterator; + /** + * This method allows mapping over the stream. The *fn* function will be called for every chunk in the stream. + * If the *fn* function returns a promise - that promise will be `await`ed before being passed to the result stream. + * @since v17.4.0, v16.14.0 + * @param fn a function to map over every chunk in the stream. Async or not. + * @returns a stream mapped with the function *fn*. + */ + map(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method allows filtering the stream. For each chunk in the stream the *fn* function will be called + * and if it returns a truthy value, the chunk will be passed to the result stream. + * If the *fn* function returns a promise - that promise will be `await`ed. + * @since v17.4.0, v16.14.0 + * @param fn a function to filter chunks from the stream. Async or not. + * @returns a stream filtered with the predicate *fn*. + */ + filter( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Readable; + /** + * This method allows iterating a stream. For each chunk in the stream the *fn* function will be called. + * If the *fn* function returns a promise - that promise will be `await`ed. + * + * This method is different from `for await...of` loops in that it can optionally process chunks concurrently. + * In addition, a `forEach` iteration can only be stopped by having passed a `signal` option + * and aborting the related AbortController while `for await...of` can be stopped with `break` or `return`. + * In either case the stream will be destroyed. + * + * This method is different from listening to the `'data'` event in that it uses the `readable` event + * in the underlying machinary and can limit the number of concurrent *fn* calls. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise for when the stream has finished. + */ + forEach( + fn: (data: any, options?: Pick) => void | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method allows easily obtaining the contents of a stream. + * + * As this method reads the entire stream into memory, it negates the benefits of streams. It's intended + * for interoperability and convenience, not as the primary way to consume streams. + * @since v17.5.0 + * @returns a promise containing an array with the contents of the stream. + */ + toArray(options?: Pick): Promise; + /** + * This method is similar to `Array.prototype.some` and calls *fn* on each chunk in the stream + * until the awaited return value is `true` (or any truthy value). Once an *fn* call on a chunk + * `await`ed return value is truthy, the stream is destroyed and the promise is fulfilled with `true`. + * If none of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `false`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for at least one of the chunks. + */ + some( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.find` and calls *fn* on each chunk in the stream + * to find a chunk with a truthy value for *fn*. Once an *fn* call's awaited return value is truthy, + * the stream is destroyed and the promise is fulfilled with value for which *fn* returned a truthy value. + * If all of the *fn* calls on the chunks return a falsy value, the promise is fulfilled with `undefined`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to the first chunk for which *fn* evaluated with a truthy value, + * or `undefined` if no element was found. + */ + find( + fn: (data: any, options?: Pick) => data is T, + options?: ArrayOptions, + ): Promise; + find( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.every` and calls *fn* on each chunk in the stream + * to check if all awaited return values are truthy value for *fn*. Once an *fn* call on a chunk + * `await`ed return value is falsy, the stream is destroyed and the promise is fulfilled with `false`. + * If all of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `true`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for every one of the chunks. + */ + every( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method returns a new stream by applying the given callback to each chunk of the stream + * and then flattening the result. + * + * It is possible to return a stream or another iterable or async iterable from *fn* and the result streams + * will be merged (flattened) into the returned stream. + * @since v17.5.0 + * @param fn a function to map over every chunk in the stream. May be async. May be a stream or generator. + * @returns a stream flat-mapped with the function *fn*. + */ + flatMap(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method returns a new stream with the first *limit* chunks dropped from the start. + * @since v17.5.0 + * @param limit the number of chunks to drop from the readable. + * @returns a stream with *limit* chunks dropped from the start. + */ + drop(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with the first *limit* chunks. + * @since v17.5.0 + * @param limit the number of chunks to take from the readable. + * @returns a stream with *limit* chunks taken. + */ + take(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with chunks of the underlying stream paired with a counter + * in the form `[index, chunk]`. The first index value is `0` and it increases by 1 for each chunk produced. + * @since v17.5.0 + * @returns a stream of indexed pairs. + */ + asIndexedPairs(options?: Pick): Readable; + /** + * This method calls *fn* on each chunk of the stream in order, passing it the result from the calculation + * on the previous element. It returns a promise for the final value of the reduction. + * + * If no *initial* value is supplied the first chunk of the stream is used as the initial value. + * If the stream is empty, the promise is rejected with a `TypeError` with the `ERR_INVALID_ARGS` code property. + * + * The reducer function iterates the stream element-by-element which means that there is no *concurrency* parameter + * or parallelism. To perform a reduce concurrently, you can extract the async function to `readable.map` method. + * @since v17.5.0 + * @param fn a reducer function to call over every chunk in the stream. Async or not. + * @param initial the initial value to use in the reduction. + * @returns a promise for the final value of the reduction. + */ + reduce( + fn: (previous: any, data: any, options?: Pick) => T, + initial?: undefined, + options?: Pick, + ): Promise; + reduce( + fn: (previous: T, data: any, options?: Pick) => T, + initial: T, + options?: Pick, + ): Promise; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()` will be ignored. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, but instead implement `readable._destroy()`. + * @since v8.0.0 + * @param error Error which will be passed as payload in `'error'` event + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. error + * 5. pause + * 6. readable + * 7. resume + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "pause"): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + /** + * Calls `readable.destroy()` with an `AbortError` and returns a promise that fulfills when the stream is finished. + * @since v20.4.0 + */ + [Symbol.asyncDispose](): Promise; + } + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean | undefined; + defaultEncoding?: BufferEncoding | undefined; + write?: + | (( + this: T, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ) => void) + | undefined; + writev?: + | (( + this: T, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ) => void) + | undefined; + final?: ((this: T, callback: (error?: Error | null) => void) => void) | undefined; + } + /** + * @since v0.9.4 + */ + class Writable extends Stream implements NodeJS.WritableStream { + /** + * A utility method for creating a `Writable` from a web `WritableStream`. + * @since v17.0.0 + */ + static fromWeb( + writableStream: streamWeb.WritableStream, + options?: Pick, + ): Writable; + /** + * A utility method for creating a web `WritableStream` from a `Writable`. + * @since v17.0.0 + */ + static toWeb(streamWritable: Writable): streamWeb.WritableStream; + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored, or ended. + * @since v11.4.0 + */ + readonly writable: boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'finish'`. + * @since v18.0.0, v16.17.0 + */ + readonly writableAborted: boolean; + /** + * Is `true` after `writable.end()` has been called. This property + * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. + * @since v12.9.0 + */ + readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + * @since v12.6.0 + */ + readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + * @since v9.3.0 + */ + readonly writableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be written. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + * @since v12.3.0 + */ + readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + * @since v13.2.0, v12.16.0 + */ + readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + /** + * Is `true` if the stream's buffer has been full and stream will emit `'drain'`. + * @since v15.2.0, v14.17.0 + */ + readonly writableNeedDrain: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + _construct?(callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + /** + * The `writable.write()` method writes some data to the stream, and calls the + * supplied `callback` once the data has been fully handled. If an error + * occurs, the `callback` will be called with the error as its + * first argument. The `callback` is called asynchronously and before `'error'` is + * emitted. + * + * The return value is `true` if the internal buffer is less than the `highWaterMark` configured when the stream was created after admitting `chunk`. + * If `false` is returned, further attempts to write data to the stream should + * stop until the `'drain'` event is emitted. + * + * While a stream is not draining, calls to `write()` will buffer `chunk`, and + * return false. Once all currently buffered chunks are drained (accepted for + * delivery by the operating system), the `'drain'` event will be emitted. + * Once `write()` returns false, do not write more chunks + * until the `'drain'` event is emitted. While calling `write()` on a stream that + * is not draining is allowed, Node.js will buffer all written chunks until + * maximum memory usage occurs, at which point it will abort unconditionally. + * Even before it aborts, high memory usage will cause poor garbage collector + * performance and high RSS (which is not typically released back to the system, + * even after the memory is no longer required). Since TCP sockets may never + * drain if the remote peer does not read the data, writing a socket that is + * not draining may lead to a remotely exploitable vulnerability. + * + * Writing data while the stream is not draining is particularly + * problematic for a `Transform`, because the `Transform` streams are paused + * by default until they are piped or a `'data'` or `'readable'` event handler + * is added. + * + * If the data to be written can be generated or fetched on demand, it is + * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is + * possible to respect backpressure and avoid memory issues using the `'drain'` event: + * + * ```js + * function write(data, cb) { + * if (!stream.write(data)) { + * stream.once('drain', cb); + * } else { + * process.nextTick(cb); + * } + * } + * + * // Wait for cb to be called before doing any other write. + * write('hello', () => { + * console.log('Write completed, do more writes now.'); + * }); + * ``` + * + * A `Writable` stream in object mode will always ignore the `encoding` argument. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; + /** + * Writes data to the stream, with an explicit encoding for string data. + * @see {@link Writable.write} for full details. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param encoding The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @since v0.11.15 + * @param encoding The new default encoding + */ + setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * import fs from 'node:fs'; + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @since v0.9.4 + * @param cb Callback for when the stream is finished. + */ + end(cb?: () => void): this; + /** + * Signals that no more data will be written, with one final chunk of data. + * @see {@link Writable.end} for full details. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param cb Callback for when the stream is finished. + */ + end(chunk: any, cb?: () => void): this; + /** + * Signals that no more data will be written, with one final chunk of data. + * @see {@link Writable.end} for full details. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param cb Callback for when the stream is finished. + */ + end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()` buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing `writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + * @since v0.11.2 + */ + cork(): void; + /** + * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. + * + * When using `writable.cork()` and `writable.uncork()` to manage the buffering + * of writes to a stream, defer calls to `writable.uncork()` using `process.nextTick()`. Doing so allows batching of all `writable.write()` calls that occur within a given Node.js event + * loop phase. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.write('data '); + * process.nextTick(() => stream.uncork()); + * ``` + * + * If the `writable.cork()` method is called multiple times on a stream, the + * same number of calls to `writable.uncork()` must be called to flush the buffered + * data. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.cork(); + * stream.write('data '); + * process.nextTick(() => { + * stream.uncork(); + * // The data will not be flushed until uncork() is called a second time. + * stream.uncork(); + * }); + * ``` + * + * See also: `writable.cork()`. + * @since v0.11.2 + */ + uncork(): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the writable + * stream has ended and subsequent calls to `write()` or `end()` will result in + * an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to `write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * Use `end()` instead of destroy if data should flush before close, or wait for + * the `'drain'` event before destroying the stream. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, + * but instead implement `writable._destroy()`. + * @since v8.0.0 + * @param error Optional, an error to emit with `'error'` event. + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean | undefined; + readableObjectMode?: boolean | undefined; + writableObjectMode?: boolean | undefined; + readableHighWaterMark?: number | undefined; + writableHighWaterMark?: number | undefined; + writableCorked?: number | undefined; + } + /** + * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Duplex` streams include: + * + * * `TCP sockets` + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Duplex extends Stream implements NodeJS.ReadWriteStream { + /** + * If `false` then the stream will automatically end the writable side when the + * readable side ends. Set initially by the `allowHalfOpen` constructor option, + * which defaults to `true`. + * + * This can be changed manually to change the half-open behavior of an existing + * `Duplex` stream instance, but must be changed before the `'end'` event is emitted. + * @since v0.9.4 + */ + allowHalfOpen: boolean; + constructor(opts?: DuplexOptions); + /** + * A utility method for creating duplex streams. + * + * - `Stream` converts writable stream into writable `Duplex` and readable stream + * to `Duplex`. + * - `Blob` converts into readable `Duplex`. + * - `string` converts into readable `Duplex`. + * - `ArrayBuffer` converts into readable `Duplex`. + * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. + * - `AsyncGeneratorFunction` converts into a readable/writable transform + * `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + * `null`. + * - `AsyncFunction` converts into a writable `Duplex`. Must return + * either `null` or `undefined` + * - `Object ({ writable, readable })` converts `readable` and + * `writable` into `Stream` and then combines them into `Duplex` where the + * `Duplex` will write to the `writable` and read from the `readable`. + * - `Promise` converts into readable `Duplex`. Value `null` is ignored. + * + * @since v16.8.0 + */ + static from( + src: + | Stream + | NodeBlob + | ArrayBuffer + | string + | Iterable + | AsyncIterable + | AsyncGeneratorFunction + | Promise + | Object, + ): Duplex; + /** + * A utility method for creating a web `ReadableStream` and `WritableStream` from a `Duplex`. + * @since v17.0.0 + */ + static toWeb(streamDuplex: Duplex): { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }; + /** + * A utility method for creating a `Duplex` from a web `ReadableStream` and `WritableStream`. + * @since v17.0.0 + */ + static fromWeb( + duplexStream: { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }, + options?: Pick< + DuplexOptions, + "allowHalfOpen" | "decodeStrings" | "encoding" | "highWaterMark" | "objectMode" | "signal" + >, + ): Duplex; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. drain + * 4. end + * 5. error + * 6. finish + * 7. pause + * 8. pipe + * 9. readable + * 10. resume + * 11. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pause"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pause", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pause", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + interface Duplex extends Readable, Writable {} + /** + * The utility function `duplexPair` returns an Array with two items, + * each being a `Duplex` stream connected to the other side: + * + * ```js + * const [ sideA, sideB ] = duplexPair(); + * ``` + * + * Whatever is written to one stream is made readable on the other. It provides + * behavior analogous to a network connection, where the data written by the client + * becomes readable by the server, and vice-versa. + * + * The Duplex streams are symmetrical; one or the other may be used without any + * difference in behavior. + * @param options A value to pass to both {@link Duplex} constructors, + * to set options such as buffering. + * @since v22.6.0 + */ + function duplexPair(options?: DuplexOptions): [Duplex, Duplex]; + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + transform?: + | ((this: T, chunk: any, encoding: BufferEncoding, callback: TransformCallback) => void) + | undefined; + flush?: ((this: T, callback: TransformCallback) => void) | undefined; + } + /** + * Transform streams are `Duplex` streams where the output is in some way + * related to the input. Like all `Duplex` streams, `Transform` streams + * implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Transform` streams include: + * + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + /** + * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is + * primarily for examples and testing, but there are some use cases where `stream.PassThrough` is useful as a building block for novel sorts of streams. + */ + class PassThrough extends Transform {} + /** + * A stream to attach a signal to. + * + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed `AbortSignal` will behave the same way as calling `.destroy(new AbortError())` on the + * stream, and `controller.error(new AbortError())` for webstreams. + * + * ```js + * import fs from 'node:fs'; + * + * const controller = new AbortController(); + * const read = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * // Later, abort the operation closing the stream + * controller.abort(); + * ``` + * + * Or using an `AbortSignal` with a readable stream as an async iterable: + * + * ```js + * const controller = new AbortController(); + * setTimeout(() => controller.abort(), 10_000); // set a timeout + * const stream = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * (async () => { + * try { + * for await (const chunk of stream) { + * await process(chunk); + * } + * } catch (e) { + * if (e.name === 'AbortError') { + * // The operation was cancelled + * } else { + * throw e; + * } + * } + * })(); + * ``` + * + * Or using an `AbortSignal` with a ReadableStream: + * + * ```js + * const controller = new AbortController(); + * const rs = new ReadableStream({ + * start(controller) { + * controller.enqueue('hello'); + * controller.enqueue('world'); + * controller.close(); + * }, + * }); + * + * addAbortSignal(controller.signal, rs); + * + * finished(rs, (err) => { + * if (err) { + * if (err.name === 'AbortError') { + * // The operation was cancelled + * } + * } + * }); + * + * const reader = rs.getReader(); + * + * reader.read().then(({ value, done }) => { + * console.log(value); // hello + * console.log(done); // false + * controller.abort(); + * }); + * ``` + * @since v15.4.0 + * @param signal A signal representing possible cancellation + * @param stream A stream to attach a signal to. + */ + function addAbortSignal(signal: AbortSignal, stream: T): T; + /** + * Returns the default highWaterMark used by streams. + * Defaults to `65536` (64 KiB), or `16` for `objectMode`. + * @since v19.9.0 + */ + function getDefaultHighWaterMark(objectMode: boolean): number; + /** + * Sets the default highWaterMark used by streams. + * @since v19.9.0 + * @param value highWaterMark value + */ + function setDefaultHighWaterMark(objectMode: boolean, value: number): void; + interface FinishedOptions extends Abortable { + error?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + /** + * A readable and/or writable stream/webstream. + * + * A function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * import { finished } from 'node:stream'; + * import fs from 'node:fs'; + * + * const rs = fs.createReadStream('archive.tar'); + * + * finished(rs, (err) => { + * if (err) { + * console.error('Stream failed.', err); + * } else { + * console.log('Stream is done reading.'); + * } + * }); + * + * rs.resume(); // Drain the stream. + * ``` + * + * Especially useful in error handling scenarios where a stream is destroyed + * prematurely (like an aborted HTTP request), and will not emit `'end'` or `'finish'`. + * + * The `finished` API provides [`promise version`](https://nodejs.org/docs/latest-v22.x/api/stream.html#streamfinishedstream-options). + * + * `stream.finished()` leaves dangling event listeners (in particular `'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * invoked. The reason for this is so that unexpected `'error'` events (due to + * incorrect stream implementations) do not cause unexpected crashes. + * If this is unwanted behavior then the returned cleanup function needs to be + * invoked in the callback: + * + * ```js + * const cleanup = finished(rs, (err) => { + * cleanup(); + * // ... + * }); + * ``` + * @since v10.0.0 + * @param stream A readable and/or writable stream. + * @param callback A callback function that takes an optional error argument. + * @returns A cleanup function which removes all registered listeners. + */ + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options: FinishedOptions, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + namespace finished { + function __promisify__( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + } + type PipelineSourceFunction = () => Iterable | AsyncIterable; + type PipelineSource = Iterable | AsyncIterable | NodeJS.ReadableStream | PipelineSourceFunction; + type PipelineTransform, U> = + | NodeJS.ReadWriteStream + | (( + source: S extends (...args: any[]) => Iterable | AsyncIterable ? AsyncIterable + : S, + ) => AsyncIterable); + type PipelineTransformSource = PipelineSource | PipelineTransform; + type PipelineDestinationIterableFunction = (source: AsyncIterable) => AsyncIterable; + type PipelineDestinationPromiseFunction = (source: AsyncIterable) => Promise

; + type PipelineDestination, P> = S extends + PipelineTransformSource ? + | NodeJS.WritableStream + | PipelineDestinationIterableFunction + | PipelineDestinationPromiseFunction + : never; + type PipelineCallback> = S extends + PipelineDestinationPromiseFunction ? (err: NodeJS.ErrnoException | null, value: P) => void + : (err: NodeJS.ErrnoException | null) => void; + type PipelinePromise> = S extends + PipelineDestinationPromiseFunction ? Promise

: Promise; + interface PipelineOptions { + signal?: AbortSignal | undefined; + end?: boolean | undefined; + } + /** + * A module method to pipe between streams and generators forwarding errors and + * properly cleaning up and provide a callback when the pipeline is complete. + * + * ```js + * import { pipeline } from 'node:stream'; + * import fs from 'node:fs'; + * import zlib from 'node:zlib'; + * + * // Use the pipeline API to easily pipe a series of streams + * // together and get notified when the pipeline is fully done. + * + * // A pipeline to gzip a potentially huge tar file efficiently: + * + * pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * (err) => { + * if (err) { + * console.error('Pipeline failed.', err); + * } else { + * console.log('Pipeline succeeded.'); + * } + * }, + * ); + * ``` + * + * The `pipeline` API provides a [`promise version`](https://nodejs.org/docs/latest-v22.x/api/stream.html#streampipelinesource-transforms-destination-options). + * + * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * + * * `Readable` streams which have emitted `'end'` or `'close'`. + * * `Writable` streams which have emitted `'finish'` or `'close'`. + * + * `stream.pipeline()` leaves dangling event listeners on the streams + * after the `callback` has been invoked. In the case of reuse of streams after + * failure, this can cause event listener leaks and swallowed errors. If the last + * stream is readable, dangling event listeners will be removed so that the last + * stream can be consumed later. + * + * `stream.pipeline()` closes all the streams when an error is raised. + * The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior + * once it would destroy the socket without sending the expected response. + * See the example below: + * + * ```js + * import fs from 'node:fs'; + * import http from 'node:http'; + * import { pipeline } from 'node:stream'; + * + * const server = http.createServer((req, res) => { + * const fileStream = fs.createReadStream('./fileNotExist.txt'); + * pipeline(fileStream, res, (err) => { + * if (err) { + * console.log(err); // No such file + * // this message can't be sent once `pipeline` already destroyed the socket + * return res.end('error!!!'); + * } + * }); + * }); + * ``` + * @since v10.0.0 + * @param callback Called when the pipeline is fully done. + */ + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline( + streams: ReadonlyArray, + callback: (err: NodeJS.ErrnoException | null) => void, + ): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array< + NodeJS.ReadWriteStream | NodeJS.WritableStream | ((err: NodeJS.ErrnoException | null) => void) + > + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; + } + // TODO: this interface never existed; remove in next major + interface Pipe { + close(): void; + hasRef(): boolean; + ref(): void; + unref(): void; + } + /** + * Returns whether the stream has encountered an error. + * @since v17.3.0, v16.14.0 + */ + function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; + /** + * Returns whether the stream is readable. + * @since v17.4.0, v16.14.0 + */ + function isReadable(stream: Readable | NodeJS.ReadableStream): boolean; + } + export = Stream; +} +declare module "node:stream" { + import stream = require("stream"); + export = stream; +} diff --git a/node_modules/@types/node/stream/consumers.d.ts b/node_modules/@types/node/stream/consumers.d.ts new file mode 100644 index 0000000..05db025 --- /dev/null +++ b/node_modules/@types/node/stream/consumers.d.ts @@ -0,0 +1,38 @@ +/** + * The utility consumer functions provide common options for consuming + * streams. + * @since v16.7.0 + */ +declare module "stream/consumers" { + import { Blob as NodeBlob, NonSharedBuffer } from "node:buffer"; + import { ReadableStream as WebReadableStream } from "node:stream/web"; + /** + * @since v16.7.0 + * @returns Fulfills with an `ArrayBuffer` containing the full contents of the stream. + */ + function arrayBuffer(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with a `Blob` containing the full contents of the stream. + */ + function blob(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with a `Buffer` containing the full contents of the stream. + */ + function buffer(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with the contents of the stream parsed as a + * UTF-8 encoded string that is then passed through `JSON.parse()`. + */ + function json(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with the contents of the stream parsed as a UTF-8 encoded string. + */ + function text(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; +} +declare module "node:stream/consumers" { + export * from "stream/consumers"; +} diff --git a/node_modules/@types/node/stream/promises.d.ts b/node_modules/@types/node/stream/promises.d.ts new file mode 100644 index 0000000..d54c14c --- /dev/null +++ b/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,90 @@ +declare module "stream/promises" { + import { + FinishedOptions as _FinishedOptions, + PipelineDestination, + PipelineOptions, + PipelinePromise, + PipelineSource, + PipelineTransform, + } from "node:stream"; + interface FinishedOptions extends _FinishedOptions { + /** + * If true, removes the listeners registered by this function before the promise is fulfilled. + * @default false + */ + cleanup?: boolean | undefined; + } + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; +} +declare module "node:stream/promises" { + export * from "stream/promises"; +} diff --git a/node_modules/@types/node/stream/web.d.ts b/node_modules/@types/node/stream/web.d.ts new file mode 100644 index 0000000..c7432f8 --- /dev/null +++ b/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,622 @@ +type _ByteLengthQueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ByteLengthQueuingStrategy; +type _CompressionStream = typeof globalThis extends { onmessage: any; ReportingObserver: any } ? {} + : import("stream/web").CompressionStream; +type _CountQueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").CountQueuingStrategy; +type _DecompressionStream = typeof globalThis extends { onmessage: any; ReportingObserver: any } ? {} + : import("stream/web").DecompressionStream; +type _QueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").QueuingStrategy; +type _ReadableByteStreamController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableByteStreamController; +type _ReadableStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStream; +type _ReadableStreamBYOBReader = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamBYOBReader; +type _ReadableStreamBYOBRequest = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamBYOBRequest; +type _ReadableStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamDefaultController; +type _ReadableStreamDefaultReader = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamDefaultReader; +type _TextDecoderStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TextDecoderStream; +type _TextEncoderStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TextEncoderStream; +type _TransformStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TransformStream; +type _TransformStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TransformStreamDefaultController; +type _WritableStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStream; +type _WritableStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStreamDefaultController; +type _WritableStreamDefaultWriter = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStreamDefaultWriter; + +declare module "stream/web" { + // stub module, pending copy&paste from .d.ts or manual impl + // copy from lib.dom.d.ts + interface ReadableWritablePair { + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream + * through a transform stream (or any other { writable, readable } + * pair). It simply pipes the stream into the writable side of the + * supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + */ + writable: WritableStream; + } + interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. + * The way in which the piping process behaves under various error + * conditions can be customized with a number of passed options. It + * returns a promise that fulfills when the piping process completes + * successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate + * as follows: + * + * An error in this source readable stream will abort destination, + * unless preventAbort is truthy. The returned promise will be rejected + * with the source's error, or with any error that occurs during + * aborting the destination. + * + * An error in destination will cancel this source readable stream, + * unless preventCancel is truthy. The returned promise will be rejected + * with the destination's error, or with any error that occurs during + * canceling the source. + * + * When this source readable stream closes, destination will be closed, + * unless preventClose is truthy. The returned promise will be fulfilled + * once this process completes, unless an error is encountered while + * closing the destination, in which case it will be rejected with that + * error. + * + * If destination starts out closed or closing, this source readable + * stream will be canceled, unless preventCancel is true. The returned + * promise will be rejected with an error indicating piping to a closed + * stream failed, or with any error that occurs during canceling the + * source. + * + * The signal option can be set to an AbortSignal to allow aborting an + * ongoing pipe operation via the corresponding AbortController. In this + * case, this source readable stream will be canceled, and destination + * aborted, unless the respective options preventCancel or preventAbort + * are set. + */ + preventClose?: boolean; + signal?: AbortSignal; + } + interface ReadableStreamGenericReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + } + type ReadableStreamController = ReadableStreamDefaultController; + interface ReadableStreamReadValueResult { + done: false; + value: T; + } + interface ReadableStreamReadDoneResult { + done: true; + value: T | undefined; + } + type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; + interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; + } + interface UnderlyingSinkAbortCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSinkCloseCallback { + (): void | PromiseLike; + } + interface UnderlyingSinkStartCallback { + (controller: WritableStreamDefaultController): any; + } + interface UnderlyingSinkWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; + } + interface UnderlyingSourceCancelCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSourcePullCallback { + (controller: ReadableStreamController): void | PromiseLike; + } + interface UnderlyingSourceStartCallback { + (controller: ReadableStreamController): any; + } + interface TransformerFlushCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerStartCallback { + (controller: TransformStreamDefaultController): any; + } + interface TransformerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerCancelCallback { + (reason: any): void | PromiseLike; + } + interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: "bytes"; + } + interface UnderlyingSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback; + start?: UnderlyingSourceStartCallback; + type?: undefined; + } + interface UnderlyingSink { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined; + write?: UnderlyingSinkWriteCallback; + } + interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; + } + interface ReadableStreamAsyncIterator extends NodeJS.AsyncIterator { + [Symbol.asyncIterator](): ReadableStreamAsyncIterator; + } + /** This Streams API interface represents a readable stream of byte data. */ + interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; + getReader(): ReadableStreamDefaultReader; + getReader(options?: ReadableStreamGetReaderOptions): ReadableStreamReader; + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; + values(options?: { preventCancel?: boolean }): ReadableStreamAsyncIterator; + [Symbol.asyncIterator](): ReadableStreamAsyncIterator; + } + const ReadableStream: { + prototype: ReadableStream; + from(iterable: Iterable | AsyncIterable): ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + }; + type ReadableStreamReaderMode = "byob"; + interface ReadableStreamGetReaderOptions { + /** + * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode?: ReadableStreamReaderMode; + } + type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ + interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + options?: { + min?: number; + }, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + } + const ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new(stream: ReadableStream): ReadableStreamDefaultReader; + }; + const ReadableStreamBYOBReader: { + prototype: ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; + }; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ + interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + readonly view: ArrayBufferView | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBufferView): void; + } + const ReadableStreamBYOBRequest: { + prototype: ReadableStreamBYOBRequest; + new(): ReadableStreamBYOBRequest; + }; + interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; + } + const ReadableByteStreamController: { + prototype: ReadableByteStreamController; + new(): ReadableByteStreamController; + }; + interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: R): void; + error(e?: any): void; + } + const ReadableStreamDefaultController: { + prototype: ReadableStreamDefaultController; + new(): ReadableStreamDefaultController; + }; + interface Transformer { + flush?: TransformerFlushCallback; + readableType?: undefined; + start?: TransformerStartCallback; + transform?: TransformerTransformCallback; + cancel?: TransformerCancelCallback; + writableType?: undefined; + } + interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const TransformStream: { + prototype: TransformStream; + new( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ): TransformStream; + }; + interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk: O): void; + error(reason?: any): void; + terminate(): void; + } + const TransformStreamDefaultController: { + prototype: TransformStreamDefaultController; + new(): TransformStreamDefaultController; + }; + /** + * This Streams API interface provides a standard abstraction for writing + * streaming data to a destination, known as a sink. This object comes with + * built-in back pressure and queuing. + */ + interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + close(): Promise; + getWriter(): WritableStreamDefaultWriter; + } + const WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; + }; + /** + * This Streams API interface is the object returned by + * WritableStream.getWriter() and once created locks the < writer to the + * WritableStream ensuring that no other streams can write to the underlying + * sink. + */ + interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk: W): Promise; + } + const WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(stream: WritableStream): WritableStreamDefaultWriter; + }; + /** + * This Streams API interface represents a controller allowing control of a + * WritableStream's state. When constructing a WritableStream, the + * underlying sink is given a corresponding WritableStreamDefaultController + * instance to manipulate. + */ + interface WritableStreamDefaultController { + error(e?: any): void; + } + const WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; + }; + interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySize; + } + interface QueuingStrategySize { + (chunk: T): number; + } + interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water + * mark. + * + * Note that the provided high water mark will not be validated ahead of + * time. Instead, if it is negative, NaN, or not a number, the resulting + * ByteLengthQueuingStrategy will cause the corresponding stream + * constructor to throw. + */ + highWaterMark: number; + } + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface ByteLengthQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(init: QueuingStrategyInit): ByteLengthQueuingStrategy; + }; + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface CountQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(init: QueuingStrategyInit): CountQueuingStrategy; + }; + interface TextEncoderStream { + /** Returns "utf-8". */ + readonly encoding: "utf-8"; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextEncoderStream: { + prototype: TextEncoderStream; + new(): TextEncoderStream; + }; + interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + type BufferSource = ArrayBufferView | ArrayBuffer; + interface TextDecoderStream { + /** Returns encoding's name, lower cased. */ + readonly encoding: string; + /** Returns `true` if error mode is "fatal", and `false` otherwise. */ + readonly fatal: boolean; + /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */ + readonly ignoreBOM: boolean; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextDecoderStream: { + prototype: TextDecoderStream; + new(encoding?: string, options?: TextDecoderOptions): TextDecoderStream; + }; + interface CompressionStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const CompressionStream: { + prototype: CompressionStream; + new(format: "deflate" | "deflate-raw" | "gzip"): CompressionStream; + }; + interface DecompressionStream { + readonly writable: WritableStream; + readonly readable: ReadableStream; + } + const DecompressionStream: { + prototype: DecompressionStream; + new(format: "deflate" | "deflate-raw" | "gzip"): DecompressionStream; + }; + + global { + interface ByteLengthQueuingStrategy extends _ByteLengthQueuingStrategy {} + /** + * `ByteLengthQueuingStrategy` class is a global reference for `import { ByteLengthQueuingStrategy } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-bytelengthqueuingstrategy + * @since v18.0.0 + */ + var ByteLengthQueuingStrategy: typeof globalThis extends { onmessage: any; ByteLengthQueuingStrategy: infer T } + ? T + : typeof import("stream/web").ByteLengthQueuingStrategy; + + interface CompressionStream extends _CompressionStream {} + /** + * `CompressionStream` class is a global reference for `import { CompressionStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-compressionstream + * @since v18.0.0 + */ + var CompressionStream: typeof globalThis extends { + onmessage: any; + // CompressionStream, DecompressionStream and ReportingObserver was introduced in the same commit. + // If ReportingObserver check is removed, the type here will form a circular reference in TS5.0+lib.dom.d.ts + ReportingObserver: any; + CompressionStream: infer T; + } ? T + // TS 4.8, 4.9, 5.0 + : typeof globalThis extends { onmessage: any; TransformStream: { prototype: infer T } } ? { + prototype: T; + new(format: "deflate" | "deflate-raw" | "gzip"): T; + } + : typeof import("stream/web").CompressionStream; + + interface CountQueuingStrategy extends _CountQueuingStrategy {} + /** + * `CountQueuingStrategy` class is a global reference for `import { CountQueuingStrategy } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-countqueuingstrategy + * @since v18.0.0 + */ + var CountQueuingStrategy: typeof globalThis extends { onmessage: any; CountQueuingStrategy: infer T } ? T + : typeof import("stream/web").CountQueuingStrategy; + + interface DecompressionStream extends _DecompressionStream {} + /** + * `DecompressionStream` class is a global reference for `import { DecompressionStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-decompressionstream + * @since v18.0.0 + */ + var DecompressionStream: typeof globalThis extends { + onmessage: any; + // CompressionStream, DecompressionStream and ReportingObserver was introduced in the same commit. + // If ReportingObserver check is removed, the type here will form a circular reference in TS5.0+lib.dom.d.ts + ReportingObserver: any; + DecompressionStream: infer T extends object; + } ? T + // TS 4.8, 4.9, 5.0 + : typeof globalThis extends { onmessage: any; TransformStream: { prototype: infer T } } ? { + prototype: T; + new(format: "deflate" | "deflate-raw" | "gzip"): T; + } + : typeof import("stream/web").DecompressionStream; + + interface QueuingStrategy extends _QueuingStrategy {} + + interface ReadableByteStreamController extends _ReadableByteStreamController {} + /** + * `ReadableByteStreamController` class is a global reference for `import { ReadableByteStreamController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablebytestreamcontroller + * @since v18.0.0 + */ + var ReadableByteStreamController: typeof globalThis extends + { onmessage: any; ReadableByteStreamController: infer T } ? T + : typeof import("stream/web").ReadableByteStreamController; + + interface ReadableStream extends _ReadableStream {} + /** + * `ReadableStream` class is a global reference for `import { ReadableStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestream + * @since v18.0.0 + */ + var ReadableStream: typeof globalThis extends { onmessage: any; ReadableStream: infer T } ? T + : typeof import("stream/web").ReadableStream; + + interface ReadableStreamBYOBReader extends _ReadableStreamBYOBReader {} + /** + * `ReadableStreamBYOBReader` class is a global reference for `import { ReadableStreamBYOBReader } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreambyobreader + * @since v18.0.0 + */ + var ReadableStreamBYOBReader: typeof globalThis extends { onmessage: any; ReadableStreamBYOBReader: infer T } + ? T + : typeof import("stream/web").ReadableStreamBYOBReader; + + interface ReadableStreamBYOBRequest extends _ReadableStreamBYOBRequest {} + /** + * `ReadableStreamBYOBRequest` class is a global reference for `import { ReadableStreamBYOBRequest } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreambyobrequest + * @since v18.0.0 + */ + var ReadableStreamBYOBRequest: typeof globalThis extends { onmessage: any; ReadableStreamBYOBRequest: infer T } + ? T + : typeof import("stream/web").ReadableStreamBYOBRequest; + + interface ReadableStreamDefaultController extends _ReadableStreamDefaultController {} + /** + * `ReadableStreamDefaultController` class is a global reference for `import { ReadableStreamDefaultController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreamdefaultcontroller + * @since v18.0.0 + */ + var ReadableStreamDefaultController: typeof globalThis extends + { onmessage: any; ReadableStreamDefaultController: infer T } ? T + : typeof import("stream/web").ReadableStreamDefaultController; + + interface ReadableStreamDefaultReader extends _ReadableStreamDefaultReader {} + /** + * `ReadableStreamDefaultReader` class is a global reference for `import { ReadableStreamDefaultReader } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreamdefaultreader + * @since v18.0.0 + */ + var ReadableStreamDefaultReader: typeof globalThis extends + { onmessage: any; ReadableStreamDefaultReader: infer T } ? T + : typeof import("stream/web").ReadableStreamDefaultReader; + + interface TextDecoderStream extends _TextDecoderStream {} + /** + * `TextDecoderStream` class is a global reference for `import { TextDecoderStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-textdecoderstream + * @since v18.0.0 + */ + var TextDecoderStream: typeof globalThis extends { onmessage: any; TextDecoderStream: infer T } ? T + : typeof import("stream/web").TextDecoderStream; + + interface TextEncoderStream extends _TextEncoderStream {} + /** + * `TextEncoderStream` class is a global reference for `import { TextEncoderStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-textencoderstream + * @since v18.0.0 + */ + var TextEncoderStream: typeof globalThis extends { onmessage: any; TextEncoderStream: infer T } ? T + : typeof import("stream/web").TextEncoderStream; + + interface TransformStream extends _TransformStream {} + /** + * `TransformStream` class is a global reference for `import { TransformStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-transformstream + * @since v18.0.0 + */ + var TransformStream: typeof globalThis extends { onmessage: any; TransformStream: infer T } ? T + : typeof import("stream/web").TransformStream; + + interface TransformStreamDefaultController extends _TransformStreamDefaultController {} + /** + * `TransformStreamDefaultController` class is a global reference for `import { TransformStreamDefaultController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-transformstreamdefaultcontroller + * @since v18.0.0 + */ + var TransformStreamDefaultController: typeof globalThis extends + { onmessage: any; TransformStreamDefaultController: infer T } ? T + : typeof import("stream/web").TransformStreamDefaultController; + + interface WritableStream extends _WritableStream {} + /** + * `WritableStream` class is a global reference for `import { WritableStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-writablestream + * @since v18.0.0 + */ + var WritableStream: typeof globalThis extends { onmessage: any; WritableStream: infer T } ? T + : typeof import("stream/web").WritableStream; + + interface WritableStreamDefaultController extends _WritableStreamDefaultController {} + /** + * `WritableStreamDefaultController` class is a global reference for `import { WritableStreamDefaultController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-writablestreamdefaultcontroller + * @since v18.0.0 + */ + var WritableStreamDefaultController: typeof globalThis extends + { onmessage: any; WritableStreamDefaultController: infer T } ? T + : typeof import("stream/web").WritableStreamDefaultController; + + interface WritableStreamDefaultWriter extends _WritableStreamDefaultWriter {} + /** + * `WritableStreamDefaultWriter` class is a global reference for `import { WritableStreamDefaultWriter } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-writablestreamdefaultwriter + * @since v18.0.0 + */ + var WritableStreamDefaultWriter: typeof globalThis extends + { onmessage: any; WritableStreamDefaultWriter: infer T } ? T + : typeof import("stream/web").WritableStreamDefaultWriter; + } +} +declare module "node:stream/web" { + export * from "stream/web"; +} diff --git a/node_modules/@types/node/string_decoder.d.ts b/node_modules/@types/node/string_decoder.d.ts new file mode 100644 index 0000000..d8b9be8 --- /dev/null +++ b/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `node:string_decoder` module provides an API for decoding `Buffer` objects + * into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 + * characters. It can be accessed using: + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); // Prints: ¢ + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); // Prints: € + * ``` + * + * When a `Buffer` instance is written to the `StringDecoder` instance, an + * internal buffer is used to ensure that the decoded string does not contain + * any incomplete multibyte characters. These are held in the buffer until the + * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. + * + * In the following example, the three UTF-8 encoded bytes of the European Euro + * symbol (`€`) are written over three separate operations: + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); // Prints: € + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/string_decoder.js) + */ +declare module "string_decoder" { + class StringDecoder { + constructor(encoding?: BufferEncoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at + * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the + * returned string and stored in an internal buffer for the next call to `stringDecoder.write()` or `stringDecoder.end()`. + * @since v0.1.99 + * @param buffer The bytes to decode. + */ + write(buffer: string | NodeJS.ArrayBufferView): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes + * representing incomplete UTF-8 and UTF-16 characters will be replaced with + * substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()` is performed before returning the remaining input. + * After `end()` is called, the `stringDecoder` object can be reused for new input. + * @since v0.9.3 + * @param buffer The bytes to decode. + */ + end(buffer?: string | NodeJS.ArrayBufferView): string; + } +} +declare module "node:string_decoder" { + export * from "string_decoder"; +} diff --git a/node_modules/@types/node/test.d.ts b/node_modules/@types/node/test.d.ts new file mode 100644 index 0000000..1e9613a --- /dev/null +++ b/node_modules/@types/node/test.d.ts @@ -0,0 +1,2163 @@ +/** + * The `node:test` module facilitates the creation of JavaScript tests. + * To access it: + * + * ```js + * import test from 'node:test'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'node:test'; + * ``` + * + * Tests created via the `test` module consist of a single function that is + * processed in one of three ways: + * + * 1. A synchronous function that is considered failing if it throws an exception, + * and is considered passing otherwise. + * 2. A function that returns a `Promise` that is considered failing if the `Promise` rejects, and is considered passing if the `Promise` fulfills. + * 3. A function that receives a callback function. If the callback receives any + * truthy value as its first argument, the test is considered failing. If a + * falsy value is passed as the first argument to the callback, the test is + * considered passing. If the test function receives a callback function and + * also returns a `Promise`, the test will fail. + * + * The following example illustrates how tests are written using the `test` module. + * + * ```js + * test('synchronous passing test', (t) => { + * // This test passes because it does not throw an exception. + * assert.strictEqual(1, 1); + * }); + * + * test('synchronous failing test', (t) => { + * // This test fails because it throws an exception. + * assert.strictEqual(1, 2); + * }); + * + * test('asynchronous passing test', async (t) => { + * // This test passes because the Promise returned by the async + * // function is settled and not rejected. + * assert.strictEqual(1, 1); + * }); + * + * test('asynchronous failing test', async (t) => { + * // This test fails because the Promise returned by the async + * // function is rejected. + * assert.strictEqual(1, 2); + * }); + * + * test('failing test using Promises', (t) => { + * // Promises can be used directly as well. + * return new Promise((resolve, reject) => { + * setImmediate(() => { + * reject(new Error('this will cause the test to fail')); + * }); + * }); + * }); + * + * test('callback passing test', (t, done) => { + * // done() is the callback function. When the setImmediate() runs, it invokes + * // done() with no arguments. + * setImmediate(done); + * }); + * + * test('callback failing test', (t, done) => { + * // When the setImmediate() runs, done() is invoked with an Error object and + * // the test fails. + * setImmediate(() => { + * done(new Error('callback failure')); + * }); + * }); + * ``` + * + * If any tests fail, the process exit code is set to `1`. + * @since v18.0.0, v16.17.0 + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/test.js) + */ +declare module "node:test" { + import { AssertMethodNames } from "node:assert"; + import { Readable } from "node:stream"; + import { URL } from "node:url"; + import TestFn = test.TestFn; + import TestOptions = test.TestOptions; + /** + * The `test()` function is the value imported from the `test` module. Each + * invocation of this function results in reporting the test to the `TestsStream`. + * + * The `TestContext` object passed to the `fn` argument can be used to perform + * actions related to the current test. Examples include skipping the test, adding + * additional diagnostic information, or creating subtests. + * + * `test()` returns a `Promise` that fulfills once the test completes. + * if `test()` is called within a suite, it fulfills immediately. + * The return value can usually be discarded for top level tests. + * However, the return value from subtests should be used to prevent the parent + * test from finishing first and cancelling the subtest + * as shown in the following example. + * + * ```js + * test('top level test', async (t) => { + * // The setTimeout() in the following subtest would cause it to outlive its + * // parent test if 'await' is removed on the next line. Once the parent test + * // completes, it will cancel any outstanding subtests. + * await t.test('longer running subtest', async (t) => { + * return new Promise((resolve, reject) => { + * setTimeout(resolve, 1000); + * }); + * }); + * }); + * ``` + * + * The `timeout` option can be used to fail the test if it takes longer than `timeout` milliseconds to complete. However, it is not a reliable mechanism for + * canceling tests because a running test might block the application thread and + * thus prevent the scheduled cancellation. + * @since v18.0.0, v16.17.0 + * @param name The name of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @return Fulfilled with `undefined` once the test completes, or immediately if the test runs within a suite. + */ + function test(name?: string, fn?: TestFn): Promise; + function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function test(options?: TestOptions, fn?: TestFn): Promise; + function test(fn?: TestFn): Promise; + namespace test { + export { test }; + export { suite as describe, test as it }; + } + namespace test { + /** + * **Note:** `shard` is used to horizontally parallelize test running across + * machines or processes, ideal for large-scale executions across varied + * environments. It's incompatible with `watch` mode, tailored for rapid + * code iteration by automatically rerunning tests on file changes. + * + * ```js + * import { tap } from 'node:test/reporters'; + * import { run } from 'node:test'; + * import process from 'node:process'; + * import path from 'node:path'; + * + * run({ files: [path.resolve('./tests/test.js')] }) + * .compose(tap) + * .pipe(process.stdout); + * ``` + * @since v18.9.0, v16.19.0 + * @param options Configuration options for running tests. + */ + function run(options?: RunOptions): TestsStream; + /** + * The `suite()` function is imported from the `node:test` module. + * @param name The name of the suite, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the suite. This supports the same options as {@link test}. + * @param fn The suite function declaring nested tests and suites. The first argument to this function is a {@link SuiteContext} object. + * @return Immediately fulfilled with `undefined`. + * @since v20.13.0 + */ + function suite(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function suite(name?: string, fn?: SuiteFn): Promise; + function suite(options?: TestOptions, fn?: SuiteFn): Promise; + function suite(fn?: SuiteFn): Promise; + namespace suite { + /** + * Shorthand for skipping a suite. This is the same as calling {@link suite} with `options.skip` set to `true`. + * @since v20.13.0 + */ + function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function skip(name?: string, fn?: SuiteFn): Promise; + function skip(options?: TestOptions, fn?: SuiteFn): Promise; + function skip(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `TODO`. This is the same as calling {@link suite} with `options.todo` set to `true`. + * @since v20.13.0 + */ + function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function todo(name?: string, fn?: SuiteFn): Promise; + function todo(options?: TestOptions, fn?: SuiteFn): Promise; + function todo(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `only`. This is the same as calling {@link suite} with `options.only` set to `true`. + * @since v20.13.0 + */ + function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function only(name?: string, fn?: SuiteFn): Promise; + function only(options?: TestOptions, fn?: SuiteFn): Promise; + function only(fn?: SuiteFn): Promise; + } + /** + * Shorthand for skipping a test. This is the same as calling {@link test} with `options.skip` set to `true`. + * @since v20.2.0 + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function skip(name?: string, fn?: TestFn): Promise; + function skip(options?: TestOptions, fn?: TestFn): Promise; + function skip(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `TODO`. This is the same as calling {@link test} with `options.todo` set to `true`. + * @since v20.2.0 + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function todo(name?: string, fn?: TestFn): Promise; + function todo(options?: TestOptions, fn?: TestFn): Promise; + function todo(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `only`. This is the same as calling {@link test} with `options.only` set to `true`. + * @since v20.2.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function only(name?: string, fn?: TestFn): Promise; + function only(options?: TestOptions, fn?: TestFn): Promise; + function only(fn?: TestFn): Promise; + /** + * The type of a function passed to {@link test}. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + */ + type TestFn = (t: TestContext, done: (result?: any) => void) => void | Promise; + /** + * The type of a suite test function. The argument to this function is a {@link SuiteContext} object. + */ + type SuiteFn = (s: SuiteContext) => void | Promise; + interface TestShard { + /** + * A positive integer between 1 and `total` that specifies the index of the shard to run. + */ + index: number; + /** + * A positive integer that specifies the total number of shards to split the test files to. + */ + total: number; + } + interface RunOptions { + /** + * If a number is provided, then that many test processes would run in parallel, where each process corresponds to one test file. + * If `true`, it would run `os.availableParallelism() - 1` test files in parallel. If `false`, it would only run one test file at a time. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * An array containing the list of files to run. If omitted, files are run according to the + * [test runner execution model](https://nodejs.org/docs/latest-v22.x/api/test.html#test-runner-execution-model). + */ + files?: readonly string[] | undefined; + /** + * Configures the test runner to exit the process once all known + * tests have finished executing even if the event loop would + * otherwise remain active. + * @default false + */ + forceExit?: boolean | undefined; + /** + * An array containing the list of glob patterns to match test files. + * This option cannot be used together with `files`. If omitted, files are run according to the + * [test runner execution model](https://nodejs.org/docs/latest-v22.x/api/test.html#test-runner-execution-model). + * @since v22.6.0 + */ + globPatterns?: readonly string[] | undefined; + /** + * Sets inspector port of test child process. + * This can be a number, or a function that takes no arguments and returns a + * number. If a nullish value is provided, each process gets its own port, + * incremented from the primary's `process.debugPort`. This option is ignored + * if the `isolation` option is set to `'none'` as no child processes are + * spawned. + * @default undefined + */ + inspectPort?: number | (() => number) | undefined; + /** + * Configures the type of test isolation. If set to + * `'process'`, each test file is run in a separate child process. If set to + * `'none'`, all test files run in the current process. + * @default 'process' + * @since v22.8.0 + */ + isolation?: "process" | "none" | undefined; + /** + * If truthy, the test context will only run tests that have the `only` option set + */ + only?: boolean | undefined; + /** + * A function that accepts the `TestsStream` instance and can be used to setup listeners before any tests are run. + * @default undefined + */ + setup?: ((reporter: TestsStream) => void | Promise) | undefined; + /** + * An array of CLI flags to pass to the `node` executable when + * spawning the subprocesses. This option has no effect when `isolation` is `'none`'. + * @since v22.10.0 + * @default [] + */ + execArgv?: readonly string[] | undefined; + /** + * An array of CLI flags to pass to each test file when spawning the + * subprocesses. This option has no effect when `isolation` is `'none'`. + * @since v22.10.0 + * @default [] + */ + argv?: readonly string[] | undefined; + /** + * Allows aborting an in-progress test execution. + */ + signal?: AbortSignal | undefined; + /** + * If provided, only run tests whose name matches the provided pattern. + * Strings are interpreted as JavaScript regular expressions. + * @default undefined + */ + testNamePatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * A String, RegExp or a RegExp Array, that can be used to exclude running tests whose + * name matches the provided pattern. Test name patterns are interpreted as JavaScript + * regular expressions. For each test that is executed, any corresponding test hooks, + * such as `beforeEach()`, are also run. + * @default undefined + * @since v22.1.0 + */ + testSkipPatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * The number of milliseconds after which the test execution will fail. + * If unspecified, subtests inherit this value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + /** + * Whether to run in watch mode or not. + * @default false + */ + watch?: boolean | undefined; + /** + * Running tests in a specific shard. + * @default undefined + */ + shard?: TestShard | undefined; + /** + * enable [code coverage](https://nodejs.org/docs/latest-v22.x/api/test.html#collecting-code-coverage) collection. + * @since v22.10.0 + * @default false + */ + coverage?: boolean | undefined; + /** + * Excludes specific files from code coverage + * using a glob pattern, which can match both absolute and relative file paths. + * This property is only applicable when `coverage` was set to `true`. + * If both `coverageExcludeGlobs` and `coverageIncludeGlobs` are provided, + * files must meet **both** criteria to be included in the coverage report. + * @since v22.10.0 + * @default undefined + */ + coverageExcludeGlobs?: string | readonly string[] | undefined; + /** + * Includes specific files in code coverage + * using a glob pattern, which can match both absolute and relative file paths. + * This property is only applicable when `coverage` was set to `true`. + * If both `coverageExcludeGlobs` and `coverageIncludeGlobs` are provided, + * files must meet **both** criteria to be included in the coverage report. + * @since v22.10.0 + * @default undefined + */ + coverageIncludeGlobs?: string | readonly string[] | undefined; + /** + * Require a minimum percent of covered lines. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + lineCoverage?: number | undefined; + /** + * Require a minimum percent of covered branches. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + branchCoverage?: number | undefined; + /** + * Require a minimum percent of covered functions. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + functionCoverage?: number | undefined; + } + /** + * A successful call to `run()` will return a new `TestsStream` object, streaming a series of events representing the execution of the tests. + * + * Some of the events are guaranteed to be emitted in the same order as the tests are defined, while others are emitted in the order that the tests execute. + * @since v18.9.0, v16.19.0 + */ + interface TestsStream extends Readable { + addListener(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + addListener(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + addListener(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + addListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + addListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + addListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + addListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + addListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + addListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; + addListener(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + addListener(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + addListener(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + addListener(event: "test:watch:drained", listener: () => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + emit(event: "test:coverage", data: EventData.TestCoverage): boolean; + emit(event: "test:complete", data: EventData.TestComplete): boolean; + emit(event: "test:dequeue", data: EventData.TestDequeue): boolean; + emit(event: "test:diagnostic", data: EventData.TestDiagnostic): boolean; + emit(event: "test:enqueue", data: EventData.TestEnqueue): boolean; + emit(event: "test:fail", data: EventData.TestFail): boolean; + emit(event: "test:pass", data: EventData.TestPass): boolean; + emit(event: "test:plan", data: EventData.TestPlan): boolean; + emit(event: "test:start", data: EventData.TestStart): boolean; + emit(event: "test:stderr", data: EventData.TestStderr): boolean; + emit(event: "test:stdout", data: EventData.TestStdout): boolean; + emit(event: "test:summary", data: EventData.TestSummary): boolean; + emit(event: "test:watch:drained"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + on(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + on(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + on(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + on(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + on(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + on(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + on(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + on(event: "test:start", listener: (data: EventData.TestStart) => void): this; + on(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + on(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + on(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + on(event: "test:watch:drained", listener: () => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + once(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + once(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + once(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + once(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + once(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + once(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + once(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + once(event: "test:start", listener: (data: EventData.TestStart) => void): this; + once(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + once(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + once(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + once(event: "test:watch:drained", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + prependListener(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + prependListener(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + prependListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + prependListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + prependListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + prependListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + prependListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + prependListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; + prependListener(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + prependListener(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + prependListener(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + prependListener(event: "test:watch:drained", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + prependOnceListener(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + prependOnceListener(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + prependOnceListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + prependOnceListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + prependOnceListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + prependOnceListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + prependOnceListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + prependOnceListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; + prependOnceListener(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + prependOnceListener(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + prependOnceListener(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + prependOnceListener(event: "test:watch:drained", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + } + namespace EventData { + interface Error extends globalThis.Error { + cause: globalThis.Error; + } + interface LocationInfo { + /** + * The column number where the test is defined, or + * `undefined` if the test was run through the REPL. + */ + column?: number; + /** + * The path of the test file, `undefined` if test was run through the REPL. + */ + file?: string; + /** + * The line number where the test is defined, or `undefined` if the test was run through the REPL. + */ + line?: number; + } + interface TestDiagnostic extends LocationInfo { + /** + * The diagnostic message. + */ + message: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The severity level of the diagnostic message. + * Possible values are: + * * `'info'`: Informational messages. + * * `'warn'`: Warnings. + * * `'error'`: Errors. + */ + level: "info" | "warn" | "error"; + } + interface TestCoverage { + /** + * An object containing the coverage report. + */ + summary: { + /** + * An array of coverage reports for individual files. + */ + files: Array<{ + /** + * The absolute path of the file. + */ + path: string; + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + /** + * An array of functions representing function coverage. + */ + functions: Array<{ + /** + * The name of the function. + */ + name: string; + /** + * The line number where the function is defined. + */ + line: number; + /** + * The number of times the function was called. + */ + count: number; + }>; + /** + * An array of branches representing branch coverage. + */ + branches: Array<{ + /** + * The line number where the branch is defined. + */ + line: number; + /** + * The number of times the branch was taken. + */ + count: number; + }>; + /** + * An array of lines representing line numbers and the number of times they were covered. + */ + lines: Array<{ + /** + * The line number. + */ + line: number; + /** + * The number of times the line was covered. + */ + count: number; + }>; + }>; + /** + * An object containing whether or not the coverage for + * each coverage type. + * @since v22.9.0 + */ + thresholds: { + /** + * The function coverage threshold. + */ + function: number; + /** + * The branch coverage threshold. + */ + branch: number; + /** + * The line coverage threshold. + */ + line: number; + }; + /** + * An object containing a summary of coverage for all files. + */ + totals: { + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + }; + /** + * The working directory when code coverage began. This + * is useful for displaying relative path names in case + * the tests changed the working directory of the Node.js process. + */ + workingDirectory: string; + }; + /** + * The nesting level of the test. + */ + nesting: number; + } + interface TestComplete extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * Whether the test passed or not. + */ + passed: boolean; + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test if it did not pass. + */ + error?: Error; + /** + * The type of the test, used to denote whether this is a suite. + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestDequeue extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The test type. Either `'suite'` or `'test'`. + * @since v22.15.0 + */ + type: "suite" | "test"; + } + interface TestEnqueue extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The test type. Either `'suite'` or `'test'`. + * @since v22.15.0 + */ + type: "suite" | "test"; + } + interface TestFail extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test. + */ + error: Error; + /** + * The type of the test, used to denote whether this is a suite. + * @since v20.0.0, v19.9.0, v18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestPass extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * The type of the test, used to denote whether this is a suite. + * @since 20.0.0, 19.9.0, 18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestPlan extends LocationInfo { + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The number of subtests that have ran. + */ + count: number; + } + interface TestStart extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + } + interface TestStderr { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stderr`. + */ + message: string; + } + interface TestStdout { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stdout`. + */ + message: string; + } + interface TestSummary { + /** + * An object containing the counts of various test results. + */ + counts: { + /** + * The total number of cancelled tests. + */ + cancelled: number; + /** + * The total number of passed tests. + */ + passed: number; + /** + * The total number of skipped tests. + */ + skipped: number; + /** + * The total number of suites run. + */ + suites: number; + /** + * The total number of tests run, excluding suites. + */ + tests: number; + /** + * The total number of TODO tests. + */ + todo: number; + /** + * The total number of top level tests and suites. + */ + topLevel: number; + }; + /** + * The duration of the test run in milliseconds. + */ + duration_ms: number; + /** + * The path of the test file that generated the + * summary. If the summary corresponds to multiple files, this value is + * `undefined`. + */ + file: string | undefined; + /** + * Indicates whether or not the test run is considered + * successful or not. If any error condition occurs, such as a failing test or + * unmet coverage threshold, this value will be set to `false`. + */ + success: boolean; + } + } + /** + * An instance of `TestContext` is passed to each test function in order to + * interact with the test runner. However, the `TestContext` constructor is not + * exposed as part of the API. + * @since v18.0.0, v16.17.0 + */ + interface TestContext { + /** + * An object containing assertion methods bound to the test context. + * The top-level functions from the `node:assert` module are exposed here for the purpose of creating test plans. + * + * **Note:** Some of the functions from `node:assert` contain type assertions. If these are called via the + * TestContext `assert` object, then the context parameter in the test's function signature **must be explicitly typed** + * (ie. the parameter must have a type annotation), otherwise an error will be raised by the TypeScript compiler: + * ```ts + * import { test, type TestContext } from 'node:test'; + * + * // The test function's context parameter must have a type annotation. + * test('example', (t: TestContext) => { + * t.assert.deepStrictEqual(actual, expected); + * }); + * + * // Omitting the type annotation will result in a compilation error. + * test('example', t => { + * t.assert.deepStrictEqual(actual, expected); // Error: 't' needs an explicit type annotation. + * }); + * ``` + * @since v22.2.0, v20.15.0 + */ + readonly assert: TestContextAssert; + /** + * This function is used to create a hook running before subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v20.1.0, v18.17.0 + */ + before(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running before each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + beforeEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook that runs after the current test finishes. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.13.0 + */ + after(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + afterEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to write diagnostics to the output. Any diagnostic + * information is included at the end of the test's results. This function does + * not return a value. + * + * ```js + * test('top level test', (t) => { + * t.diagnostic('A diagnostic message'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Message to be reported. + */ + diagnostic(message: string): void; + /** + * The absolute path of the test file that created the current test. If a test file imports + * additional modules that generate tests, the imported tests will return the path of the root test file. + * @since v22.6.0 + */ + readonly filePath: string | undefined; + /** + * The name of the test and each of its ancestors, separated by `>`. + * @since v22.3.0 + */ + readonly fullName: string; + /** + * The name of the test. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * This function is used to set the number of assertions and subtests that are expected to run + * within the test. If the number of assertions and subtests that run does not match the + * expected count, the test will fail. + * + * > Note: To make sure assertions are tracked, `t.assert` must be used instead of `assert` directly. + * + * ```js + * test('top level test', (t) => { + * t.plan(2); + * t.assert.ok('some relevant assertion here'); + * t.test('subtest', () => {}); + * }); + * ``` + * + * When working with asynchronous code, the `plan` function can be used to ensure that the + * correct number of assertions are run: + * + * ```js + * test('planning with streams', (t, done) => { + * function* generate() { + * yield 'a'; + * yield 'b'; + * yield 'c'; + * } + * const expected = ['a', 'b', 'c']; + * t.plan(expected.length); + * const stream = Readable.from(generate()); + * stream.on('data', (chunk) => { + * t.assert.strictEqual(chunk, expected.shift()); + * }); + * + * stream.on('end', () => { + * done(); + * }); + * }); + * ``` + * + * When using the `wait` option, you can control how long the test will wait for the expected assertions. + * For example, setting a maximum wait time ensures that the test will wait for asynchronous assertions + * to complete within the specified timeframe: + * + * ```js + * test('plan with wait: 2000 waits for async assertions', (t) => { + * t.plan(1, { wait: 2000 }); // Waits for up to 2 seconds for the assertion to complete. + * + * const asyncActivity = () => { + * setTimeout(() => { + * * t.assert.ok(true, 'Async assertion completed within the wait time'); + * }, 1000); // Completes after 1 second, within the 2-second wait time. + * }; + * + * asyncActivity(); // The test will pass because the assertion is completed in time. + * }); + * ``` + * + * Note: If a `wait` timeout is specified, it begins counting down only after the test function finishes executing. + * @since v22.2.0 + */ + plan(count: number, options?: TestContextPlanOptions): void; + /** + * If `shouldRunOnlyTests` is truthy, the test context will only run tests that + * have the `only` option set. Otherwise, all tests are run. If Node.js was not + * started with the `--test-only` command-line option, this function is a + * no-op. + * + * ```js + * test('top level test', (t) => { + * // The test context can be set to run subtests with the 'only' option. + * t.runOnly(true); + * return Promise.all([ + * t.test('this subtest is now skipped'), + * t.test('this subtest is run', { only: true }), + * ]); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param shouldRunOnlyTests Whether or not to run `only` tests. + */ + runOnly(shouldRunOnlyTests: boolean): void; + /** + * ```js + * test('top level test', async (t) => { + * await fetch('some/uri', { signal: t.signal }); + * }); + * ``` + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + /** + * This function causes the test's output to indicate the test as skipped. If `message` is provided, it is included in the output. Calling `skip()` does + * not terminate execution of the test function. This function does not return a + * value. + * + * ```js + * test('top level test', (t) => { + * // Make sure to return here as well if the test contains additional logic. + * t.skip('this is skipped'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional skip message. + */ + skip(message?: string): void; + /** + * This function adds a `TODO` directive to the test's output. If `message` is + * provided, it is included in the output. Calling `todo()` does not terminate + * execution of the test function. This function does not return a value. + * + * ```js + * test('top level test', (t) => { + * // This test is marked as `TODO` + * t.todo('this is a todo'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional `TODO` message. + */ + todo(message?: string): void; + /** + * This function is used to create subtests under the current test. This function behaves in + * the same fashion as the top level {@link test} function. + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. This first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + test: typeof test; + /** + * This method polls a `condition` function until that function either returns + * successfully or the operation times out. + * @since v22.14.0 + * @param condition An assertion function that is invoked + * periodically until it completes successfully or the defined polling timeout + * elapses. Successful completion is defined as not throwing or rejecting. This + * function does not accept any arguments, and is allowed to return any value. + * @param options An optional configuration object for the polling operation. + * @returns Fulfilled with the value returned by `condition`. + */ + waitFor(condition: () => T, options?: TestContextWaitForOptions): Promise>; + /** + * Each test provides its own MockTracker instance. + */ + readonly mock: MockTracker; + } + interface TestContextAssert extends Pick { + /** + * This function serializes `value` and writes it to the file specified by `path`. + * + * ```js + * test('snapshot test with default serialization', (t) => { + * t.assert.fileSnapshot({ value1: 1, value2: 2 }, './snapshots/snapshot.json'); + * }); + * ``` + * + * This function differs from `context.assert.snapshot()` in the following ways: + * + * * The snapshot file path is explicitly provided by the user. + * * Each snapshot file is limited to a single snapshot value. + * * No additional escaping is performed by the test runner. + * + * These differences allow snapshot files to better support features such as syntax + * highlighting. + * @since v22.14.0 + * @param value A value to serialize to a string. If Node.js was started with + * the [`--test-update-snapshots`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--test-update-snapshots) + * flag, the serialized value is written to + * `path`. Otherwise, the serialized value is compared to the contents of the + * existing snapshot file. + * @param path The file where the serialized `value` is written. + * @param options Optional configuration options. + */ + fileSnapshot(value: any, path: string, options?: AssertSnapshotOptions): void; + /** + * This function implements assertions for snapshot testing. + * ```js + * test('snapshot test with default serialization', (t) => { + * t.assert.snapshot({ value1: 1, value2: 2 }); + * }); + * + * test('snapshot test with custom serialization', (t) => { + * t.assert.snapshot({ value3: 3, value4: 4 }, { + * serializers: [(value) => JSON.stringify(value)] + * }); + * }); + * ``` + * @since v22.3.0 + * @param value A value to serialize to a string. If Node.js was started with + * the [`--test-update-snapshots`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--test-update-snapshots) + * flag, the serialized value is written to + * the snapshot file. Otherwise, the serialized value is compared to the + * corresponding value in the existing snapshot file. + */ + snapshot(value: any, options?: AssertSnapshotOptions): void; + /** + * A custom assertion function registered with `assert.register()`. + */ + [name: string]: (...args: any[]) => void; + } + interface AssertSnapshotOptions { + /** + * An array of synchronous functions used to serialize `value` into a string. + * `value` is passed as the only argument to the first serializer function. + * The return value of each serializer is passed as input to the next serializer. + * Once all serializers have run, the resulting value is coerced to a string. + * + * If no serializers are provided, the test runner's default serializers are used. + */ + serializers?: ReadonlyArray<(value: any) => any> | undefined; + } + interface TestContextPlanOptions { + /** + * The wait time for the plan: + * * If `true`, the plan waits indefinitely for all assertions and subtests to run. + * * If `false`, the plan performs an immediate check after the test function completes, + * without waiting for any pending assertions or subtests. + * Any assertions or subtests that complete after this check will not be counted towards the plan. + * * If a number, it specifies the maximum wait time in milliseconds + * before timing out while waiting for expected assertions and subtests to be matched. + * If the timeout is reached, the test will fail. + * @default false + */ + wait?: boolean | number | undefined; + } + interface TestContextWaitForOptions { + /** + * The number of milliseconds to wait after an unsuccessful + * invocation of `condition` before trying again. + * @default 50 + */ + interval?: number | undefined; + /** + * The poll timeout in milliseconds. If `condition` has not + * succeeded by the time this elapses, an error occurs. + * @default 1000 + */ + timeout?: number | undefined; + } + /** + * An instance of `SuiteContext` is passed to each suite function in order to + * interact with the test runner. However, the `SuiteContext` constructor is not + * exposed as part of the API. + * @since v18.7.0, v16.17.0 + */ + interface SuiteContext { + /** + * The absolute path of the test file that created the current suite. If a test file imports + * additional modules that generate suites, the imported suites will return the path of the root test file. + * @since v22.6.0 + */ + readonly filePath: string | undefined; + /** + * The name of the suite. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * Can be used to abort test subtasks when the test has been aborted. + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + } + interface TestOptions { + /** + * If a number is provided, then that many tests would run in parallel. + * If truthy, it would run (number of cpu cores - 1) tests in parallel. + * For subtests, it will be `Infinity` tests in parallel. + * If falsy, it would only run one test at a time. + * If unspecified, subtests inherit this value from their parent. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * If truthy, and the test context is configured to run `only` tests, then this test will be + * run. Otherwise, the test is skipped. + * @default false + */ + only?: boolean | undefined; + /** + * Allows aborting an in-progress test. + * @since v18.8.0 + */ + signal?: AbortSignal | undefined; + /** + * If truthy, the test is skipped. If a string is provided, that string is displayed in the + * test results as the reason for skipping the test. + * @default false + */ + skip?: boolean | string | undefined; + /** + * A number of milliseconds the test will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + * @since v18.7.0 + */ + timeout?: number | undefined; + /** + * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in + * the test results as the reason why the test is `TODO`. + * @default false + */ + todo?: boolean | string | undefined; + /** + * The number of assertions and subtests expected to be run in the test. + * If the number of assertions run in the test does not match the number + * specified in the plan, the test will fail. + * @default undefined + * @since v22.2.0 + */ + plan?: number | undefined; + } + /** + * This function creates a hook that runs before executing a suite. + * + * ```js + * describe('tests', async () => { + * before(() => console.log('about to run some test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function before(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after executing a suite. + * + * ```js + * describe('tests', async () => { + * after(() => console.log('finished running tests')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function after(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs before each test in the current suite. + * + * ```js + * describe('tests', async () => { + * beforeEach(() => console.log('about to run a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function beforeEach(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after each test in the current suite. + * The `afterEach()` hook is run even if the test fails. + * + * ```js + * describe('tests', async () => { + * afterEach(() => console.log('finished running a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function afterEach(fn?: HookFn, options?: HookOptions): void; + /** + * The hook function. The first argument is the context in which the hook is called. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type HookFn = (c: TestContext | SuiteContext, done: (result?: any) => void) => any; + /** + * The hook function. The first argument is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type TestContextHookFn = (t: TestContext, done: (result?: any) => void) => any; + /** + * Configuration options for hooks. + * @since v18.8.0 + */ + interface HookOptions { + /** + * Allows aborting an in-progress hook. + */ + signal?: AbortSignal | undefined; + /** + * A number of milliseconds the hook will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + } + interface MockFunctionOptions { + /** + * The number of times that the mock will use the behavior of `implementation`. + * Once the mock function has been called `times` times, + * it will automatically restore the behavior of `original`. + * This value must be an integer greater than zero. + * @default Infinity + */ + times?: number | undefined; + } + interface MockMethodOptions extends MockFunctionOptions { + /** + * If `true`, `object[methodName]` is treated as a getter. + * This option cannot be used with the `setter` option. + */ + getter?: boolean | undefined; + /** + * If `true`, `object[methodName]` is treated as a setter. + * This option cannot be used with the `getter` option. + */ + setter?: boolean | undefined; + } + type Mock = F & { + mock: MockFunctionContext; + }; + interface MockModuleOptions { + /** + * If false, each call to `require()` or `import()` generates a new mock module. + * If true, subsequent calls will return the same module mock, and the mock module is inserted into the CommonJS cache. + * @default false + */ + cache?: boolean | undefined; + /** + * The value to use as the mocked module's default export. + * + * If this value is not provided, ESM mocks do not include a default export. + * If the mock is a CommonJS or builtin module, this setting is used as the value of `module.exports`. + * If this value is not provided, CJS and builtin mocks use an empty object as the value of `module.exports`. + */ + defaultExport?: any; + /** + * An object whose keys and values are used to create the named exports of the mock module. + * + * If the mock is a CommonJS or builtin module, these values are copied onto `module.exports`. + * Therefore, if a mock is created with both named exports and a non-object default export, + * the mock will throw an exception when used as a CJS or builtin module. + */ + namedExports?: object | undefined; + } + /** + * The `MockTracker` class is used to manage mocking functionality. The test runner + * module provides a top level `mock` export which is a `MockTracker` instance. + * Each test also provides its own `MockTracker` instance via the test context's `mock` property. + * @since v19.1.0, v18.13.0 + */ + interface MockTracker { + /** + * This function is used to create a mock function. + * + * The following example creates a mock function that increments a counter by one + * on each invocation. The `times` option is used to modify the mock behavior such + * that the first two invocations add two to the counter instead of one. + * + * ```js + * test('mocks a counting function', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne, addTwo, { times: 2 }); + * + * assert.strictEqual(fn(), 2); + * assert.strictEqual(fn(), 4); + * assert.strictEqual(fn(), 5); + * assert.strictEqual(fn(), 6); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param original An optional function to create a mock on. + * @param implementation An optional function used as the mock implementation for `original`. This is useful for creating mocks that exhibit one behavior for a specified number of calls and + * then restore the behavior of `original`. + * @param options Optional configuration options for the mock function. + * @return The mocked function. The mocked function contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked function. + */ + fn undefined>( + original?: F, + options?: MockFunctionOptions, + ): Mock; + fn undefined, Implementation extends Function = F>( + original?: F, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock; + /** + * This function is used to create a mock on an existing object method. The + * following example demonstrates how a mock is created on an existing object + * method. + * + * ```js + * test('spies on an object method', (t) => { + * const number = { + * value: 5, + * subtract(a) { + * return this.value - a; + * }, + * }; + * + * t.mock.method(number, 'subtract'); + * assert.strictEqual(number.subtract.mock.calls.length, 0); + * assert.strictEqual(number.subtract(3), 2); + * assert.strictEqual(number.subtract.mock.calls.length, 1); + * + * const call = number.subtract.mock.calls[0]; + * + * assert.deepStrictEqual(call.arguments, [3]); + * assert.strictEqual(call.result, 2); + * assert.strictEqual(call.error, undefined); + * assert.strictEqual(call.target, undefined); + * assert.strictEqual(call.this, number); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param object The object whose method is being mocked. + * @param methodName The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown. + * @param implementation An optional function used as the mock implementation for `object[methodName]`. + * @param options Optional configuration options for the mock method. + * @return The mocked method. The mocked method contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked method. + */ + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation: Implementation, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method( + object: MockedObject, + methodName: keyof MockedObject, + options: MockMethodOptions, + ): Mock; + method( + object: MockedObject, + methodName: keyof MockedObject, + implementation: Function, + options: MockMethodOptions, + ): Mock; + /** + * This function is syntax sugar for `MockTracker.method` with `options.getter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<() => MockedObject[MethodName]>; + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<(() => MockedObject[MethodName]) | Implementation>; + /** + * This function is syntax sugar for `MockTracker.method` with `options.setter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<(value: MockedObject[MethodName]) => void>; + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<((value: MockedObject[MethodName]) => void) | Implementation>; + /** + * This function is used to mock the exports of ECMAScript modules, CommonJS modules, and Node.js builtin modules. + * Any references to the original module prior to mocking are not impacted. + * + * Only available through the [--experimental-test-module-mocks](https://nodejs.org/api/cli.html#--experimental-test-module-mocks) flag. + * @since v22.3.0 + * @experimental + * @param specifier A string identifying the module to mock. + * @param options Optional configuration options for the mock module. + */ + module(specifier: string | URL, options?: MockModuleOptions): MockModuleContext; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker` and disassociates the mocks from the `MockTracker` instance. Once disassociated, the mocks can still be used, but the `MockTracker` instance can no longer be + * used to reset their behavior or + * otherwise interact with them. + * + * After each test completes, this function is called on the test context's `MockTracker`. If the global `MockTracker` is used extensively, calling this + * function manually is recommended. + * @since v19.1.0, v18.13.0 + */ + reset(): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does + * not disassociate the mocks from the `MockTracker` instance. + * @since v19.1.0, v18.13.0 + */ + restoreAll(): void; + readonly timers: MockTimers; + } + const mock: MockTracker; + interface MockFunctionCall< + F extends Function, + ReturnType = F extends (...args: any) => infer T ? T + : F extends abstract new(...args: any) => infer T ? T + : unknown, + Args = F extends (...args: infer Y) => any ? Y + : F extends abstract new(...args: infer Y) => any ? Y + : unknown[], + > { + /** + * An array of the arguments passed to the mock function. + */ + arguments: Args; + /** + * If the mocked function threw then this property contains the thrown value. + */ + error: unknown | undefined; + /** + * The value returned by the mocked function. + * + * If the mocked function threw, it will be `undefined`. + */ + result: ReturnType | undefined; + /** + * An `Error` object whose stack can be used to determine the callsite of the mocked function invocation. + */ + stack: Error; + /** + * If the mocked function is a constructor, this field contains the class being constructed. + * Otherwise this will be `undefined`. + */ + target: F extends abstract new(...args: any) => any ? F : undefined; + /** + * The mocked function's `this` value. + */ + this: unknown; + } + /** + * The `MockFunctionContext` class is used to inspect or manipulate the behavior of + * mocks created via the `MockTracker` APIs. + * @since v19.1.0, v18.13.0 + */ + interface MockFunctionContext { + /** + * A getter that returns a copy of the internal array used to track calls to the + * mock. Each entry in the array is an object with the following properties. + * @since v19.1.0, v18.13.0 + */ + readonly calls: MockFunctionCall[]; + /** + * This function returns the number of times that this mock has been invoked. This + * function is more efficient than checking `ctx.calls.length` because `ctx.calls` is a getter that creates a copy of the internal call tracking array. + * @since v19.1.0, v18.13.0 + * @return The number of times that this mock has been invoked. + */ + callCount(): number; + /** + * This function is used to change the behavior of an existing mock. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, and then changes the mock implementation to a different function. + * + * ```js + * test('changes a mock behavior', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementation(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 5); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's new implementation. + */ + mockImplementation(implementation: F): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onCall` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, changes the mock implementation to a different function for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementationOnce(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 4); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's implementation for the invocation number specified by `onCall`. + * @param onCall The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown. + */ + mockImplementationOnce(implementation: F, onCall?: number): void; + /** + * Resets the call history of the mock function. + * @since v19.3.0, v18.13.0 + */ + resetCalls(): void; + /** + * Resets the implementation of the mock function to its original behavior. The + * mock can still be used after calling this function. + * @since v19.1.0, v18.13.0 + */ + restore(): void; + } + /** + * @since v22.3.0 + * @experimental + */ + interface MockModuleContext { + /** + * Resets the implementation of the mock module. + * @since v22.3.0 + */ + restore(): void; + } + interface MockTimersOptions { + apis: ReadonlyArray<"setInterval" | "setTimeout" | "setImmediate" | "Date">; + now?: number | Date | undefined; + } + /** + * Mocking timers is a technique commonly used in software testing to simulate and + * control the behavior of timers, such as `setInterval` and `setTimeout`, + * without actually waiting for the specified time intervals. + * + * The MockTimers API also allows for mocking of the `Date` constructor and + * `setImmediate`/`clearImmediate` functions. + * + * The `MockTracker` provides a top-level `timers` export + * which is a `MockTimers` instance. + * @since v20.4.0 + * @experimental + */ + interface MockTimers { + /** + * Enables timer mocking for the specified timers. + * + * **Note:** When you enable mocking for a specific timer, its associated + * clear function will also be implicitly mocked. + * + * **Note:** Mocking `Date` will affect the behavior of the mocked timers + * as they use the same internal clock. + * + * Example usage without setting initial time: + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1234 }); + * ``` + * + * The above example enables mocking for the `Date` constructor, `setInterval` timer and + * implicitly mocks the `clearInterval` function. Only the `Date` constructor from `globalThis`, + * `setInterval` and `clearInterval` functions from `node:timers`, `node:timers/promises`, and `globalThis` will be mocked. + * + * Example usage with initial time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: 1000 }); + * ``` + * + * Example usage with initial Date object as time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: new Date() }); + * ``` + * + * Alternatively, if you call `mock.timers.enable()` without any parameters: + * + * All timers (`'setInterval'`, `'clearInterval'`, `'Date'`, `'setImmediate'`, `'clearImmediate'`, `'setTimeout'`, and `'clearTimeout'`) + * will be mocked. + * + * The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout` functions from `node:timers`, `node:timers/promises`, + * and `globalThis` will be mocked. + * The `Date` constructor from `globalThis` will be mocked. + * + * If there is no initial epoch set, the initial date will be based on 0 in the Unix epoch. This is `January 1st, 1970, 00:00:00 UTC`. You can + * set an initial date by passing a now property to the `.enable()` method. This value will be used as the initial date for the mocked Date + * object. It can either be a positive integer, or another Date object. + * @since v20.4.0 + */ + enable(options?: MockTimersOptions): void; + /** + * You can use the `.setTime()` method to manually move the mocked date to another time. This method only accepts a positive integer. + * Note: This method will execute any mocked timers that are in the past from the new time. + * In the below example we are setting a new time for the mocked date. + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * test('sets the time of a date object', (context) => { + * // Optionally choose what to mock + * context.mock.timers.enable({ apis: ['Date'], now: 100 }); + * assert.strictEqual(Date.now(), 100); + * // Advance in time will also advance the date + * context.mock.timers.setTime(1000); + * context.mock.timers.tick(200); + * assert.strictEqual(Date.now(), 1200); + * }); + * ``` + */ + setTime(time: number): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTimers` instance and disassociates the mocks + * from the `MockTracker` instance. + * + * **Note:** After each test completes, this function is called on + * the test context's `MockTracker`. + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.reset(); + * ``` + * @since v20.4.0 + */ + reset(): void; + /** + * Advances time for all mocked timers. + * + * **Note:** This diverges from how `setTimeout` in Node.js behaves and accepts + * only positive numbers. In Node.js, `setTimeout` with negative numbers is + * only supported for web compatibility reasons. + * + * The following example mocks a `setTimeout` function and + * by using `.tick` advances in + * time triggering all pending timers. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Alternativelly, the `.tick` function can be called many times + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * const nineSecs = 9000; + * setTimeout(fn, nineSecs); + * + * const twoSeconds = 3000; + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Advancing time using `.tick` will also advance the time for any `Date` object + * created after the mock was enabled (if `Date` was also set to be mocked). + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * assert.strictEqual(Date.now(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * assert.strictEqual(fn.mock.callCount(), 1); + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * @since v20.4.0 + */ + tick(milliseconds: number): void; + /** + * Triggers all pending mocked timers immediately. If the `Date` object is also + * mocked, it will also advance the `Date` object to the furthest timer's time. + * + * The example below triggers all pending timers immediately, + * causing them to execute without any delay. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('runAll functions following the given order', (context) => { + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * const results = []; + * setTimeout(() => results.push(1), 9999); + * + * // Notice that if both timers have the same timeout, + * // the order of execution is guaranteed + * setTimeout(() => results.push(3), 8888); + * setTimeout(() => results.push(2), 8888); + * + * assert.deepStrictEqual(results, []); + * + * context.mock.timers.runAll(); + * assert.deepStrictEqual(results, [3, 2, 1]); + * // The Date object is also advanced to the furthest timer's time + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * + * **Note:** The `runAll()` function is specifically designed for + * triggering timers in the context of timer mocking. + * It does not have any effect on real-time system + * clocks or actual timers outside of the mocking environment. + * @since v20.4.0 + */ + runAll(): void; + /** + * Calls {@link MockTimers.reset()}. + */ + [Symbol.dispose](): void; + } + /** + * An object whose methods are used to configure available assertions on the + * `TestContext` objects in the current process. The methods from `node:assert` + * and snapshot testing functions are available by default. + * + * It is possible to apply the same configuration to all files by placing common + * configuration code in a module + * preloaded with `--require` or `--import`. + * @since v22.14.0 + */ + namespace assert { + /** + * Defines a new assertion function with the provided name and function. If an + * assertion already exists with the same name, it is overwritten. + * @since v22.14.0 + */ + function register(name: string, fn: (this: TestContext, ...args: any[]) => void): void; + } + /** + * @since v22.3.0 + */ + namespace snapshot { + /** + * This function is used to customize the default serialization mechanism used by the test runner. + * + * By default, the test runner performs serialization by calling `JSON.stringify(value, null, 2)` on the provided value. + * `JSON.stringify()` does have limitations regarding circular structures and supported data types. + * If a more robust serialization mechanism is required, this function should be used to specify a list of custom serializers. + * + * Serializers are called in order, with the output of the previous serializer passed as input to the next. + * The final result must be a string value. + * @since v22.3.0 + * @param serializers An array of synchronous functions used as the default serializers for snapshot tests. + */ + function setDefaultSnapshotSerializers(serializers: ReadonlyArray<(value: any) => any>): void; + /** + * This function is used to set a custom resolver for the location of the snapshot file used for snapshot testing. + * By default, the snapshot filename is the same as the entry point filename with `.snapshot` appended. + * @since v22.3.0 + * @param fn A function used to compute the location of the snapshot file. + * The function receives the path of the test file as its only argument. If the + * test is not associated with a file (for example in the REPL), the input is + * undefined. `fn()` must return a string specifying the location of the snapshot file. + */ + function setResolveSnapshotPath(fn: (path: string | undefined) => string): void; + } + } + type FunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? K : never; + }[keyof T]; + export = test; +} + +/** + * The `node:test/reporters` module exposes the builtin-reporters for `node:test`. + * To access it: + * + * ```js + * import test from 'node:test/reporters'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'node:test/reporters'; + * ``` + * @since v19.9.0 + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/test/reporters.js) + */ +declare module "node:test/reporters" { + import { Transform, TransformOptions } from "node:stream"; + import { EventData } from "node:test"; + + type TestEvent = + | { type: "test:coverage"; data: EventData.TestCoverage } + | { type: "test:complete"; data: EventData.TestComplete } + | { type: "test:dequeue"; data: EventData.TestDequeue } + | { type: "test:diagnostic"; data: EventData.TestDiagnostic } + | { type: "test:enqueue"; data: EventData.TestEnqueue } + | { type: "test:fail"; data: EventData.TestFail } + | { type: "test:pass"; data: EventData.TestPass } + | { type: "test:plan"; data: EventData.TestPlan } + | { type: "test:start"; data: EventData.TestStart } + | { type: "test:stderr"; data: EventData.TestStderr } + | { type: "test:stdout"; data: EventData.TestStdout } + | { type: "test:summary"; data: EventData.TestSummary } + | { type: "test:watch:drained"; data: undefined }; + type TestEventGenerator = AsyncGenerator; + + interface ReporterConstructorWrapper Transform> { + new(...args: ConstructorParameters): InstanceType; + (...args: ConstructorParameters): InstanceType; + } + + /** + * The `dot` reporter outputs the test results in a compact format, + * where each passing test is represented by a `.`, + * and each failing test is represented by a `X`. + * @since v20.0.0 + */ + function dot(source: TestEventGenerator): AsyncGenerator<"\n" | "." | "X", void>; + /** + * The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format. + * @since v20.0.0 + */ + function tap(source: TestEventGenerator): AsyncGenerator; + class SpecReporter extends Transform { + constructor(); + } + /** + * The `spec` reporter outputs the test results in a human-readable format. + * @since v20.0.0 + */ + const spec: ReporterConstructorWrapper; + /** + * The `junit` reporter outputs test results in a jUnit XML format. + * @since v21.0.0 + */ + function junit(source: TestEventGenerator): AsyncGenerator; + class LcovReporter extends Transform { + constructor(opts?: Omit); + } + /** + * The `lcov` reporter outputs test coverage when used with the + * [`--experimental-test-coverage`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--experimental-test-coverage) flag. + * @since v22.0.0 + */ + const lcov: LcovReporter; + + export { dot, junit, lcov, spec, tap, TestEvent }; +} diff --git a/node_modules/@types/node/timers.d.ts b/node_modules/@types/node/timers.d.ts new file mode 100644 index 0000000..44bc977 --- /dev/null +++ b/node_modules/@types/node/timers.d.ts @@ -0,0 +1,287 @@ +/** + * The `timer` module exposes a global API for scheduling functions to + * be called at some future period of time. Because the timer functions are + * globals, there is no need to import `node:timers` to use the API. + * + * The timer functions within Node.js implement a similar API as the timers API + * provided by Web Browsers but use a different internal implementation that is + * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/timers.js) + */ +declare module "timers" { + import { Abortable } from "node:events"; + import * as promises from "node:timers/promises"; + export interface TimerOptions extends Abortable { + /** + * Set to `false` to indicate that the scheduled `Timeout` + * should not require the Node.js event loop to remain active. + * @default true + */ + ref?: boolean | undefined; + } + global { + namespace NodeJS { + /** + * This object is created internally and is returned from `setImmediate()`. It + * can be passed to `clearImmediate()` in order to cancel the scheduled + * actions. + * + * By default, when an immediate is scheduled, the Node.js event loop will continue + * running as long as the immediate is active. The `Immediate` object returned by + * `setImmediate()` exports both `immediate.ref()` and `immediate.unref()` + * functions that can be used to control this default behavior. + */ + interface Immediate extends RefCounted, Disposable { + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the + * `Immediate` is active. Calling `immediate.ref()` multiple times will have no + * effect. + * + * By default, all `Immediate` objects are "ref'ed", making it normally unnecessary + * to call `immediate.ref()` unless `immediate.unref()` had been called previously. + * @since v9.7.0 + * @returns a reference to `immediate` + */ + ref(): this; + /** + * When called, the active `Immediate` object will not require the Node.js event + * loop to remain active. If there is no other activity keeping the event loop + * running, the process may exit before the `Immediate` object's callback is + * invoked. Calling `immediate.unref()` multiple times will have no effect. + * @since v9.7.0 + * @returns a reference to `immediate` + */ + unref(): this; + /** + * Cancels the immediate. This is similar to calling `clearImmediate()`. + * @since v20.5.0, v18.18.0 + * @experimental + */ + [Symbol.dispose](): void; + _onImmediate(...args: any[]): void; + } + // Legacy interface used in Node.js v9 and prior + // TODO: remove in a future major version bump + /** @deprecated Use `NodeJS.Timeout` instead. */ + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + /** + * This object is created internally and is returned from `setTimeout()` and + * `setInterval()`. It can be passed to either `clearTimeout()` or + * `clearInterval()` in order to cancel the scheduled actions. + * + * By default, when a timer is scheduled using either `setTimeout()` or + * `setInterval()`, the Node.js event loop will continue running as long as the + * timer is active. Each of the `Timeout` objects returned by these functions + * export both `timeout.ref()` and `timeout.unref()` functions that can be used to + * control this default behavior. + */ + interface Timeout extends RefCounted, Disposable, Timer { + /** + * Cancels the timeout. + * @since v0.9.1 + * @legacy Use `clearTimeout()` instead. + * @returns a reference to `timeout` + */ + close(): this; + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the + * `Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. + * + * By default, all `Timeout` objects are "ref'ed", making it normally unnecessary + * to call `timeout.ref()` unless `timeout.unref()` had been called previously. + * @since v0.9.1 + * @returns a reference to `timeout` + */ + ref(): this; + /** + * Sets the timer's start time to the current time, and reschedules the timer to + * call its callback at the previously specified duration adjusted to the current + * time. This is useful for refreshing a timer without allocating a new + * JavaScript object. + * + * Using this on a timer that has already called its callback will reactivate the + * timer. + * @since v10.2.0 + * @returns a reference to `timeout` + */ + refresh(): this; + /** + * When called, the active `Timeout` object will not require the Node.js event loop + * to remain active. If there is no other activity keeping the event loop running, + * the process may exit before the `Timeout` object's callback is invoked. Calling + * `timeout.unref()` multiple times will have no effect. + * @since v0.9.1 + * @returns a reference to `timeout` + */ + unref(): this; + /** + * Coerce a `Timeout` to a primitive. The primitive can be used to + * clear the `Timeout`. The primitive can only be used in the + * same thread where the timeout was created. Therefore, to use it + * across `worker_threads` it must first be passed to the correct + * thread. This allows enhanced compatibility with browser + * `setTimeout()` and `setInterval()` implementations. + * @since v14.9.0, v12.19.0 + */ + [Symbol.toPrimitive](): number; + /** + * Cancels the timeout. + * @since v20.5.0, v18.18.0 + * @experimental + */ + [Symbol.dispose](): void; + _onTimeout(...args: any[]): void; + } + } + /** + * Schedules the "immediate" execution of the `callback` after I/O events' + * callbacks. + * + * When multiple calls to `setImmediate()` are made, the `callback` functions are + * queued for execution in the order in which they are created. The entire callback + * queue is processed every event loop iteration. If an immediate timer is queued + * from inside an executing callback, that timer will not be triggered until the + * next event loop iteration. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using + * `timersPromises.setImmediate()`. + * @since v0.9.1 + * @param callback The function to call at the end of this turn of + * the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout) + * @param args Optional arguments to pass when the `callback` is called. + * @returns for use with `clearImmediate()` + */ + function setImmediate( + callback: (...args: TArgs) => void, + ...args: TArgs + ): NodeJS.Immediate; + // Allow a single void-accepting argument to be optional in arguments lists. + // Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258) + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setImmediate(callback: (_: void) => void): NodeJS.Immediate; + namespace setImmediate { + import __promisify__ = promises.setImmediate; + export { __promisify__ }; + } + /** + * Schedules repeated execution of `callback` every `delay` milliseconds. + * + * When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay` + * will be set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using + * `timersPromises.setInterval()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param delay The number of milliseconds to wait before calling the + * `callback`. **Default:** `1`. + * @param args Optional arguments to pass when the `callback` is called. + * @returns for use with `clearInterval()` + */ + function setInterval( + callback: (...args: TArgs) => void, + delay?: number, + ...args: TArgs + ): NodeJS.Timeout; + // Allow a single void-accepting argument to be optional in arguments lists. + // Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258) + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setInterval(callback: (_: void) => void, delay?: number): NodeJS.Timeout; + /** + * Schedules execution of a one-time `callback` after `delay` milliseconds. + * + * The `callback` will likely not be invoked in precisely `delay` milliseconds. + * Node.js makes no guarantees about the exact timing of when callbacks will fire, + * nor of their ordering. The callback will be called as close as possible to the + * time specified. + * + * When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay` + * will be set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using + * `timersPromises.setTimeout()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param delay The number of milliseconds to wait before calling the + * `callback`. **Default:** `1`. + * @param args Optional arguments to pass when the `callback` is called. + * @returns for use with `clearTimeout()` + */ + function setTimeout( + callback: (...args: TArgs) => void, + delay?: number, + ...args: TArgs + ): NodeJS.Timeout; + // Allow a single void-accepting argument to be optional in arguments lists. + // Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258) + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setTimeout(callback: (_: void) => void, delay?: number): NodeJS.Timeout; + namespace setTimeout { + import __promisify__ = promises.setTimeout; + export { __promisify__ }; + } + /** + * Cancels an `Immediate` object created by `setImmediate()`. + * @since v0.9.1 + * @param immediate An `Immediate` object as returned by `setImmediate()`. + */ + function clearImmediate(immediate: NodeJS.Immediate | undefined): void; + /** + * Cancels a `Timeout` object created by `setInterval()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by `setInterval()` + * or the primitive of the `Timeout` object as a string or a number. + */ + function clearInterval(timeout: NodeJS.Timeout | string | number | undefined): void; + /** + * Cancels a `Timeout` object created by `setTimeout()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by `setTimeout()` + * or the primitive of the `Timeout` object as a string or a number. + */ + function clearTimeout(timeout: NodeJS.Timeout | string | number | undefined): void; + /** + * The `queueMicrotask()` method queues a microtask to invoke `callback`. If + * `callback` throws an exception, the `process` object `'uncaughtException'` + * event will be emitted. + * + * The microtask queue is managed by V8 and may be used in a similar manner to + * the `process.nextTick()` queue, which is managed by Node.js. The + * `process.nextTick()` queue is always processed before the microtask queue + * within each turn of the Node.js event loop. + * @since v11.0.0 + * @param callback Function to be queued. + */ + function queueMicrotask(callback: () => void): void; + } + import clearImmediate = globalThis.clearImmediate; + import clearInterval = globalThis.clearInterval; + import clearTimeout = globalThis.clearTimeout; + import setImmediate = globalThis.setImmediate; + import setInterval = globalThis.setInterval; + import setTimeout = globalThis.setTimeout; + export { clearImmediate, clearInterval, clearTimeout, promises, setImmediate, setInterval, setTimeout }; +} +declare module "node:timers" { + export * from "timers"; +} diff --git a/node_modules/@types/node/timers/promises.d.ts b/node_modules/@types/node/timers/promises.d.ts new file mode 100644 index 0000000..05db90c --- /dev/null +++ b/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,108 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via + * `require('node:timers/promises')`. + * + * ```js + * import { + * setTimeout, + * setImmediate, + * setInterval, + * } from 'node:timers/promises'; + * ``` + * @since v15.0.0 + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/timers/promises.js) + */ +declare module "timers/promises" { + import { TimerOptions } from "node:timers"; + /** + * ```js + * import { + * setTimeout, + * } from 'node:timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param delay The number of milliseconds to wait before fulfilling the + * promise. **Default:** `1`. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from 'node:timers/promises'; + * + * const res = await setImmediate('result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param value A value with which the promise is fulfilled. + */ + function setImmediate(value?: T, options?: TimerOptions): Promise; + /** + * Returns an async iterator that generates values in an interval of `delay` ms. + * If `ref` is `true`, you need to call `next()` of async iterator explicitly + * or implicitly to keep the event loop alive. + * + * ```js + * import { + * setInterval, + * } from 'node:timers/promises'; + * + * const interval = 100; + * for await (const startTime of setInterval(interval, Date.now())) { + * const now = Date.now(); + * console.log(now); + * if ((now - startTime) > 1000) + * break; + * } + * console.log(Date.now()); + * ``` + * @since v15.9.0 + * @param delay The number of milliseconds to wait between iterations. + * **Default:** `1`. + * @param value A value with which the iterator returns. + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): NodeJS.AsyncIterator; + interface Scheduler { + /** + * An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification + * being developed as a standard Web Platform API. + * + * Calling `timersPromises.scheduler.wait(delay, options)` is roughly equivalent + * to calling `timersPromises.setTimeout(delay, undefined, options)` except that + * the `ref` option is not supported. + * + * ```js + * import { scheduler } from 'node:timers/promises'; + * + * await scheduler.wait(1000); // Wait one second before continuing + * ``` + * @since v17.3.0, v16.14.0 + * @experimental + * @param delay The number of milliseconds to wait before resolving the + * promise. + */ + wait(delay: number, options?: { signal?: AbortSignal }): Promise; + /** + * An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification + * being developed as a standard Web Platform API. + * + * Calling `timersPromises.scheduler.yield()` is equivalent to calling + * `timersPromises.setImmediate()` with no arguments. + * @since v17.3.0, v16.14.0 + * @experimental + */ + yield(): Promise; + } + const scheduler: Scheduler; +} +declare module "node:timers/promises" { + export * from "timers/promises"; +} diff --git a/node_modules/@types/node/tls.d.ts b/node_modules/@types/node/tls.d.ts new file mode 100644 index 0000000..5177032 --- /dev/null +++ b/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1319 @@ +/** + * The `node:tls` module provides an implementation of the Transport Layer Security + * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. + * The module can be accessed using: + * + * ```js + * import tls from 'node:tls'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/tls.js) + */ +declare module "tls" { + import { NonSharedBuffer } from "node:buffer"; + import { X509Certificate } from "node:crypto"; + import * as net from "node:net"; + import * as stream from "stream"; + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + interface Certificate extends NodeJS.Dict { + /** + * Country code. + */ + C?: string | string[]; + /** + * Street. + */ + ST?: string | string[]; + /** + * Locality. + */ + L?: string | string[]; + /** + * Organization. + */ + O?: string | string[]; + /** + * Organizational unit. + */ + OU?: string | string[]; + /** + * Common name. + */ + CN?: string | string[]; + } + interface PeerCertificate { + /** + * `true` if a Certificate Authority (CA), `false` otherwise. + * @since v18.13.0 + */ + ca: boolean; + /** + * The DER encoded X.509 certificate data. + */ + raw: NonSharedBuffer; + /** + * The certificate subject. + */ + subject: Certificate; + /** + * The certificate issuer, described in the same terms as the `subject`. + */ + issuer: Certificate; + /** + * The date-time the certificate is valid from. + */ + valid_from: string; + /** + * The date-time the certificate is valid to. + */ + valid_to: string; + /** + * The certificate serial number, as a hex string. + */ + serialNumber: string; + /** + * The SHA-1 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint: string; + /** + * The SHA-256 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint256: string; + /** + * The SHA-512 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint512: string; + /** + * The extended key usage, a set of OIDs. + */ + ext_key_usage?: string[]; + /** + * A string containing concatenated names for the subject, + * an alternative to the `subject` names. + */ + subjectaltname?: string; + /** + * An array describing the AuthorityInfoAccess, used with OCSP. + */ + infoAccess?: NodeJS.Dict; + /** + * For RSA keys: The RSA bit size. + * + * For EC keys: The key size in bits. + */ + bits?: number; + /** + * The RSA exponent, as a string in hexadecimal number notation. + */ + exponent?: string; + /** + * The RSA modulus, as a hexadecimal string. + */ + modulus?: string; + /** + * The public key. + */ + pubkey?: NonSharedBuffer; + /** + * The ASN.1 name of the OID of the elliptic curve. + * Well-known curves are identified by an OID. + * While it is unusual, it is possible that the curve + * is identified by its mathematical properties, + * in which case it will not have an OID. + */ + asn1Curve?: string; + /** + * The NIST name for the elliptic curve, if it has one + * (not all well-known curves have been assigned names by NIST). + */ + nistCurve?: string; + } + interface DetailedPeerCertificate extends PeerCertificate { + /** + * The issuer certificate object. + * For self-signed certificates, this may be a circular reference. + */ + issuerCertificate: DetailedPeerCertificate; + } + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + /** + * IETF name for the cipher suite. + */ + standardName: string; + } + interface EphemeralKeyInfo { + /** + * The supported types are 'DH' and 'ECDH'. + */ + type: string; + /** + * The name property is available only when type is 'ECDH'. + */ + name?: string | undefined; + /** + * The size of parameter of an ephemeral key exchange. + */ + size: number; + } + interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean | undefined; + /** + * An optional net.Server instance. + */ + server?: net.Server | undefined; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer | undefined; + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean | undefined; + } + /** + * Performs transparent encryption of written data and all required TLS + * negotiation. + * + * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. + * + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the + * connection is open. + * @since v0.11.4 + */ + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket | stream.Duplex, options?: TLSSocketOptions); + /** + * This property is `true` if the peer certificate was signed by one of the CAs + * specified when creating the `tls.TLSSocket` instance, otherwise `false`. + * @since v0.11.4 + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This + * property is set only when `tlsSocket.authorized === false`. + * @since v0.11.4 + */ + authorizationError: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. + * @since v0.11.4 + */ + encrypted: true; + /** + * String containing the selected ALPN protocol. + * Before a handshake has completed, this value is always null. + * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol: string | false | null; + /** + * String containing the server name requested via SNI (Server Name Indication) TLS extension. + */ + servername: string | false | null; + /** + * Returns an object representing the local certificate. The returned object has + * some properties corresponding to the fields of the certificate. + * + * See {@link TLSSocket.getPeerCertificate} for an example of the certificate + * structure. + * + * If there is no local certificate, an empty object will be returned. If the + * socket has been destroyed, `null` will be returned. + * @since v11.2.0 + */ + getCertificate(): PeerCertificate | object | null; + /** + * Returns an object containing information on the negotiated cipher suite. + * + * For example, a TLSv1.2 protocol with AES256-SHA cipher: + * + * ```json + * { + * "name": "AES256-SHA", + * "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", + * "version": "SSLv3" + * } + * ``` + * + * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. + * @since v0.11.4 + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the type, name, and size of parameter of + * an ephemeral key exchange in `perfect forward secrecy` on a client + * connection. It returns an empty object when the key exchange is not + * ephemeral. As this is only supported on a client socket; `null` is returned + * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The `name` property is available only when type is `'ECDH'`. + * + * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. + * @since v5.0.0 + */ + getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. + */ + getFinished(): NonSharedBuffer | undefined; + /** + * Returns an object representing the peer's certificate. If the peer does not + * provide a certificate, an empty object will be returned. If the socket has been + * destroyed, `null` will be returned. + * + * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's + * certificate. + * @since v0.11.4 + * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. + * @return A certificate object. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so + * far. + */ + getPeerFinished(): NonSharedBuffer | undefined; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the + * current connection. The value `'unknown'` will be returned for connected + * sockets that have not completed the handshaking process. The value `null` will + * be returned for server sockets or disconnected client sockets. + * + * Protocol versions are: + * + * * `'SSLv3'` + * * `'TLSv1'` + * * `'TLSv1.1'` + * * `'TLSv1.2'` + * * `'TLSv1.3'` + * + * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. + * @since v5.7.0 + */ + getProtocol(): string | null; + /** + * Returns the TLS session data or `undefined` if no session was + * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful + * for debugging. + * + * See `Session Resumption` for more information. + * + * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications + * must use the `'session'` event (it also works for TLSv1.2 and below). + * @since v0.11.4 + */ + getSession(): NonSharedBuffer | undefined; + /** + * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. + * @since v12.11.0 + * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. + */ + getSharedSigalgs(): string[]; + /** + * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. + * + * It may be useful for debugging. + * + * See `Session Resumption` for more information. + * @since v0.11.4 + */ + getTLSTicket(): NonSharedBuffer | undefined; + /** + * See `Session Resumption` for more information. + * @since v0.5.6 + * @return `true` if the session was reused, `false` otherwise. + */ + isSessionReused(): boolean; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * Upon completion, the `callback` function will be passed a single argument + * that is either an `Error` (if the request failed) or `null`. + * + * This method can be used to request a peer's certificate after the secure + * connection has been established. + * + * When running as the server, the socket will be destroyed with an error after `handshakeTimeout` timeout. + * + * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the + * protocol. + * @since v0.11.8 + * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with + * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. + * @return `true` if renegotiation was initiated, `false` otherwise. + */ + renegotiate( + options: { + rejectUnauthorized?: boolean | undefined; + requestCert?: boolean | undefined; + }, + callback: (err: Error | null) => void, + ): undefined | boolean; + /** + * The `tlsSocket.setKeyCert()` method sets the private key and certificate to use for the socket. + * This is mainly useful if you wish to select a server certificate from a TLS server's `ALPNCallback`. + * @since v22.5.0, v20.17.0 + * @param context An object containing at least `key` and `cert` properties from the {@link createSecureContext()} `options`, + * or a TLS context object created with {@link createSecureContext()} itself. + */ + setKeyCert(context: SecureContextOptions | SecureContext): void; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. + * Returns `true` if setting the limit succeeded; `false` otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger + * fragments are buffered by the TLS layer until the entire fragment is received + * and its integrity is verified; large fragments can span multiple roundtrips + * and their processing can be delayed due to packet loss or reordering. However, + * smaller fragments add extra TLS framing bytes and CPU overhead, which may + * decrease overall server throughput. + * @since v0.11.11 + * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + /** + * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts + * to renegotiate will trigger an `'error'` event on the `TLSSocket`. + * @since v8.4.0 + */ + disableRenegotiation(): void; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * + * The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by + * OpenSSL's `SSL_trace()` function, the format is undocumented, can change + * without notice, and should not be relied on. + * @since v12.2.0 + */ + enableTrace(): void; + /** + * Returns the peer certificate as an `X509Certificate` object. + * + * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getPeerX509Certificate(): X509Certificate | undefined; + /** + * Returns the local certificate as an `X509Certificate` object. + * + * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getX509Certificate(): X509Certificate | undefined; + /** + * Keying material is used for validations to prevent different kind of attacks in + * network protocols, for example in the specifications of IEEE 802.1X. + * + * Example + * + * ```js + * const keyingMaterial = tlsSocket.exportKeyingMaterial( + * 128, + * 'client finished'); + * + * /* + * Example return value of keyingMaterial: + * + * + * ``` + * + * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more + * information. + * @since v13.10.0, v12.17.0 + * @param length number of bytes to retrieve from keying material + * @param label an application specific label, typically this will be a value from the [IANA Exporter Label + * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * @param context Optionally provide a context. + * @return requested bytes of the keying material + */ + exportKeyingMaterial(length: number, label: string, context: Buffer): NonSharedBuffer; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + addListener(event: "session", listener: (session: NonSharedBuffer) => void): this; + addListener(event: "keylog", listener: (line: NonSharedBuffer) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: NonSharedBuffer): boolean; + emit(event: "secureConnect"): boolean; + emit(event: "session", session: NonSharedBuffer): boolean; + emit(event: "keylog", line: NonSharedBuffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + on(event: "session", listener: (session: NonSharedBuffer) => void): this; + on(event: "keylog", listener: (line: NonSharedBuffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + once(event: "session", listener: (session: NonSharedBuffer) => void): this; + once(event: "keylog", listener: (line: NonSharedBuffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + prependListener(event: "session", listener: (session: NonSharedBuffer) => void): this; + prependListener(event: "keylog", listener: (line: NonSharedBuffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + prependOnceListener(event: "session", listener: (session: NonSharedBuffer) => void): this; + prependOnceListener(event: "keylog", listener: (line: NonSharedBuffer) => void): this; + } + interface CommonConnectionOptions { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext | undefined; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * @default false + */ + enableTrace?: boolean | undefined; + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean | undefined; + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) + */ + ALPNProtocols?: readonly string[] | NodeJS.ArrayBufferView | undefined; + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. + * @default true + */ + rejectUnauthorized?: boolean | undefined; + } + interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { + /** + * Abort the connection if the SSL/TLS handshake does not finish in the + * specified number of milliseconds. A 'tlsClientError' is emitted on + * the tls.Server object whenever a handshake times out. Default: + * 120000 (120 seconds). + */ + handshakeTimeout?: number | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + */ + ticketKeys?: Buffer | undefined; + /** + * @param socket + * @param identity identity parameter sent from the client. + * @return pre-shared key that must either be + * a buffer or `null` to stop the negotiation process. Returned PSK must be + * compatible with the selected cipher's digest. + * + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with the identity provided by the client. + * If the return value is `null` the negotiation process will stop and an + * "unknown_psk_identity" alert message will be sent to the other party. + * If the server wishes to hide the fact that the PSK identity was not known, + * the callback must provide some random data as `psk` to make the connection + * fail with "decrypt_error" before negotiation is finished. + * PSK ciphers are disabled by default, and using TLS-PSK thus + * requires explicitly specifying a cipher suite with the `ciphers` option. + * More information can be found in the RFC 4279. + */ + pskCallback?: ((socket: TLSSocket, identity: string) => NodeJS.ArrayBufferView | null) | undefined; + /** + * hint to send to a client to help + * with selecting the identity during TLS-PSK negotiation. Will be ignored + * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be + * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. + */ + pskIdentityHint?: string | undefined; + } + interface PSKCallbackNegotation { + psk: NodeJS.ArrayBufferView; + identity: string; + } + interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { + host?: string | undefined; + port?: number | undefined; + path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket + checkServerIdentity?: typeof checkServerIdentity | undefined; + servername?: string | undefined; // SNI TLS Extension + session?: Buffer | undefined; + minDHSize?: number | undefined; + lookup?: net.LookupFunction | undefined; + timeout?: number | undefined; + /** + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with optional identity `hint` provided by the server or `null` + * in case of TLS 1.3 where `hint` was removed. + * It will be necessary to provide a custom `tls.checkServerIdentity()` + * for the connection as the default one will try to check hostname/IP + * of the server against the certificate but that's not applicable for PSK + * because there won't be a certificate present. + * More information can be found in the RFC 4279. + * + * @param hint message sent from the server to help client + * decide which identity to use during negotiation. + * Always `null` if TLS 1.3 is used. + * @returns Return `null` to stop the negotiation process. `psk` must be + * compatible with the selected cipher's digest. + * `identity` must use UTF-8 encoding. + */ + pskCallback?: ((hint: string | null) => PSKCallbackNegotation | null) | undefined; + } + /** + * Accepts encrypted connections using TLS or SSL. + * @since v0.3.2 + */ + class Server extends net.Server { + constructor(secureConnectionListener?: (socket: TLSSocket) => void); + constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); + /** + * The `server.addContext()` method adds a secure context that will be used if + * the client request's SNI name matches the supplied `hostname` (or wildcard). + * + * When there are multiple matching contexts, the most recently added one is + * used. + * @since v0.5.3 + * @param hostname A SNI host name or wildcard (e.g. `'*'`) + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc), or a TLS context object created + * with {@link createSecureContext} itself. + */ + addContext(hostname: string, context: SecureContextOptions | SecureContext): void; + /** + * Returns the session ticket keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @return A 48-byte buffer containing the session ticket keys. + */ + getTicketKeys(): NonSharedBuffer; + /** + * The `server.setSecureContext()` method replaces the secure context of an + * existing server. Existing connections to the server are not interrupted. + * @since v11.0.0 + * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + setSecureContext(options: SecureContextOptions): void; + /** + * Sets the session ticket keys. + * + * Changes to the ticket keys are effective only for future server connections. + * Existing or currently pending server connections will use the previous keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @param keys A 48-byte buffer containing the session ticket keys. + */ + setTicketKeys(keys: Buffer): void; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + * 6. keylog + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + addListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit( + event: "newSession", + sessionId: NonSharedBuffer, + sessionData: NonSharedBuffer, + callback: () => void, + ): boolean; + emit( + event: "OCSPRequest", + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ): boolean; + emit( + event: "resumeSession", + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + emit(event: "keylog", line: NonSharedBuffer, tlsSocket: TLSSocket): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + on( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + on(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + once(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this; + } + /** + * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. + */ + interface SecurePair { + encrypted: TLSSocket; + cleartext: TLSSocket; + } + type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1"; + interface SecureContextOptions { + /** + * If set, this will be called when a client opens a connection using the ALPN extension. + * One argument will be passed to the callback: an object containing `servername` and `protocols` fields, + * respectively containing the server name from the SNI extension (if any) and an array of + * ALPN protocol name strings. The callback must return either one of the strings listed in `protocols`, + * which will be returned to the client as the selected ALPN protocol, or `undefined`, + * to reject the connection with a fatal alert. If a string is returned that does not match one of + * the client's ALPN protocols, an error will be thrown. + * This option cannot be used with the `ALPNProtocols` option, and setting both options will throw an error. + */ + ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined; + /** + * Treat intermediate (non-self-signed) + * certificates in the trust CA certificate list as trusted. + * @since v22.9.0, v20.18.0 + */ + allowPartialTrustChain?: boolean | undefined; + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Colon-separated list of supported signature algorithms. The list + * can contain digest algorithms (SHA256, MD5 etc.), public key + * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g + * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). + */ + sigalgs?: string | undefined; + /** + * Cipher suite specification, replacing the default. For more + * information, see modifying the default cipher suite. Permitted + * ciphers can be obtained via tls.getCiphers(). Cipher names must be + * uppercased in order for OpenSSL to accept them. + */ + ciphers?: string | undefined; + /** + * Name of an OpenSSL engine which can provide the client certificate. + * @deprecated + */ + clientCertEngine?: string | undefined; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: string | Buffer | Array | undefined; + /** + * `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. + * If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. + * ECDHE-based perfect forward secrecy will still be available. + */ + dhparam?: string | Buffer | undefined; + /** + * A string describing a named curve or a colon separated list of curve + * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key + * agreement. Set to auto to select the curve automatically. Use + * crypto.getCurves() to obtain a list of available curve names. On + * recent releases, openssl ecparam -list_curves will also display the + * name and description of each available elliptic curve. Default: + * tls.DEFAULT_ECDH_CURVE. + */ + ecdhCurve?: string | undefined; + /** + * Attempt to use the server's cipher suite preferences instead of the + * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be + * set in secureOptions + */ + honorCipherOrder?: boolean | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Name of an OpenSSL engine to get private key from. Should be used + * together with privateKeyIdentifier. + * @deprecated + */ + privateKeyEngine?: string | undefined; + /** + * Identifier of a private key managed by an OpenSSL engine. Should be + * used together with privateKeyEngine. Should not be set together with + * key, because both options define a private key in different ways. + * @deprecated + */ + privateKeyIdentifier?: string | undefined; + /** + * Optionally set the maximum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. + * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using + * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to + * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. + */ + maxVersion?: SecureVersion | undefined; + /** + * Optionally set the minimum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to + * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. + */ + minVersion?: SecureVersion | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form {buf: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted PFX will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; + /** + * Optionally affect the OpenSSL protocol behavior, which is not + * usually necessary. This should be used carefully if at all! Value is + * a numeric bitmask of the SSL_OP_* options from OpenSSL Options + */ + secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options + /** + * Legacy mechanism to select the TLS protocol version to use, it does + * not support independent control of the minimum and maximum version, + * and does not support limiting the protocol to TLSv1.3. Use + * minVersion and maxVersion instead. The possible values are listed as + * SSL_METHODS, use the function names as strings. For example, use + * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow + * any TLS protocol version up to TLSv1.3. It is not recommended to use + * TLS versions less than 1.2, but it may be required for + * interoperability. Default: none, see minVersion. + */ + secureProtocol?: string | undefined; + /** + * Opaque identifier used by servers to ensure session state is not + * shared between applications. Unused by clients. + */ + sessionIdContext?: string | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + * See Session Resumption for more information. + */ + ticketKeys?: Buffer | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + } + interface SecureContext { + context: any; + } + /** + * Verifies the certificate `cert` is issued to `hostname`. + * + * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on + * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). + * + * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as + * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead. + * + * This function can be overwritten by providing an alternative function as the `options.checkServerIdentity` option that is passed to `tls.connect()`. The + * overwriting function can call `tls.checkServerIdentity()` of course, to augment + * the checks done with additional verification. + * + * This function is only called if the certificate passed all other checks, such as + * being issued by trusted CA (`options.ca`). + * + * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name + * was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use + * a custom `options.checkServerIdentity` function that implements the desired behavior. + * @since v0.8.4 + * @param hostname The host name or IP address to verify the certificate against. + * @param cert A `certificate object` representing the peer's certificate. + */ + function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; + /** + * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is + * automatically set as a listener for the `'secureConnection'` event. + * + * The `ticketKeys` options is automatically shared between `node:cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * import tls from 'node:tls'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * + * // This is necessary only if using client certificate authentication. + * requestCert: true, + * + * // This is necessary only if the client uses a self-signed certificate. + * ca: [ fs.readFileSync('client-cert.pem') ], + * }; + * + * const server = tls.createServer(options, (socket) => { + * console.log('server connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * socket.write('welcome!\n'); + * socket.setEncoding('utf8'); + * socket.pipe(socket); + * }); + * server.listen(8000, () => { + * console.log('server bound'); + * }); + * ``` + * + * The server can be tested by connecting to it using the example client from {@link connect}. + * @since v0.3.2 + */ + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. + * + * `tls.connect()` returns a {@link TLSSocket} object. + * + * Unlike the `https` API, `tls.connect()` does not enable the + * SNI (Server Name Indication) extension by default, which may cause some + * servers to return an incorrect certificate or reject the connection + * altogether. To enable SNI, set the `servername` option in addition + * to `host`. + * + * The following illustrates a client for the echo server example from {@link createServer}: + * + * ```js + * // Assumes an echo server that is listening on port 8000. + * import tls from 'node:tls'; + * import fs from 'node:fs'; + * + * const options = { + * // Necessary only if the server requires client certificate authentication. + * key: fs.readFileSync('client-key.pem'), + * cert: fs.readFileSync('client-cert.pem'), + * + * // Necessary only if the server uses a self-signed certificate. + * ca: [ fs.readFileSync('server-cert.pem') ], + * + * // Necessary only if the server's cert isn't for "localhost". + * checkServerIdentity: () => { return null; }, + * }; + * + * const socket = tls.connect(8000, options, () => { + * console.log('client connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * process.stdin.pipe(socket); + * process.stdin.resume(); + * }); + * socket.setEncoding('utf8'); + * socket.on('data', (data) => { + * console.log(data); + * }); + * socket.on('end', () => { + * console.log('server ends connection'); + * }); + * ``` + * @since v0.11.3 + */ + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect( + port: number, + host?: string, + options?: ConnectionOptions, + secureConnectListener?: () => void, + ): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * Creates a new secure pair object with two streams, one of which reads and writes + * the encrypted data and the other of which reads and writes the cleartext data. + * Generally, the encrypted stream is piped to/from an incoming encrypted data + * stream and the cleartext one is used as a replacement for the initial encrypted + * stream. + * + * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and `encrypted` stream properties. + * + * Using `cleartext` has the same API as {@link TLSSocket}. + * + * The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code: + * + * ```js + * pair = tls.createSecurePair(// ... ); + * pair.encrypted.pipe(socket); + * socket.pipe(pair.encrypted); + * ``` + * + * can be replaced by: + * + * ```js + * secureSocket = tls.TLSSocket(socket, options); + * ``` + * + * where `secureSocket` has the same API as `pair.cleartext`. + * @since v0.3.2 + * @deprecated Since v0.11.3 - Use {@link TLSSocket} instead. + * @param context A secure context object as returned by `tls.createSecureContext()` + * @param isServer `true` to specify that this TLS connection should be opened as a server. + * @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`. + * @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`. + */ + function createSecurePair( + context?: SecureContext, + isServer?: boolean, + requestCert?: boolean, + rejectUnauthorized?: boolean, + ): SecurePair; + /** + * `{@link createServer}` sets the default value of the `honorCipherOrder` option + * to `true`, other APIs that create secure contexts leave it unset. + * + * `{@link createServer}` uses a 128 bit truncated SHA1 hash value generated + * from `process.argv` as the default value of the `sessionIdContext` option, other + * APIs that create secure contexts have no default value. + * + * The `tls.createSecureContext()` method creates a `SecureContext` object. It is + * usable as an argument to several `tls` APIs, such as `server.addContext()`, + * but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option. + * + * A key is _required_ for ciphers that use certificates. Either `key` or `pfx` can be used to provide it. + * + * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of + * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * + * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto' `option. When set to `'auto'`, well-known DHE parameters of sufficient strength + * will be selected automatically. Otherwise, if necessary, `openssl dhparam` can + * be used to create custom parameters. The key length must be greater than or + * equal to 1024 bits or else an error will be thrown. Although 1024 bits is + * permissible, use 2048 bits or larger for stronger security. + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * Returns an array containing the CA certificates from various sources, depending on `type`: + * + * * `"default"`: return the CA certificates that will be used by the Node.js TLS clients by default. + * * When `--use-bundled-ca` is enabled (default), or `--use-openssl-ca` is not enabled, + * this would include CA certificates from the bundled Mozilla CA store. + * * When `--use-system-ca` is enabled, this would also include certificates from the system's + * trusted store. + * * When `NODE_EXTRA_CA_CERTS` is used, this would also include certificates loaded from the specified + * file. + * * `"system"`: return the CA certificates that are loaded from the system's trusted store, according + * to rules set by `--use-system-ca`. This can be used to get the certificates from the system + * when `--use-system-ca` is not enabled. + * * `"bundled"`: return the CA certificates from the bundled Mozilla CA store. This would be the same + * as `tls.rootCertificates`. + * * `"extra"`: return the CA certificates loaded from `NODE_EXTRA_CA_CERTS`. It's an empty array if + * `NODE_EXTRA_CA_CERTS` is not set. + * @since v22.15.0 + * @param type The type of CA certificates that will be returned. Valid values + * are `"default"`, `"system"`, `"bundled"` and `"extra"`. + * **Default:** `"default"`. + * @returns An array of PEM-encoded certificates. The array may contain duplicates + * if the same certificate is repeatedly stored in multiple sources. + */ + function getCACertificates(type?: "default" | "system" | "bundled" | "extra"): string[]; + /** + * Returns an array with the names of the supported TLS ciphers. The names are + * lower-case for historical reasons, but must be uppercased to be used in + * the `ciphers` option of `{@link createSecureContext}`. + * + * Not all supported ciphers are enabled by default. See + * [Modifying the default TLS cipher suite](https://nodejs.org/docs/latest-v22.x/api/tls.html#modifying-the-default-tls-cipher-suite). + * + * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for + * TLSv1.2 and below. + * + * ```js + * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] + * ``` + * @since v0.10.2 + */ + function getCiphers(): string[]; + /** + * Sets the default CA certificates used by Node.js TLS clients. If the provided + * certificates are parsed successfully, they will become the default CA + * certificate list returned by {@link getCACertificates} and used + * by subsequent TLS connections that don't specify their own CA certificates. + * The certificates will be deduplicated before being set as the default. + * + * This function only affects the current Node.js thread. Previous + * sessions cached by the HTTPS agent won't be affected by this change, so + * this method should be called before any unwanted cachable TLS connections are + * made. + * + * To use system CA certificates as the default: + * + * ```js + * import tls from 'node:tls'; + * tls.setDefaultCACertificates(tls.getCACertificates('system')); + * ``` + * + * This function completely replaces the default CA certificate list. To add additional + * certificates to the existing defaults, get the current certificates and append to them: + * + * ```js + * import tls from 'node:tls'; + * const currentCerts = tls.getCACertificates('default'); + * const additionalCerts = ['-----BEGIN CERTIFICATE-----\n...']; + * tls.setDefaultCACertificates([...currentCerts, ...additionalCerts]); + * ``` + * @since v22.19.0 + * @param certs An array of CA certificates in PEM format. + */ + function setDefaultCACertificates(certs: ReadonlyArray): void; + /** + * The default curve name to use for ECDH key agreement in a tls server. + * The default value is `'auto'`. See `{@link createSecureContext()}` for further + * information. + * @since v0.11.13 + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the `maxVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.3'`, unless + * changed using CLI options. Using `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using + * `--tls-max-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the highest maximum is used. + * @since v11.4.0 + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the `minVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.2'`, unless + * changed using CLI options. Using `--tls-min-v1.0` sets the default to + * `'TLSv1'`. Using `--tls-min-v1.1` sets the default to `'TLSv1.1'`. Using + * `--tls-min-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the lowest minimum is used. + * @since v11.4.0 + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * The default value of the `ciphers` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported OpenSSL ciphers. + * Defaults to the content of `crypto.constants.defaultCoreCipherList`, unless + * changed using CLI options using `--tls-default-ciphers`. + * @since v19.8.0 + */ + let DEFAULT_CIPHERS: string; + /** + * An immutable array of strings representing the root certificates (in PEM format) + * from the bundled Mozilla CA store as supplied by the current Node.js version. + * + * The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store + * that is fixed at release time. It is identical on all supported platforms. + * @since v12.3.0 + */ + const rootCertificates: readonly string[]; +} +declare module "node:tls" { + export * from "tls"; +} diff --git a/node_modules/@types/node/trace_events.d.ts b/node_modules/@types/node/trace_events.d.ts new file mode 100644 index 0000000..f334b0b --- /dev/null +++ b/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,197 @@ +/** + * The `node:trace_events` module provides a mechanism to centralize tracing information + * generated by V8, Node.js core, and userspace code. + * + * Tracing can be enabled with the `--trace-event-categories` command-line flag + * or by using the `trace_events` module. The `--trace-event-categories` flag + * accepts a list of comma-separated category names. + * + * The available categories are: + * + * * `node`: An empty placeholder. + * * `node.async_hooks`: Enables capture of detailed [`async_hooks`](https://nodejs.org/docs/latest-v22.x/api/async_hooks.html) trace data. + * The [`async_hooks`](https://nodejs.org/docs/latest-v22.x/api/async_hooks.html) events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. + * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. + * * `node.console`: Enables capture of `console.time()` and `console.count()` output. + * * `node.threadpoolwork.sync`: Enables capture of trace data for threadpool synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.threadpoolwork.async`: Enables capture of trace data for threadpool asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.dns.native`: Enables capture of trace data for DNS queries. + * * `node.net.native`: Enables capture of trace data for network. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.fs_dir.sync`: Enables capture of trace data for file system sync directory methods. + * * `node.fs.async`: Enables capture of trace data for file system async methods. + * * `node.fs_dir.async`: Enables capture of trace data for file system async directory methods. + * * `node.perf`: Enables capture of [Performance API](https://nodejs.org/docs/latest-v22.x/api/perf_hooks.html) measurements. + * * `node.perf.usertiming`: Enables capture of only Performance API User Timing + * measures and marks. + * * `node.perf.timerify`: Enables capture of only Performance API timerify + * measurements. + * * `node.promises.rejections`: Enables capture of trace data tracking the number + * of unhandled Promise rejections and handled-after-rejections. + * * `node.vm.script`: Enables capture of trace data for the `node:vm` module's `runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The [V8](https://nodejs.org/docs/latest-v22.x/api/v8.html) events are GC, compiling, and execution related. + * * `node.http`: Enables capture of trace data for http request / response. + * + * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. + * + * ```bash + * node --trace-event-categories v8,node,node.async_hooks server.js + * ``` + * + * Prior versions of Node.js required the use of the `--trace-events-enabled` flag to enable trace events. This requirement has been removed. However, the `--trace-events-enabled` flag _may_ still be + * used and will enable the `node`, `node.async_hooks`, and `v8` trace event categories by default. + * + * ```bash + * node --trace-events-enabled + * + * # is equivalent to + * + * node --trace-event-categories v8,node,node.async_hooks + * ``` + * + * Alternatively, trace events may be enabled using the `node:trace_events` module: + * + * ```js + * import trace_events from 'node:trace_events'; + * const tracing = trace_events.createTracing({ categories: ['node.perf'] }); + * tracing.enable(); // Enable trace event capture for the 'node.perf' category + * + * // do work + * + * tracing.disable(); // Disable trace event capture for the 'node.perf' category + * ``` + * + * Running Node.js with tracing enabled will produce log files that can be opened + * in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome. + * + * The logging file is by default called `node_trace.${rotation}.log`, where `${rotation}` is an incrementing log-rotation id. The filepath pattern can + * be specified with `--trace-event-file-pattern` that accepts a template + * string that supports `${rotation}` and `${pid}`: + * + * ```bash + * node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js + * ``` + * + * To guarantee that the log file is properly generated after signal events like `SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers + * in your code, such as: + * + * ```js + * process.on('SIGINT', function onSigint() { + * console.info('Received SIGINT.'); + * process.exit(130); // Or applicable exit code depending on OS and signal + * }); + * ``` + * + * The tracing system uses the same time source + * as the one used by `process.hrtime()`. + * However the trace-event timestamps are expressed in microseconds, + * unlike `process.hrtime()` which returns nanoseconds. + * + * The features from this module are not available in [`Worker`](https://nodejs.org/docs/latest-v22.x/api/worker_threads.html#class-worker) threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/trace_events.js) + */ +declare module "trace_events" { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + * @since v10.0.0 + */ + readonly categories: string; + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + * + * ```js + * import trace_events from 'node:trace_events'; + * const t1 = trace_events.createTracing({ categories: ['node', 'v8'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] }); + * t1.enable(); + * t2.enable(); + * + * // Prints 'node,node.perf,v8' + * console.log(trace_events.getEnabledCategories()); + * + * t2.disable(); // Will only disable emission of the 'node.perf' category + * + * // Prints 'node,v8' + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + * @since v10.0.0 + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + * @since v10.0.0 + */ + readonly enabled: boolean; + } + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + /** + * Creates and returns a `Tracing` object for the given set of `categories`. + * + * ```js + * import trace_events from 'node:trace_events'; + * const categories = ['node.perf', 'node.async_hooks']; + * const tracing = trace_events.createTracing({ categories }); + * tracing.enable(); + * // do stuff + * tracing.disable(); + * ``` + * @since v10.0.0 + */ + function createTracing(options: CreateTracingOptions): Tracing; + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is determined + * by the _union_ of all currently-enabled `Tracing` objects and any categories + * enabled using the `--trace-event-categories` flag. + * + * Given the file `test.js` below, the command `node --trace-event-categories node.perf test.js` will print `'node.async_hooks,node.perf'` to the console. + * + * ```js + * import trace_events from 'node:trace_events'; + * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); + * const t3 = trace_events.createTracing({ categories: ['v8'] }); + * + * t1.enable(); + * t2.enable(); + * + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + function getEnabledCategories(): string | undefined; +} +declare module "node:trace_events" { + export * from "trace_events"; +} diff --git a/node_modules/@types/node/ts5.6/buffer.buffer.d.ts b/node_modules/@types/node/ts5.6/buffer.buffer.d.ts new file mode 100644 index 0000000..a5f67d7 --- /dev/null +++ b/node_modules/@types/node/ts5.6/buffer.buffer.d.ts @@ -0,0 +1,468 @@ +declare module "buffer" { + global { + interface BufferConstructor { + // see ../buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: ArrayLike): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: ArrayBufferLike): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * If `array` is an `Array`-like object (that is, one with a `length` property of + * type `number`), it is treated as if it is an array, unless it is a `Buffer` or + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an + * `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use + * `Buffer.copyBytesFrom()`. + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal + * `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from(array: WithImplicitCoercion>): Buffer; + /** + * This creates a view of the `ArrayBuffer` without copying the underlying + * memory. For example, when passed a reference to the `.buffer` property of a + * `TypedArray` instance, the newly created `Buffer` will share the same + * allocated memory as the `TypedArray`'s underlying `ArrayBuffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arr = new Uint16Array(2); + * + * arr[0] = 5000; + * arr[1] = 4000; + * + * // Shares memory with `arr`. + * const buf = Buffer.from(arr.buffer); + * + * console.log(buf); + * // Prints: + * + * // Changing the original Uint16Array changes the Buffer also. + * arr[1] = 6000; + * + * console.log(buf); + * // Prints: + * ``` + * + * The optional `byteOffset` and `length` arguments specify a memory range within + * the `arrayBuffer` that will be shared by the `Buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const ab = new ArrayBuffer(10); + * const buf = Buffer.from(ab, 0, 2); + * + * console.log(buf.length); + * // Prints: 2 + * ``` + * + * A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer` or a + * `SharedArrayBuffer` or another type appropriate for `Buffer.from()` + * variants. + * + * It is important to remember that a backing `ArrayBuffer` can cover a range + * of memory that extends beyond the bounds of a `TypedArray` view. A new + * `Buffer` created using the `buffer` property of a `TypedArray` may extend + * beyond the range of the `TypedArray`: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements + * const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements + * console.log(arrA.buffer === arrB.buffer); // true + * + * const buf = Buffer.from(arrB.buffer); + * console.log(buf); + * // Prints: + * ``` + * @since v5.10.0 + * @param arrayBuffer An `ArrayBuffer`, `SharedArrayBuffer`, for example the + * `.buffer` property of a `TypedArray`. + * @param byteOffset Index of first byte to expose. **Default:** `0`. + * @param length Number of bytes to expose. **Default:** + * `arrayBuffer.byteLength - byteOffset`. + */ + from( + arrayBuffer: WithImplicitCoercion, + byteOffset?: number, + length?: number, + ): Buffer; + /** + * Creates a new `Buffer` containing `string`. The `encoding` parameter identifies + * the character encoding to be used when converting `string` into bytes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('this is a tést'); + * const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); + * + * console.log(buf1.toString()); + * // Prints: this is a tést + * console.log(buf2.toString()); + * // Prints: this is a tést + * console.log(buf1.toString('latin1')); + * // Prints: this is a tést + * ``` + * + * A `TypeError` will be thrown if `string` is not a string or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(string)` may also use the internal `Buffer` pool like + * `Buffer.allocUnsafe()` does. + * @since v5.10.0 + * @param string A string to encode. + * @param encoding The encoding of `string`. **Default:** `'utf8'`. + */ + from(string: WithImplicitCoercion, encoding?: BufferEncoding): Buffer; + from(arrayOrString: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: readonly Uint8Array[], totalLength?: number): Buffer; + /** + * Copies the underlying memory of `view` into a new `Buffer`. + * + * ```js + * const u16 = new Uint16Array([0, 0xffff]); + * const buf = Buffer.copyBytesFrom(u16, 1, 1); + * u16[1] = 0; + * console.log(buf.length); // 2 + * console.log(buf[0]); // 255 + * console.log(buf[1]); // 255 + * ``` + * @since v19.8.0 + * @param view The {TypedArray} to copy. + * @param [offset=0] The starting offset within `view`. + * @param [length=view.length - offset] The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if + * `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + } + interface Buffer extends Uint8Array { + // see ../buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + } + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedBuffer = Buffer; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type AllowSharedBuffer = Buffer; + } + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + var SlowBuffer: { + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + new(size: number): Buffer; + prototype: Buffer; + }; +} diff --git a/node_modules/@types/node/ts5.6/globals.typedarray.d.ts b/node_modules/@types/node/ts5.6/globals.typedarray.d.ts new file mode 100644 index 0000000..f1c444d --- /dev/null +++ b/node_modules/@types/node/ts5.6/globals.typedarray.d.ts @@ -0,0 +1,34 @@ +export {}; // Make this a module + +declare global { + namespace NodeJS { + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float32Array + | Float64Array; + type ArrayBufferView = TypedArray | DataView; + + type NonSharedUint8Array = Uint8Array; + type NonSharedUint8ClampedArray = Uint8ClampedArray; + type NonSharedUint16Array = Uint16Array; + type NonSharedUint32Array = Uint32Array; + type NonSharedInt8Array = Int8Array; + type NonSharedInt16Array = Int16Array; + type NonSharedInt32Array = Int32Array; + type NonSharedBigUint64Array = BigUint64Array; + type NonSharedBigInt64Array = BigInt64Array; + type NonSharedFloat32Array = Float32Array; + type NonSharedFloat64Array = Float64Array; + type NonSharedDataView = DataView; + type NonSharedTypedArray = TypedArray; + type NonSharedArrayBufferView = ArrayBufferView; + } +} diff --git a/node_modules/@types/node/ts5.6/index.d.ts b/node_modules/@types/node/ts5.6/index.d.ts new file mode 100644 index 0000000..5a5af42 --- /dev/null +++ b/node_modules/@types/node/ts5.6/index.d.ts @@ -0,0 +1,97 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +// NOTE: These definitions support Node.js and TypeScript 4.9 through 5.6. + +// Reference required TypeScript libs: +/// + +// TypeScript backwards-compatibility definitions: +/// + +// Definitions specific to TypeScript 4.9 through 5.6: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/node_modules/@types/node/tty.d.ts b/node_modules/@types/node/tty.d.ts new file mode 100644 index 0000000..f567946 --- /dev/null +++ b/node_modules/@types/node/tty.d.ts @@ -0,0 +1,208 @@ +/** + * The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. In most cases, it will not be necessary or possible to use this module + * directly. However, it can be accessed using: + * + * ```js + * import tty from 'node:tty'; + * ``` + * + * When Node.js detects that it is being run with a text terminal ("TTY") + * attached, `process.stdin` will, by default, be initialized as an instance of `tty.ReadStream` and both `process.stdout` and `process.stderr` will, by + * default, be instances of `tty.WriteStream`. The preferred method of determining + * whether Node.js is being run within a TTY context is to check that the value of + * the `process.stdout.isTTY` property is `true`: + * + * ```console + * $ node -p -e "Boolean(process.stdout.isTTY)" + * true + * $ node -p -e "Boolean(process.stdout.isTTY)" | cat + * false + * ``` + * + * In most cases, there should be little to no reason for an application to + * manually create instances of the `tty.ReadStream` and `tty.WriteStream` classes. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/tty.js) + */ +declare module "tty" { + import * as net from "node:net"; + /** + * The `tty.isatty()` method returns `true` if the given `fd` is associated with + * a TTY and `false` if it is not, including whenever `fd` is not a non-negative + * integer. + * @since v0.5.8 + * @param fd A numeric file descriptor + */ + function isatty(fd: number): boolean; + /** + * Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js + * process and there should be no reason to create additional instances. + * @since v0.5.8 + */ + class ReadStream extends net.Socket { + constructor(fd: number, options?: net.SocketConstructorOpts); + /** + * A `boolean` that is `true` if the TTY is currently configured to operate as a + * raw device. + * + * This flag is always `false` when a process starts, even if the terminal is + * operating in raw mode. Its value will change with subsequent calls to `setRawMode`. + * @since v0.7.7 + */ + isRaw: boolean; + /** + * Allows configuration of `tty.ReadStream` so that it operates as a raw device. + * + * When in raw mode, input is always available character-by-character, not + * including modifiers. Additionally, all special processing of characters by the + * terminal is disabled, including echoing input + * characters. Ctrl+C will no longer cause a `SIGINT` when + * in this mode. + * @since v0.7.7 + * @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` + * property will be set to the resulting mode. + * @return The read stream instance. + */ + setRawMode(mode: boolean): this; + /** + * A `boolean` that is always `true` for `tty.ReadStream` instances. + * @since v0.5.8 + */ + isTTY: boolean; + } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; + /** + * Represents the writable side of a TTY. In normal circumstances, `process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there + * should be no reason to create additional instances. + * @since v0.5.8 + */ + class WriteStream extends net.Socket { + constructor(fd: number); + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "resize", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "resize"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "resize", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "resize", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "resize", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "resize", listener: () => void): this; + /** + * `writeStream.clearLine()` clears the current line of this `WriteStream` in a + * direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearLine(dir: Direction, callback?: () => void): boolean; + /** + * `writeStream.clearScreenDown()` clears this `WriteStream` from the current + * cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearScreenDown(callback?: () => void): boolean; + /** + * `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified + * position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + cursorTo(x: number, y?: number, callback?: () => void): boolean; + cursorTo(x: number, callback: () => void): boolean; + /** + * `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its + * current position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + moveCursor(dx: number, dy: number, callback?: () => void): boolean; + /** + * Returns: + * + * * `1` for 2, + * * `4` for 16, + * * `8` for 256, + * * `24` for 16,777,216 colors supported. + * + * Use this to determine what colors the terminal supports. Due to the nature of + * colors in terminals it is possible to either have false positives or false + * negatives. It depends on process information and the environment variables that + * may lie about what terminal is used. + * It is possible to pass in an `env` object to simulate the usage of a specific + * terminal. This can be useful to check how specific environment settings behave. + * + * To enforce a specific color support, use one of the below environment settings. + * + * * 2 colors: `FORCE_COLOR = 0` (Disables colors) + * * 16 colors: `FORCE_COLOR = 1` + * * 256 colors: `FORCE_COLOR = 2` + * * 16,777,216 colors: `FORCE_COLOR = 3` + * + * Disabling color support is also possible by using the `NO_COLOR` and `NODE_DISABLE_COLORS` environment variables. + * @since v9.9.0 + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + getColorDepth(env?: object): number; + /** + * Returns `true` if the `writeStream` supports at least as many colors as provided + * in `count`. Minimum support is 2 (black and white). + * + * This has the same false positives and negatives as described in `writeStream.getColorDepth()`. + * + * ```js + * process.stdout.hasColors(); + * // Returns true or false depending on if `stdout` supports at least 16 colors. + * process.stdout.hasColors(256); + * // Returns true or false depending on if `stdout` supports at least 256 colors. + * process.stdout.hasColors({ TMUX: '1' }); + * // Returns true. + * process.stdout.hasColors(2 ** 24, { TMUX: '1' }); + * // Returns false (the environment setting pretends to support 2 ** 8 colors). + * ``` + * @since v11.13.0, v10.16.0 + * @param [count=16] The number of colors that are requested (minimum 2). + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + hasColors(count?: number): boolean; + hasColors(env?: object): boolean; + hasColors(count: number, env?: object): boolean; + /** + * `writeStream.getWindowSize()` returns the size of the TTY + * corresponding to this `WriteStream`. The array is of the type `[numColumns, numRows]` where `numColumns` and `numRows` represent the number + * of columns and rows in the corresponding TTY. + * @since v0.7.7 + */ + getWindowSize(): [number, number]; + /** + * A `number` specifying the number of columns the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + columns: number; + /** + * A `number` specifying the number of rows the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + rows: number; + /** + * A `boolean` that is always `true`. + * @since v0.5.8 + */ + isTTY: boolean; + } +} +declare module "node:tty" { + export * from "tty"; +} diff --git a/node_modules/@types/node/url.d.ts b/node_modules/@types/node/url.d.ts new file mode 100644 index 0000000..6a0effc --- /dev/null +++ b/node_modules/@types/node/url.d.ts @@ -0,0 +1,984 @@ +/** + * The `node:url` module provides utilities for URL resolution and parsing. It can + * be accessed using: + * + * ```js + * import url from 'node:url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/url.js) + */ +declare module "url" { + import { Blob as NodeBlob, NonSharedBuffer } from "node:buffer"; + import { ClientRequestArgs } from "node:http"; + import { ParsedUrlQuery, ParsedUrlQueryInput } from "node:querystring"; + // Input to `url.format` + interface UrlObject { + auth?: string | null | undefined; + hash?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + href?: string | null | undefined; + pathname?: string | null | undefined; + protocol?: string | null | undefined; + search?: string | null | undefined; + slashes?: boolean | null | undefined; + port?: string | number | null | undefined; + query?: string | null | ParsedUrlQueryInput | undefined; + } + // Output of `url.parse` + interface Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; + } + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + interface UrlWithStringQuery extends Url { + query: string | null; + } + interface FileUrlToPathOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + * @since v22.1.0 + */ + windows?: boolean | undefined; + } + interface PathToFileUrlOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + * @since v22.1.0 + */ + windows?: boolean | undefined; + } + /** + * The `url.parse()` method takes a URL string, parses it, and returns a URL + * object. + * + * A `TypeError` is thrown if `urlString` is not a string. + * + * A `URIError` is thrown if the `auth` property is present but cannot be decoded. + * + * `url.parse()` uses a lenient, non-standard algorithm for parsing URL + * strings. It is prone to security issues such as [host name spoofing](https://hackerone.com/reports/678487) and incorrect handling of usernames and passwords. Do not use with untrusted + * input. CVEs are not issued for `url.parse()` vulnerabilities. Use the `WHATWG URL` API instead. + * @since v0.1.25 + * @deprecated Use the WHATWG URL API instead. + * @param urlString The URL string to parse. + * @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property + * on the returned URL object will be an unparsed, undecoded string. + * @param [slashesDenoteHost=false] If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the + * result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + */ + function parse(urlString: string): UrlWithStringQuery; + function parse( + urlString: string, + parseQueryString: false | undefined, + slashesDenoteHost?: boolean, + ): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * import url from 'node:url'; + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: URL, options?: URLFormatOptions): string; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * import url from 'node:url'; + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: UrlObject | string): string; + /** + * The `url.resolve()` method resolves a target URL relative to a base URL in a + * manner similar to that of a web browser resolving an anchor tag. + * + * ```js + * import url from 'node:url'; + * url.resolve('/one/two/three', 'four'); // '/one/two/four' + * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' + * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * + * To achieve the same result using the WHATWG URL API: + * + * ```js + * function resolve(from, to) { + * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); + * if (resolvedUrl.protocol === 'resolve:') { + * // `from` is a relative URL. + * const { pathname, search, hash } = resolvedUrl; + * return pathname + search + hash; + * } + * return resolvedUrl.toString(); + * } + * + * resolve('/one/two/three', 'four'); // '/one/two/four' + * resolve('http://example.com/', '/one'); // 'http://example.com/one' + * resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param from The base URL to use if `to` is a relative URL. + * @param to The target URL to resolve. + */ + function resolve(from: string, to: string): string; + /** + * Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an + * invalid domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToUnicode}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToASCII('español.com')); + * // Prints xn--espaol-zwa.com + * console.log(url.domainToASCII('中文.com')); + * // Prints xn--fiq228c.com + * console.log(url.domainToASCII('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToASCII(domain: string): string; + /** + * Returns the Unicode serialization of the `domain`. If `domain` is an invalid + * domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToASCII}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToUnicode('xn--espaol-zwa.com')); + * // Prints español.com + * console.log(url.domainToUnicode('xn--fiq228c.com')); + * // Prints 中文.com + * console.log(url.domainToUnicode('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToUnicode(domain: string): string; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * + * ```js + * import { fileURLToPath } from 'node:url'; + * + * const __filename = fileURLToPath(import.meta.url); + * + * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ + * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) + * + * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt + * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) + * + * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt + * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) + * + * new URL('file:///hello world').pathname; // Incorrect: /hello%20world + * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) + * ``` + * @since v10.12.0 + * @param url The file URL string or URL object to convert to a path. + * @return The fully-resolved platform-specific Node.js file path. + */ + function fileURLToPath(url: string | URL, options?: FileUrlToPathOptions): string; + /** + * Like `url.fileURLToPath(...)` except that instead of returning a string + * representation of the path, a `Buffer` is returned. This conversion is + * helpful when the input URL contains percent-encoded segments that are + * not valid UTF-8 / Unicode sequences. + * @since v22.18.0 + * @param url The file URL string or URL object to convert to a path. + * @returns The fully-resolved platform-specific Node.js file path + * as a `Buffer`. + */ + function fileURLToPathBuffer(url: string | URL, options?: FileUrlToPathOptions): NonSharedBuffer; + /** + * This function ensures that `path` is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * + * ```js + * import { pathToFileURL } from 'node:url'; + * + * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 + * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) + * + * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c + * pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) + * ``` + * @since v10.12.0 + * @param path The path to convert to a File URL. + * @return The file URL object. + */ + function pathToFileURL(path: string, options?: PathToFileUrlOptions): URL; + /** + * This utility function converts a URL object into an ordinary options object as + * expected by the `http.request()` and `https.request()` APIs. + * + * ```js + * import { urlToHttpOptions } from 'node:url'; + * const myURL = new URL('https://a:b@測試?abc#foo'); + * + * console.log(urlToHttpOptions(myURL)); + * /* + * { + * protocol: 'https:', + * hostname: 'xn--g6w251d', + * hash: '#foo', + * search: '?abc', + * pathname: '/', + * path: '/?abc', + * href: 'https://a:b@xn--g6w251d/?abc#foo', + * auth: 'a:b' + * } + * + * ``` + * @since v15.7.0, v14.18.0 + * @param url The `WHATWG URL` object to convert to an options object. + * @return Options object + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; + interface URLFormatOptions { + /** + * `true` if the serialized URL string should include the username and password, `false` otherwise. + * @default true + */ + auth?: boolean | undefined; + /** + * `true` if the serialized URL string should include the fragment, `false` otherwise. + * @default true + */ + fragment?: boolean | undefined; + /** + * `true` if the serialized URL string should include the search query, `false` otherwise. + * @default true + */ + search?: boolean | undefined; + /** + * `true` if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to + * being Punycode encoded. + * @default false + */ + unicode?: boolean | undefined; + } + /** + * Browser-compatible `URL` class, implemented by following the WHATWG URL + * Standard. [Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself. + * The `URL` class is also available on the global object. + * + * In accordance with browser conventions, all properties of `URL` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. Thus, unlike `legacy urlObject`s, + * using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still + * return `true`. + * @since v7.0.0, v6.13.0 + */ + class URL { + /** + * Creates a `'blob:nodedata:...'` URL string that represents the given `Blob` object and can be used to retrieve the `Blob` later. + * + * ```js + * import { + * Blob, + * resolveObjectURL, + * } from 'node:buffer'; + * + * const blob = new Blob(['hello']); + * const id = URL.createObjectURL(blob); + * + * // later... + * + * const otherBlob = resolveObjectURL(id); + * console.log(otherBlob.size); + * ``` + * + * The data stored by the registered `Blob` will be retained in memory until `URL.revokeObjectURL()` is called to remove it. + * + * `Blob` objects are registered within the current thread. If using Worker + * Threads, `Blob` objects registered within one Worker will not be available + * to other workers or the main thread. + * @since v16.7.0 + */ + static createObjectURL(blob: NodeBlob): string; + /** + * Removes the stored `Blob` identified by the given ID. Attempting to revoke a + * ID that isn't registered will silently fail. + * @since v16.7.0 + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + static revokeObjectURL(id: string): void; + /** + * Checks if an `input` relative to the `base` can be parsed to a `URL`. + * + * ```js + * const isValid = URL.canParse('/foo', 'https://example.org/'); // true + * + * const isNotValid = URL.canParse('/foo'); // false + * ``` + * @since v19.9.0 + * @param input The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored. If `input` is not a string, it is + * `converted to a string` first. + * @param base The base URL to resolve against if the `input` is not absolute. If `base` is not a string, it is `converted to a string` first. + */ + static canParse(input: string, base?: string): boolean; + /** + * Parses a string as a URL. If `base` is provided, it will be used as the base + * URL for the purpose of resolving non-absolute `input` URLs. Returns `null` + * if the parameters can't be resolved to a valid URL. + * @since v22.1.0 + * @param input The absolute or relative input URL to parse. If `input` + * is relative, then `base` is required. If `input` is absolute, the `base` + * is ignored. If `input` is not a string, it is [converted to a string](https://tc39.es/ecma262/#sec-tostring) first. + * @param base The base URL to resolve against if the `input` is not + * absolute. If `base` is not a string, it is [converted to a string](https://tc39.es/ecma262/#sec-tostring) first. + */ + static parse(input: string, base?: string): URL | null; + constructor(input: string | { toString: () => string }, base?: string | URL); + /** + * Gets and sets the fragment portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/foo#bar'); + * console.log(myURL.hash); + * // Prints #bar + * + * myURL.hash = 'baz'; + * console.log(myURL.href); + * // Prints https://example.org/foo#baz + * ``` + * + * Invalid URL characters included in the value assigned to the `hash` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + hash: string; + /** + * Gets and sets the host portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.host); + * // Prints example.org:81 + * + * myURL.host = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:82/foo + * ``` + * + * Invalid host values assigned to the `host` property are ignored. + */ + host: string; + /** + * Gets and sets the host name portion of the URL. The key difference between`url.host` and `url.hostname` is that `url.hostname` does _not_ include the + * port. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.hostname); + * // Prints example.org + * + * // Setting the hostname does not change the port + * myURL.hostname = 'example.com'; + * console.log(myURL.href); + * // Prints https://example.com:81/foo + * + * // Use myURL.host to change the hostname and port + * myURL.host = 'example.org:82'; + * console.log(myURL.href); + * // Prints https://example.org:82/foo + * ``` + * + * Invalid host name values assigned to the `hostname` property are ignored. + */ + hostname: string; + /** + * Gets and sets the serialized URL. + * + * ```js + * const myURL = new URL('https://example.org/foo'); + * console.log(myURL.href); + * // Prints https://example.org/foo + * + * myURL.href = 'https://example.com/bar'; + * console.log(myURL.href); + * // Prints https://example.com/bar + * ``` + * + * Getting the value of the `href` property is equivalent to calling {@link toString}. + * + * Setting the value of this property to a new value is equivalent to creating a + * new `URL` object using `new URL(value)`. Each of the `URL` object's properties will be modified. + * + * If the value assigned to the `href` property is not a valid URL, a `TypeError` will be thrown. + */ + href: string; + /** + * Gets the read-only serialization of the URL's origin. + * + * ```js + * const myURL = new URL('https://example.org/foo/bar?baz'); + * console.log(myURL.origin); + * // Prints https://example.org + * ``` + * + * ```js + * const idnURL = new URL('https://測試'); + * console.log(idnURL.origin); + * // Prints https://xn--g6w251d + * + * console.log(idnURL.hostname); + * // Prints xn--g6w251d + * ``` + */ + readonly origin: string; + /** + * Gets and sets the password portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.password); + * // Prints xyz + * + * myURL.password = '123'; + * console.log(myURL.href); + * // Prints https://abc:123@example.com/ + * ``` + * + * Invalid URL characters included in the value assigned to the `password` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + password: string; + /** + * Gets and sets the path portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc/xyz?123'); + * console.log(myURL.pathname); + * // Prints /abc/xyz + * + * myURL.pathname = '/abcdef'; + * console.log(myURL.href); + * // Prints https://example.org/abcdef?123 + * ``` + * + * Invalid URL characters included in the value assigned to the `pathname` property are `percent-encoded`. The selection of which characters + * to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + pathname: string; + /** + * Gets and sets the port portion of the URL. + * + * The port value may be a number or a string containing a number in the range `0` to `65535` (inclusive). Setting the value to the default port of the `URL` objects given `protocol` will + * result in the `port` value becoming + * the empty string (`''`). + * + * The port value can be an empty string in which case the port depends on + * the protocol/scheme: + * + * + * + * Upon assigning a value to the port, the value will first be converted to a + * string using `.toString()`. + * + * If that string is invalid but it begins with a number, the leading number is + * assigned to `port`. + * If the number lies outside the range denoted above, it is ignored. + * + * ```js + * const myURL = new URL('https://example.org:8888'); + * console.log(myURL.port); + * // Prints 8888 + * + * // Default ports are automatically transformed to the empty string + * // (HTTPS protocol's default port is 443) + * myURL.port = '443'; + * console.log(myURL.port); + * // Prints the empty string + * console.log(myURL.href); + * // Prints https://example.org/ + * + * myURL.port = 1234; + * console.log(myURL.port); + * // Prints 1234 + * console.log(myURL.href); + * // Prints https://example.org:1234/ + * + * // Completely invalid port strings are ignored + * myURL.port = 'abcd'; + * console.log(myURL.port); + * // Prints 1234 + * + * // Leading numbers are treated as a port number + * myURL.port = '5678abcd'; + * console.log(myURL.port); + * // Prints 5678 + * + * // Non-integers are truncated + * myURL.port = 1234.5678; + * console.log(myURL.port); + * // Prints 1234 + * + * // Out-of-range numbers which are not represented in scientific notation + * // will be ignored. + * myURL.port = 1e10; // 10000000000, will be range-checked as described below + * console.log(myURL.port); + * // Prints 1234 + * ``` + * + * Numbers which contain a decimal point, + * such as floating-point numbers or numbers in scientific notation, + * are not an exception to this rule. + * Leading numbers up to the decimal point will be set as the URL's port, + * assuming they are valid: + * + * ```js + * myURL.port = 4.567e21; + * console.log(myURL.port); + * // Prints 4 (because it is the leading number in the string '4.567e21') + * ``` + */ + port: string; + /** + * Gets and sets the protocol portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org'); + * console.log(myURL.protocol); + * // Prints https: + * + * myURL.protocol = 'ftp'; + * console.log(myURL.href); + * // Prints ftp://example.org/ + * ``` + * + * Invalid URL protocol values assigned to the `protocol` property are ignored. + */ + protocol: string; + /** + * Gets and sets the serialized query portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc?123'); + * console.log(myURL.search); + * // Prints ?123 + * + * myURL.search = 'abc=xyz'; + * console.log(myURL.href); + * // Prints https://example.org/abc?abc=xyz + * ``` + * + * Any invalid URL characters appearing in the value assigned the `search` property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + search: string; + /** + * Gets the `URLSearchParams` object representing the query parameters of the + * URL. This property is read-only but the `URLSearchParams` object it provides + * can be used to mutate the URL instance; to replace the entirety of query + * parameters of the URL, use the {@link search} setter. See `URLSearchParams` documentation for details. + * + * Use care when using `.searchParams` to modify the `URL` because, + * per the WHATWG specification, the `URLSearchParams` object uses + * different rules to determine which characters to percent-encode. For + * instance, the `URL` object will not percent encode the ASCII tilde (`~`) + * character, while `URLSearchParams` will always encode it: + * + * ```js + * const myURL = new URL('https://example.org/abc?foo=~bar'); + * + * console.log(myURL.search); // prints ?foo=~bar + * + * // Modify the URL via searchParams... + * myURL.searchParams.sort(); + * + * console.log(myURL.search); // prints ?foo=%7Ebar + * ``` + */ + readonly searchParams: URLSearchParams; + /** + * Gets and sets the username portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.username); + * // Prints abc + * + * myURL.username = '123'; + * console.log(myURL.href); + * // Prints https://123:xyz@example.com/ + * ``` + * + * Any invalid URL characters appearing in the value assigned the `username` property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + username: string; + /** + * The `toString()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toJSON}. + */ + toString(): string; + /** + * The `toJSON()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toString}. + * + * This method is automatically called when an `URL` object is serialized + * with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). + * + * ```js + * const myURLs = [ + * new URL('https://www.example.com'), + * new URL('https://test.example.org'), + * ]; + * console.log(JSON.stringify(myURLs)); + * // Prints ["https://www.example.com/","https://test.example.org/"] + * ``` + */ + toJSON(): string; + } + interface URLSearchParamsIterator extends NodeJS.Iterator { + [Symbol.iterator](): URLSearchParamsIterator; + } + /** + * The `URLSearchParams` API provides read and write access to the query of a `URL`. The `URLSearchParams` class can also be used standalone with one of the + * four following constructors. + * The `URLSearchParams` class is also available on the global object. + * + * The WHATWG `URLSearchParams` interface and the `querystring` module have + * similar purpose, but the purpose of the `querystring` module is more + * general, as it allows the customization of delimiter characters (`&` and `=`). + * On the other hand, this API is designed purely for URL query strings. + * + * ```js + * const myURL = new URL('https://example.org/?abc=123'); + * console.log(myURL.searchParams.get('abc')); + * // Prints 123 + * + * myURL.searchParams.append('abc', 'xyz'); + * console.log(myURL.href); + * // Prints https://example.org/?abc=123&abc=xyz + * + * myURL.searchParams.delete('abc'); + * myURL.searchParams.set('a', 'b'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * + * const newSearchParams = new URLSearchParams(myURL.searchParams); + * // The above is equivalent to + * // const newSearchParams = new URLSearchParams(myURL.search); + * + * newSearchParams.append('a', 'c'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * console.log(newSearchParams.toString()); + * // Prints a=b&a=c + * + * // newSearchParams.toString() is implicitly called + * myURL.search = newSearchParams; + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * newSearchParams.delete('a'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * ``` + * @since v7.5.0, v6.13.0 + */ + class URLSearchParams implements Iterable<[string, string]> { + constructor( + init?: + | URLSearchParams + | string + | Record + | Iterable<[string, string]> + | ReadonlyArray<[string, string]>, + ); + /** + * Append a new name-value pair to the query string. + */ + append(name: string, value: string): void; + /** + * If `value` is provided, removes all name-value pairs + * where name is `name` and value is `value`. + * + * If `value` is not provided, removes all name-value pairs whose name is `name`. + */ + delete(name: string, value?: string): void; + /** + * Returns an ES6 `Iterator` over each of the name-value pairs in the query. + * Each item of the iterator is a JavaScript `Array`. The first item of the `Array` is the `name`, the second item of the `Array` is the `value`. + * + * Alias for `urlSearchParams[Symbol.iterator]()`. + */ + entries(): URLSearchParamsIterator<[string, string]>; + /** + * Iterates over each name-value pair in the query and invokes the given function. + * + * ```js + * const myURL = new URL('https://example.org/?a=b&c=d'); + * myURL.searchParams.forEach((value, name, searchParams) => { + * console.log(name, value, myURL.searchParams === searchParams); + * }); + * // Prints: + * // a b true + * // c d true + * ``` + * @param fn Invoked for each name-value pair in the query + * @param thisArg To be used as `this` value for when `fn` is called + */ + forEach( + fn: (this: TThis, value: string, name: string, searchParams: URLSearchParams) => void, + thisArg?: TThis, + ): void; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns the values of all name-value pairs whose name is `name`. If there are + * no such pairs, an empty array is returned. + */ + getAll(name: string): string[]; + /** + * Checks if the `URLSearchParams` object contains key-value pair(s) based on `name` and an optional `value` argument. + * + * If `value` is provided, returns `true` when name-value pair with + * same `name` and `value` exists. + * + * If `value` is not provided, returns `true` if there is at least one name-value + * pair whose name is `name`. + */ + has(name: string, value?: string): boolean; + /** + * Returns an ES6 `Iterator` over the names of each name-value pair. + * + * ```js + * const params = new URLSearchParams('foo=bar&foo=baz'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // foo + * ``` + */ + keys(): URLSearchParamsIterator; + /** + * Sets the value in the `URLSearchParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value` and remove all others. If not, + * append the name-value pair to the query string. + * + * ```js + * const params = new URLSearchParams(); + * params.append('foo', 'bar'); + * params.append('foo', 'baz'); + * params.append('abc', 'def'); + * console.log(params.toString()); + * // Prints foo=bar&foo=baz&abc=def + * + * params.set('foo', 'def'); + * params.set('xyz', 'opq'); + * console.log(params.toString()); + * // Prints foo=def&abc=def&xyz=opq + * ``` + */ + set(name: string, value: string): void; + /** + * The total number of parameter entries. + * @since v19.8.0 + */ + readonly size: number; + /** + * Sort all existing name-value pairs in-place by their names. Sorting is done + * with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs + * with the same name is preserved. + * + * This method can be used, in particular, to increase cache hits. + * + * ```js + * const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); + * params.sort(); + * console.log(params.toString()); + * // Prints query%5B%5D=abc&query%5B%5D=123&type=search + * ``` + * @since v7.7.0, v6.13.0 + */ + sort(): void; + /** + * Returns the search parameters serialized as a string, with characters + * percent-encoded where necessary. + */ + toString(): string; + /** + * Returns an ES6 `Iterator` over the values of each name-value pair. + */ + values(): URLSearchParamsIterator; + [Symbol.iterator](): URLSearchParamsIterator<[string, string]>; + } + import { URL as _URL, URLSearchParams as _URLSearchParams } from "url"; + global { + interface URLSearchParams extends _URLSearchParams {} + interface URL extends _URL {} + interface Global { + URL: typeof _URL; + URLSearchParams: typeof _URLSearchParams; + } + /** + * `URL` class is a global reference for `import { URL } from 'url'` + * https://nodejs.org/api/url.html#the-whatwg-url-api + * @since v10.0.0 + */ + var URL: typeof globalThis extends { + onmessage: any; + URL: infer T; + } ? T + : typeof _URL; + /** + * `URLSearchParams` class is a global reference for `import { URLSearchParams } from 'node:url'` + * https://nodejs.org/api/url.html#class-urlsearchparams + * @since v10.0.0 + */ + var URLSearchParams: typeof globalThis extends { + onmessage: any; + URLSearchParams: infer T; + } ? T + : typeof _URLSearchParams; + } +} +declare module "node:url" { + export * from "url"; +} diff --git a/node_modules/@types/node/util.d.ts b/node_modules/@types/node/util.d.ts new file mode 100644 index 0000000..a171f65 --- /dev/null +++ b/node_modules/@types/node/util.d.ts @@ -0,0 +1,2606 @@ +/** + * The `node:util` module supports the needs of Node.js internal APIs. Many of the + * utilities are useful for application and module developers as well. To access + * it: + * + * ```js + * import util from 'node:util'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/util.js) + */ +declare module "util" { + import * as types from "node:util/types"; + export interface InspectOptions { + /** + * If `true`, object's non-enumerable symbols and properties are included in the formatted result. + * `WeakMap` and `WeakSet` entries are also included as well as user defined prototype properties (excluding method properties). + * @default false + */ + showHidden?: boolean | undefined; + /** + * Specifies the number of times to recurse while formatting object. + * This is useful for inspecting large objects. + * To recurse up to the maximum call stack size pass `Infinity` or `null`. + * @default 2 + */ + depth?: number | null | undefined; + /** + * If `true`, the output is styled with ANSI color codes. Colors are customizable. + */ + colors?: boolean | undefined; + /** + * If `false`, `[util.inspect.custom](depth, opts, inspect)` functions are not invoked. + * @default true + */ + customInspect?: boolean | undefined; + /** + * If `true`, `Proxy` inspection includes the target and handler objects. + * @default false + */ + showProxy?: boolean | undefined; + /** + * Specifies the maximum number of `Array`, `TypedArray`, `WeakMap`, and `WeakSet` elements + * to include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no elements. + * @default 100 + */ + maxArrayLength?: number | null | undefined; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default 10000 + */ + maxStringLength?: number | null | undefined; + /** + * The length at which input values are split across multiple lines. + * Set to `Infinity` to format the input as a single line + * (in combination with `compact` set to `true` or any number >= `1`). + * @default 80 + */ + breakLength?: number | undefined; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default true + */ + compact?: boolean | number | undefined; + /** + * If set to `true` or a function, all properties of an object, and `Set` and `Map` + * entries are sorted in the resulting string. + * If set to `true` the default sort is used. + * If set to a function, it is used as a compare function. + */ + sorted?: boolean | ((a: string, b: string) => number) | undefined; + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default false + */ + getters?: "get" | "set" | boolean | undefined; + /** + * If set to `true`, an underscore is used to separate every three digits in all bigints and numbers. + * @default false + */ + numericSeparator?: boolean | undefined; + } + export type Style = + | "special" + | "number" + | "bigint" + | "boolean" + | "undefined" + | "null" + | "string" + | "symbol" + | "date" + | "regexp" + | "module"; + export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => any; // TODO: , inspect: inspect + export interface InspectOptionsStylized extends InspectOptions { + stylize(text: string, styleType: Style): string; + } + export interface CallSiteObject { + /** + * Returns the name of the function associated with this call site. + */ + functionName: string; + /** + * Returns the name of the resource that contains the script for the + * function for this call site. + */ + scriptName: string; + /** + * Returns the unique id of the script, as in Chrome DevTools protocol + * [`Runtime.ScriptId`](https://chromedevtools.github.io/devtools-protocol/1-3/Runtime/#type-ScriptId). + * @since v22.14.0 + */ + scriptId: string; + /** + * Returns the number, 1-based, of the line for the associate function call. + */ + lineNumber: number; + /** + * Returns the 1-based column offset on the line for the associated function call. + */ + columnNumber: number; + } + export type DiffEntry = [operation: -1 | 0 | 1, value: string]; + /** + * `util.diff()` compares two string or array values and returns an array of difference entries. + * It uses the Myers diff algorithm to compute minimal differences, which is the same algorithm + * used internally by assertion error messages. + * + * If the values are equal, an empty array is returned. + * + * ```js + * const { diff } = require('node:util'); + * + * // Comparing strings + * const actualString = '12345678'; + * const expectedString = '12!!5!7!'; + * console.log(diff(actualString, expectedString)); + * // [ + * // [0, '1'], + * // [0, '2'], + * // [1, '3'], + * // [1, '4'], + * // [-1, '!'], + * // [-1, '!'], + * // [0, '5'], + * // [1, '6'], + * // [-1, '!'], + * // [0, '7'], + * // [1, '8'], + * // [-1, '!'], + * // ] + * // Comparing arrays + * const actualArray = ['1', '2', '3']; + * const expectedArray = ['1', '3', '4']; + * console.log(diff(actualArray, expectedArray)); + * // [ + * // [0, '1'], + * // [1, '2'], + * // [0, '3'], + * // [-1, '4'], + * // ] + * // Equal values return empty array + * console.log(diff('same', 'same')); + * // [] + * ``` + * @since v22.15.0 + * @experimental + * @param actual The first value to compare + * @param expected The second value to compare + * @returns An array of difference entries. Each entry is an array with two elements: + * * Index 0: `number` Operation code: `-1` for delete, `0` for no-op/unchanged, `1` for insert + * * Index 1: `string` The value associated with the operation + */ + export function diff(actual: string | readonly string[], expected: string | readonly string[]): DiffEntry[]; + /** + * The `util.format()` method returns a formatted string using the first argument + * as a `printf`-like format string which can contain zero or more format + * specifiers. Each specifier is replaced with the converted value from the + * corresponding argument. Supported specifiers are: + * + * If a specifier does not have a corresponding argument, it is not replaced: + * + * ```js + * util.format('%s:%s', 'foo'); + * // Returns: 'foo:%s' + * ``` + * + * Values that are not part of the format string are formatted using `util.inspect()` if their type is not `string`. + * + * If there are more arguments passed to the `util.format()` method than the + * number of specifiers, the extra arguments are concatenated to the returned + * string, separated by spaces: + * + * ```js + * util.format('%s:%s', 'foo', 'bar', 'baz'); + * // Returns: 'foo:bar baz' + * ``` + * + * If the first argument does not contain a valid format specifier, `util.format()` returns a string that is the concatenation of all arguments separated by spaces: + * + * ```js + * util.format(1, 2, 3); + * // Returns: '1 2 3' + * ``` + * + * If only one argument is passed to `util.format()`, it is returned as it is + * without any formatting: + * + * ```js + * util.format('%% %s'); + * // Returns: '%% %s' + * ``` + * + * `util.format()` is a synchronous method that is intended as a debugging tool. + * Some input values can have a significant performance overhead that can block the + * event loop. Use this function with care and never in a hot code path. + * @since v0.5.3 + * @param format A `printf`-like format string. + */ + export function format(format?: any, ...param: any[]): string; + /** + * This function is identical to {@link format}, except in that it takes + * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}. + * + * ```js + * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + * // Returns 'See object { foo: 42 }', where `42` is colored as a number + * // when printed to a terminal. + * ``` + * @since v10.0.0 + */ + export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; + interface GetCallSitesOptions { + /** + * Reconstruct the original location in the stacktrace from the source-map. + * Enabled by default with the flag `--enable-source-maps`. + */ + sourceMap?: boolean | undefined; + } + /** + * Returns an array of call site objects containing the stack of + * the caller function. + * + * ```js + * import { getCallSites } from 'node:util'; + * + * function exampleFunction() { + * const callSites = getCallSites(); + * + * console.log('Call Sites:'); + * callSites.forEach((callSite, index) => { + * console.log(`CallSite ${index + 1}:`); + * console.log(`Function Name: ${callSite.functionName}`); + * console.log(`Script Name: ${callSite.scriptName}`); + * console.log(`Line Number: ${callSite.lineNumber}`); + * console.log(`Column Number: ${callSite.column}`); + * }); + * // CallSite 1: + * // Function Name: exampleFunction + * // Script Name: /home/example.js + * // Line Number: 5 + * // Column Number: 26 + * + * // CallSite 2: + * // Function Name: anotherFunction + * // Script Name: /home/example.js + * // Line Number: 22 + * // Column Number: 3 + * + * // ... + * } + * + * // A function to simulate another stack layer + * function anotherFunction() { + * exampleFunction(); + * } + * + * anotherFunction(); + * ``` + * + * It is possible to reconstruct the original locations by setting the option `sourceMap` to `true`. + * If the source map is not available, the original location will be the same as the current location. + * When the `--enable-source-maps` flag is enabled, for example when using `--experimental-transform-types`, + * `sourceMap` will be true by default. + * + * ```ts + * import { getCallSites } from 'node:util'; + * + * interface Foo { + * foo: string; + * } + * + * const callSites = getCallSites({ sourceMap: true }); + * + * // With sourceMap: + * // Function Name: '' + * // Script Name: example.js + * // Line Number: 7 + * // Column Number: 26 + * + * // Without sourceMap: + * // Function Name: '' + * // Script Name: example.js + * // Line Number: 2 + * // Column Number: 26 + * ``` + * @param frameCount Number of frames to capture as call site objects. + * **Default:** `10`. Allowable range is between 1 and 200. + * @return An array of call site objects + * @since v22.9.0 + */ + export function getCallSites(frameCount?: number, options?: GetCallSitesOptions): CallSiteObject[]; + export function getCallSites(options: GetCallSitesOptions): CallSiteObject[]; + /** + * Returns the string name for a numeric error code that comes from a Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const name = util.getSystemErrorName(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v9.7.0 + */ + export function getSystemErrorName(err: number): string; + /** + * Enable or disable printing a stack trace on `SIGINT`. The API is only available on the main thread. + * @since 22.19.0 + */ + export function setTraceSigInt(enable: boolean): void; + /** + * Returns a Map of all system error codes available from the Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const errorMap = util.getSystemErrorMap(); + * const name = errorMap.get(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v16.0.0, v14.17.0 + */ + export function getSystemErrorMap(): Map; + /** + * Returns the string message for a numeric error code that comes from a Node.js + * API. + * The mapping between error codes and string messages is platform-dependent. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const message = util.getSystemErrorMessage(err.errno); + * console.error(message); // no such file or directory + * }); + * ``` + * @since v22.12.0 + */ + export function getSystemErrorMessage(err: number): string; + /** + * The `util.log()` method prints the given `string` to `stdout` with an included + * timestamp. + * + * ```js + * import util from 'node:util'; + * + * util.log('Timestamped message.'); + * ``` + * @since v0.3.0 + * @deprecated Since v6.0.0 - Use a third party module instead. + */ + export function log(string: string): void; + /** + * Returns the `string` after replacing any surrogate code points + * (or equivalently, any unpaired surrogate code units) with the + * Unicode "replacement character" U+FFFD. + * @since v16.8.0, v14.18.0 + */ + export function toUSVString(string: string): string; + /** + * Creates and returns an `AbortController` instance whose `AbortSignal` is marked + * as transferable and can be used with `structuredClone()` or `postMessage()`. + * @since v18.11.0 + * @returns A transferable AbortController + */ + export function transferableAbortController(): AbortController; + /** + * Marks the given `AbortSignal` as transferable so that it can be used with`structuredClone()` and `postMessage()`. + * + * ```js + * const signal = transferableAbortSignal(AbortSignal.timeout(100)); + * const channel = new MessageChannel(); + * channel.port2.postMessage(signal, [signal]); + * ``` + * @since v18.11.0 + * @param signal The AbortSignal + * @returns The same AbortSignal + */ + export function transferableAbortSignal(signal: AbortSignal): AbortSignal; + /** + * Listens to abort event on the provided `signal` and returns a promise that resolves when the `signal` is aborted. + * If `resource` is provided, it weakly references the operation's associated object, + * so if `resource` is garbage collected before the `signal` aborts, + * then returned promise shall remain pending. + * This prevents memory leaks in long-running or non-cancelable operations. + * + * ```js + * import { aborted } from 'node:util'; + * + * // Obtain an object with an abortable signal, like a custom resource or operation. + * const dependent = obtainSomethingAbortable(); + * + * // Pass `dependent` as the resource, indicating the promise should only resolve + * // if `dependent` is still in memory when the signal is aborted. + * aborted(dependent.signal, dependent).then(() => { + * // This code runs when `dependent` is aborted. + * console.log('Dependent resource was aborted.'); + * }); + * + * // Simulate an event that triggers the abort. + * dependent.on('event', () => { + * dependent.abort(); // This will cause the `aborted` promise to resolve. + * }); + * ``` + * @since v19.7.0 + * @param resource Any non-null object tied to the abortable operation and held weakly. + * If `resource` is garbage collected before the `signal` aborts, the promise remains pending, + * allowing Node.js to stop tracking it. + * This helps prevent memory leaks in long-running or non-cancelable operations. + */ + export function aborted(signal: AbortSignal, resource: any): Promise; + /** + * The `util.inspect()` method returns a string representation of `object` that is + * intended for debugging. The output of `util.inspect` may change at any time + * and should not be depended upon programmatically. Additional `options` may be + * passed that alter the result. + * `util.inspect()` will use the constructor's name and/or `Symbol.toStringTag` + * property to make an identifiable tag for an inspected value. + * + * ```js + * class Foo { + * get [Symbol.toStringTag]() { + * return 'bar'; + * } + * } + * + * class Bar {} + * + * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); + * + * util.inspect(new Foo()); // 'Foo [bar] {}' + * util.inspect(new Bar()); // 'Bar {}' + * util.inspect(baz); // '[foo] {}' + * ``` + * + * Circular references point to their anchor by using a reference index: + * + * ```js + * import { inspect } from 'node:util'; + * + * const obj = {}; + * obj.a = [obj]; + * obj.b = {}; + * obj.b.inner = obj.b; + * obj.b.obj = obj; + * + * console.log(inspect(obj)); + * // { + * // a: [ [Circular *1] ], + * // b: { inner: [Circular *2], obj: [Circular *1] } + * // } + * ``` + * + * The following example inspects all properties of the `util` object: + * + * ```js + * import util from 'node:util'; + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * import { inspect } from 'node:util'; + * + * const o = { + * a: [1, 2, [[ + * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + + * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', + * 'test', + * 'foo']], 4], + * b: new Map([['za', 1], ['zb', 'test']]), + * }; + * console.log(inspect(o, { compact: true, depth: 5, breakLength: 80 })); + * + * // { a: + * // [ 1, + * // 2, + * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line + * // 'test', + * // 'foo' ] ], + * // 4 ], + * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } + * + * // Setting `compact` to false or an integer creates more reader friendly output. + * console.log(inspect(o, { compact: false, depth: 5, breakLength: 80 })); + * + * // { + * // a: [ + * // 1, + * // 2, + * // [ + * // [ + * // 'Lorem ipsum dolor sit amet,\n' + + * // 'consectetur adipiscing elit, sed do eiusmod \n' + + * // 'tempor incididunt ut labore et dolore magna aliqua.', + * // 'test', + * // 'foo' + * // ] + * // ], + * // 4 + * // ], + * // b: Map(2) { + * // 'za' => 1, + * // 'zb' => 'test' + * // } + * // } + * + * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a + * // single line. + * ``` + * + * The `showHidden` option allows `WeakMap` and `WeakSet` entries to be + * inspected. If there are more entries than `maxArrayLength`, there is no + * guarantee which entries are displayed. That means retrieving the same + * `WeakSet` entries twice may result in different output. Furthermore, entries + * with no remaining strong references may be garbage collected at any time. + * + * ```js + * import { inspect } from 'node:util'; + * + * const obj = { a: 1 }; + * const obj2 = { b: 2 }; + * const weakSet = new WeakSet([obj, obj2]); + * + * console.log(inspect(weakSet, { showHidden: true })); + * // WeakSet { { a: 1 }, { b: 2 } } + * ``` + * + * The `sorted` option ensures that an object's property insertion order does not + * impact the result of `util.inspect()`. + * + * ```js + * import { inspect } from 'node:util'; + * import assert from 'node:assert'; + * + * const o1 = { + * b: [2, 3, 1], + * a: '`a` comes before `b`', + * c: new Set([2, 3, 1]), + * }; + * console.log(inspect(o1, { sorted: true })); + * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } + * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); + * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } + * + * const o2 = { + * c: new Set([2, 1, 3]), + * a: '`a` comes before `b`', + * b: [2, 3, 1], + * }; + * assert.strict.equal( + * inspect(o1, { sorted: true }), + * inspect(o2, { sorted: true }), + * ); + * ``` + * + * The `numericSeparator` option adds an underscore every three digits to all + * numbers. + * + * ```js + * import { inspect } from 'node:util'; + * + * const thousand = 1000; + * const million = 1000000; + * const bigNumber = 123456789n; + * const bigDecimal = 1234.12345; + * + * console.log(inspect(thousand, { numericSeparator: true })); + * // 1_000 + * console.log(inspect(million, { numericSeparator: true })); + * // 1_000_000 + * console.log(inspect(bigNumber, { numericSeparator: true })); + * // 123_456_789n + * console.log(inspect(bigDecimal, { numericSeparator: true })); + * // 1_234.123_45 + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MiB. Inputs that result in longer output will + * be truncated. + * @since v0.3.0 + * @param object Any JavaScript primitive or `Object`. + * @return The representation of `object`. + */ + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options?: InspectOptions): string; + export namespace inspect { + let colors: NodeJS.Dict<[number, number]>; + let styles: { + [K in Style]: string; + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; + /** + * That can be used to declare custom inspect functions. + */ + const custom: unique symbol; + } + /** + * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). + * + * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isArray([]); + * // Returns: true + * util.isArray(new Array()); + * // Returns: true + * util.isArray({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use `isArray` instead. + */ + export function isArray(object: unknown): object is unknown[]; + /** + * Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isRegExp(/some regexp/); + * // Returns: true + * util.isRegExp(new RegExp('another regexp')); + * // Returns: true + * util.isRegExp({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Deprecated + */ + export function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isDate(new Date()); + * // Returns: true + * util.isDate(Date()); + * // false (without 'new' returns a String) + * util.isDate({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isDate} instead. + */ + export function isDate(object: unknown): object is Date; + /** + * Returns `true` if the given `object` is an `Error`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isError(new Error()); + * // Returns: true + * util.isError(new TypeError()); + * // Returns: true + * util.isError({ name: 'Error', message: 'an error occurred' }); + * // Returns: false + * ``` + * + * This method relies on `Object.prototype.toString()` behavior. It is + * possible to obtain an incorrect result when the `object` argument manipulates `@@toStringTag`. + * + * ```js + * import util from 'node:util'; + * const obj = { name: 'Error', message: 'an error occurred' }; + * + * util.isError(obj); + * // Returns: false + * obj[Symbol.toStringTag] = 'Error'; + * util.isError(obj); + * // Returns: true + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isNativeError} instead. + */ + export function isError(object: unknown): object is Error; + /** + * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and + * `extends` keywords to get language level inheritance support. Also note + * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). + * + * Inherit the prototype methods from one + * [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The + * prototype of `constructor` will be set to a new object created from + * `superConstructor`. + * + * This mainly adds some input validation on top of + * `Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. + * As an additional convenience, `superConstructor` will be accessible + * through the `constructor.super_` property. + * + * ```js + * const util = require('node:util'); + * const EventEmitter = require('node:events'); + * + * function MyStream() { + * EventEmitter.call(this); + * } + * + * util.inherits(MyStream, EventEmitter); + * + * MyStream.prototype.write = function(data) { + * this.emit('data', data); + * }; + * + * const stream = new MyStream(); + * + * console.log(stream instanceof EventEmitter); // true + * console.log(MyStream.super_ === EventEmitter); // true + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('It works!'); // Received data: "It works!" + * ``` + * + * ES6 example using `class` and `extends`: + * + * ```js + * import EventEmitter from 'node:events'; + * + * class MyStream extends EventEmitter { + * write(data) { + * this.emit('data', data); + * } + * } + * + * const stream = new MyStream(); + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('With ES6'); + * ``` + * @since v0.3.0 + * @legacy Use ES2015 class syntax and `extends` keyword instead. + */ + export function inherits(constructor: unknown, superConstructor: unknown): void; + export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; + export interface DebugLogger extends DebugLoggerFunction { + /** + * The `util.debuglog().enabled` getter is used to create a test that can be used + * in conditionals based on the existence of the `NODE_DEBUG` environment variable. + * If the `section` name appears within the value of that environment variable, + * then the returned value will be `true`. If not, then the returned value will be + * `false`. + * + * ```js + * import { debuglog } from 'node:util'; + * const enabled = debuglog('foo').enabled; + * if (enabled) { + * console.log('hello from foo [%d]', 123); + * } + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then it will + * output something like: + * + * ```console + * hello from foo [123] + * ``` + */ + enabled: boolean; + } + /** + * The `util.debuglog()` method is used to create a function that conditionally + * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG` + * environment variable. If the `section` name appears within the value of that + * environment variable, then the returned function operates similar to + * `console.error()`. If not, then the returned function is a no-op. + * + * ```js + * import { debuglog } from 'node:util'; + * const log = debuglog('foo'); + * + * log('hello from foo [%d]', 123); + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then + * it will output something like: + * + * ```console + * FOO 3245: hello from foo [123] + * ``` + * + * where `3245` is the process id. If it is not run with that + * environment variable set, then it will not print anything. + * + * The `section` supports wildcard also: + * + * ```js + * import { debuglog } from 'node:util'; + * const log = debuglog('foo'); + * + * log('hi there, it\'s foo-bar [%d]', 2333); + * ``` + * + * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output + * something like: + * + * ```console + * FOO-BAR 3257: hi there, it's foo-bar [2333] + * ``` + * + * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG` + * environment variable: `NODE_DEBUG=fs,net,tls`. + * + * The optional `callback` argument can be used to replace the logging function + * with a different function that doesn't have any initialization or + * unnecessary wrapping. + * + * ```js + * import { debuglog } from 'node:util'; + * let log = debuglog('internals', (debug) => { + * // Replace with a logging function that optimizes out + * // testing if the section is enabled + * log = debug; + * }); + * ``` + * @since v0.11.3 + * @param section A string identifying the portion of the application for which the `debuglog` function is being created. + * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function. + * @return The logging function + */ + export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; + export { debuglog as debug }; + /** + * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isBoolean(1); + * // Returns: false + * util.isBoolean(0); + * // Returns: false + * util.isBoolean(false); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'boolean'` instead. + */ + export function isBoolean(object: unknown): object is boolean; + /** + * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isBuffer({ length: 0 }); + * // Returns: false + * util.isBuffer([]); + * // Returns: false + * util.isBuffer(Buffer.from('hello world')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `isBuffer` instead. + */ + export function isBuffer(object: unknown): object is Buffer; + /** + * Returns `true` if the given `object` is a `Function`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * function Foo() {} + * const Bar = () => {}; + * + * util.isFunction({}); + * // Returns: false + * util.isFunction(Foo); + * // Returns: true + * util.isFunction(Bar); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'function'` instead. + */ + export function isFunction(object: unknown): boolean; + /** + * Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`. + * + * ```js + * import util from 'node:util'; + * + * util.isNull(0); + * // Returns: false + * util.isNull(undefined); + * // Returns: false + * util.isNull(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === null` instead. + */ + export function isNull(object: unknown): object is null; + /** + * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, + * returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isNullOrUndefined(0); + * // Returns: false + * util.isNullOrUndefined(undefined); + * // Returns: true + * util.isNullOrUndefined(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined || value === null` instead. + */ + export function isNullOrUndefined(object: unknown): object is null | undefined; + /** + * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isNumber(false); + * // Returns: false + * util.isNumber(Infinity); + * // Returns: true + * util.isNumber(0); + * // Returns: true + * util.isNumber(NaN); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'number'` instead. + */ + export function isNumber(object: unknown): object is number; + /** + * Returns `true` if the given `object` is strictly an `Object`**and** not a`Function` (even though functions are objects in JavaScript). + * Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isObject(5); + * // Returns: false + * util.isObject(null); + * // Returns: false + * util.isObject({}); + * // Returns: true + * util.isObject(() => {}); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value !== null && typeof value === 'object'` instead. + */ + export function isObject(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a primitive type. Otherwise, returns`false`. + * + * ```js + * import util from 'node:util'; + * + * util.isPrimitive(5); + * // Returns: true + * util.isPrimitive('foo'); + * // Returns: true + * util.isPrimitive(false); + * // Returns: true + * util.isPrimitive(null); + * // Returns: true + * util.isPrimitive(undefined); + * // Returns: true + * util.isPrimitive({}); + * // Returns: false + * util.isPrimitive(() => {}); + * // Returns: false + * util.isPrimitive(/^$/); + * // Returns: false + * util.isPrimitive(new Date()); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. + */ + export function isPrimitive(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isString(''); + * // Returns: true + * util.isString('foo'); + * // Returns: true + * util.isString(String('foo')); + * // Returns: true + * util.isString(5); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'string'` instead. + */ + export function isString(object: unknown): object is string; + /** + * Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isSymbol(5); + * // Returns: false + * util.isSymbol('foo'); + * // Returns: false + * util.isSymbol(Symbol('foo')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'symbol'` instead. + */ + export function isSymbol(object: unknown): object is symbol; + /** + * Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * const foo = undefined; + * util.isUndefined(5); + * // Returns: false + * util.isUndefined(foo); + * // Returns: true + * util.isUndefined(null); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined` instead. + */ + export function isUndefined(object: unknown): object is undefined; + /** + * The `util.deprecate()` method wraps `fn` (which may be a function or class) in + * such a way that it is marked as deprecated. + * + * ```js + * import { deprecate } from 'node:util'; + * + * export const obsoleteFunction = deprecate(() => { + * // Do something here. + * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); + * ``` + * + * When called, `util.deprecate()` will return a function that will emit a + * `DeprecationWarning` using the `'warning'` event. The warning will + * be emitted and printed to `stderr` the first time the returned function is + * called. After the warning is emitted, the wrapped function is called without + * emitting a warning. + * + * If the same optional `code` is supplied in multiple calls to `util.deprecate()`, + * the warning will be emitted only once for that `code`. + * + * ```js + * import { deprecate } from 'node:util'; + * + * const fn1 = deprecate( + * () => 'a value', + * 'deprecation message', + * 'DEP0001', + * ); + * const fn2 = deprecate( + * () => 'a different value', + * 'other dep message', + * 'DEP0001', + * ); + * fn1(); // Emits a deprecation warning with code DEP0001 + * fn2(); // Does not emit a deprecation warning because it has the same code + * ``` + * + * If either the `--no-deprecation` or `--no-warnings` command-line flags are + * used, or if the `process.noDeprecation` property is set to `true` _prior_ to + * the first deprecation warning, the `util.deprecate()` method does nothing. + * + * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, + * or the `process.traceDeprecation` property is set to `true`, a warning and a + * stack trace are printed to `stderr` the first time the deprecated function is + * called. + * + * If the `--throw-deprecation` command-line flag is set, or the + * `process.throwDeprecation` property is set to `true`, then an exception will be + * thrown when the deprecated function is called. + * + * The `--throw-deprecation` command-line flag and `process.throwDeprecation` + * property take precedence over `--trace-deprecation` and + * `process.traceDeprecation`. + * @since v0.8.0 + * @param fn The function that is being deprecated. + * @param msg A warning message to display when the deprecated function is invoked. + * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes. + * @return The deprecated function wrapped to emit a warning. + */ + export function deprecate(fn: T, msg: string, code?: string): T; + /** + * Returns `true` if there is deep strict equality between `val1` and `val2`. + * Otherwise, returns `false`. + * + * See `assert.deepStrictEqual()` for more information about deep strict + * equality. + * @since v9.0.0 + */ + export function isDeepStrictEqual(val1: unknown, val2: unknown): boolean; + /** + * Returns `str` with any ANSI escape codes removed. + * + * ```js + * console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); + * // Prints "value" + * ``` + * @since v16.11.0 + */ + export function stripVTControlCharacters(str: string): string; + /** + * Takes an `async` function (or a function that returns a `Promise`) and returns a + * function following the error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument. In the callback, the + * first argument will be the rejection reason (or `null` if the `Promise` + * resolved), and the second argument will be the resolved value. + * + * ```js + * import { callbackify } from 'node:util'; + * + * async function fn() { + * return 'hello world'; + * } + * const callbackFunction = callbackify(fn); + * + * callbackFunction((err, ret) => { + * if (err) throw err; + * console.log(ret); + * }); + * ``` + * + * Will print: + * + * ```text + * hello world + * ``` + * + * The callback is executed asynchronously, and will have a limited stack trace. + * If the callback throws, the process will emit an `'uncaughtException'` + * event, and if not handled will exit. + * + * Since `null` has a special meaning as the first argument to a callback, if a + * wrapped function rejects a `Promise` with a falsy value as a reason, the value + * is wrapped in an `Error` with the original value stored in a field named + * `reason`. + * + * ```js + * function fn() { + * return Promise.reject(null); + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * // When the Promise was rejected with `null` it is wrapped with an Error and + * // the original value is stored in `reason`. + * err && Object.hasOwn(err, 'reason') && err.reason === null; // true + * }); + * ``` + * @since v8.2.0 + * @param fn An `async` function + * @return a callback style function + */ + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: () => Promise, + ): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export interface CustomPromisifyLegacy extends Function { + __promisify__: TCustom; + } + export interface CustomPromisifySymbol extends Function { + [promisify.custom]: TCustom; + } + export type CustomPromisify = + | CustomPromisifySymbol + | CustomPromisifyLegacy; + /** + * Takes a function following the common error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument, and returns a version + * that returns promises. + * + * ```js + * import { promisify } from 'node:util'; + * import { stat } from 'node:fs'; + * + * const promisifiedStat = promisify(stat); + * promisifiedStat('.').then((stats) => { + * // Do something with `stats` + * }).catch((error) => { + * // Handle the error. + * }); + * ``` + * + * Or, equivalently using `async function`s: + * + * ```js + * import { promisify } from 'node:util'; + * import { stat } from 'node:fs'; + * + * const promisifiedStat = promisify(stat); + * + * async function callStat() { + * const stats = await promisifiedStat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * + * callStat(); + * ``` + * + * If there is an `original[util.promisify.custom]` property present, `promisify` + * will return its value, see [Custom promisified functions](https://nodejs.org/docs/latest-v22.x/api/util.html#custom-promisified-functions). + * + * `promisify()` assumes that `original` is a function taking a callback as its + * final argument in all cases. If `original` is not a function, `promisify()` + * will throw an error. If `original` is a function but its last argument is not + * an error-first callback, it will still be passed an error-first + * callback as its last argument. + * + * Using `promisify()` on class methods or other methods that use `this` may not + * work as expected unless handled specially: + * + * ```js + * import { promisify } from 'node:util'; + * + * class Foo { + * constructor() { + * this.a = 42; + * } + * + * bar(callback) { + * callback(null, this.a); + * } + * } + * + * const foo = new Foo(); + * + * const naiveBar = promisify(foo.bar); + * // TypeError: Cannot read properties of undefined (reading 'a') + * // naiveBar().then(a => console.log(a)); + * + * naiveBar.call(foo).then((a) => console.log(a)); // '42' + * + * const bindBar = naiveBar.bind(foo); + * bindBar().then((a) => console.log(a)); // '42' + * ``` + * @since v8.0.0 + */ + export function promisify(fn: CustomPromisify): TCustom; + export function promisify( + fn: (callback: (err: any, result: TResult) => void) => void, + ): () => Promise; + export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + export function promisify( + fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: Function): Function; + export namespace promisify { + /** + * That can be used to declare custom promisified variants of functions. + */ + const custom: unique symbol; + } + /** + * Stability: 1.1 - Active development + * Given an example `.env` file: + * + * ```js + * import { parseEnv } from 'node:util'; + * + * parseEnv('HELLO=world\nHELLO=oh my\n'); + * // Returns: { HELLO: 'oh my' } + * ``` + * @param content The raw contents of a `.env` file. + * @since v20.12.0 + */ + export function parseEnv(content: string): NodeJS.Dict; + // https://nodejs.org/docs/latest/api/util.html#foreground-colors + type ForegroundColors = + | "black" + | "blackBright" + | "blue" + | "blueBright" + | "cyan" + | "cyanBright" + | "gray" + | "green" + | "greenBright" + | "grey" + | "magenta" + | "magentaBright" + | "red" + | "redBright" + | "white" + | "whiteBright" + | "yellow" + | "yellowBright"; + // https://nodejs.org/docs/latest/api/util.html#background-colors + type BackgroundColors = + | "bgBlack" + | "bgBlackBright" + | "bgBlue" + | "bgBlueBright" + | "bgCyan" + | "bgCyanBright" + | "bgGray" + | "bgGreen" + | "bgGreenBright" + | "bgGrey" + | "bgMagenta" + | "bgMagentaBright" + | "bgRed" + | "bgRedBright" + | "bgWhite" + | "bgWhiteBright" + | "bgYellow" + | "bgYellowBright"; + // https://nodejs.org/docs/latest/api/util.html#modifiers + type Modifiers = + | "blink" + | "bold" + | "dim" + | "doubleunderline" + | "framed" + | "hidden" + | "inverse" + | "italic" + | "none" + | "overlined" + | "reset" + | "strikethrough" + | "underline"; + export interface StyleTextOptions { + /** + * When true, `stream` is checked to see if it can handle colors. + * @default true + */ + validateStream?: boolean | undefined; + /** + * A stream that will be validated if it can be colored. + * @default process.stdout + */ + stream?: NodeJS.WritableStream | undefined; + } + /** + * This function returns a formatted text considering the `format` passed + * for printing in a terminal. It is aware of the terminal's capabilities + * and acts according to the configuration set via `NO_COLOR`, + * `NODE_DISABLE_COLORS` and `FORCE_COLOR` environment variables. + * + * ```js + * import { styleText } from 'node:util'; + * import { stderr } from 'node:process'; + * + * const successMessage = styleText('green', 'Success!'); + * console.log(successMessage); + * + * const errorMessage = styleText( + * 'red', + * 'Error! Error!', + * // Validate if process.stderr has TTY + * { stream: stderr }, + * ); + * console.error(errorMessage); + * ``` + * + * `util.inspect.colors` also provides text formats such as `italic`, and + * `underline` and you can combine both: + * + * ```js + * console.log( + * util.styleText(['underline', 'italic'], 'My italic underlined message'), + * ); + * ``` + * + * When passing an array of formats, the order of the format applied + * is left to right so the following style might overwrite the previous one. + * + * ```js + * console.log( + * util.styleText(['red', 'green'], 'text'), // green + * ); + * ``` + * + * The special format value `none` applies no additional styling to the text. + * + * The full list of formats can be found in [modifiers](https://nodejs.org/docs/latest-v22.x/api/util.html#modifiers). + * @param format A text format or an Array of text formats defined in `util.inspect.colors`. + * @param text The text to to be formatted. + * @since v20.12.0 + */ + export function styleText( + format: + | ForegroundColors + | BackgroundColors + | Modifiers + | Array, + text: string, + options?: StyleTextOptions, + ): string; + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. + * + * ```js + * const decoder = new TextDecoder(); + * const u8arr = new Uint8Array([72, 101, 108, 108, 111]); + * console.log(decoder.decode(u8arr)); // Hello + * ``` + * @since v8.3.0 + */ + export class TextDecoder { + /** + * The encoding supported by the `TextDecoder` instance. + */ + readonly encoding: string; + /** + * The value will be `true` if decoding errors result in a `TypeError` being + * thrown. + */ + readonly fatal: boolean; + /** + * The value will be `true` if the decoding result will include the byte order + * mark. + */ + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { + fatal?: boolean | undefined; + ignoreBOM?: boolean | undefined; + }, + ); + /** + * Decodes the `input` and returns a string. If `options.stream` is `true`, any + * incomplete byte sequences occurring at the end of the `input` are buffered + * internally and emitted after the next call to `textDecoder.decode()`. + * + * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a `TypeError` being thrown. + * @param input An `ArrayBuffer`, `DataView`, or `TypedArray` instance containing the encoded data. + */ + decode( + input?: NodeJS.ArrayBufferView | ArrayBuffer | null, + options?: { + stream?: boolean | undefined; + }, + ): string; + } + export interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; + } + export { types }; + + //// TextEncoder/Decoder + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All + * instances of `TextEncoder` only support UTF-8 encoding. + * + * ```js + * const encoder = new TextEncoder(); + * const uint8array = encoder.encode('this is some data'); + * ``` + * + * The `TextEncoder` class is also available on the global object. + * @since v8.3.0 + */ + export class TextEncoder { + /** + * The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. + */ + readonly encoding: string; + /** + * UTF-8 encodes the `input` string and returns a `Uint8Array` containing the + * encoded bytes. + * @param [input='an empty string'] The text to encode. + */ + encode(input?: string): NodeJS.NonSharedUint8Array; + /** + * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object + * containing the read Unicode code units and written UTF-8 bytes. + * + * ```js + * const encoder = new TextEncoder(); + * const src = 'this is some data'; + * const dest = new Uint8Array(10); + * const { read, written } = encoder.encodeInto(src, dest); + * ``` + * @param src The text to encode. + * @param dest The array to hold the encode result. + */ + encodeInto(src: string, dest: Uint8Array): EncodeIntoResult; + } + import { TextDecoder as _TextDecoder, TextEncoder as _TextEncoder } from "util"; + global { + /** + * `TextDecoder` class is a global reference for `import { TextDecoder } from 'node:util'` + * https://nodejs.org/api/globals.html#textdecoder + * @since v11.0.0 + */ + var TextDecoder: typeof globalThis extends { + onmessage: any; + TextDecoder: infer TextDecoder; + } ? TextDecoder + : typeof _TextDecoder; + /** + * `TextEncoder` class is a global reference for `import { TextEncoder } from 'node:util'` + * https://nodejs.org/api/globals.html#textencoder + * @since v11.0.0 + */ + var TextEncoder: typeof globalThis extends { + onmessage: any; + TextEncoder: infer TextEncoder; + } ? TextEncoder + : typeof _TextEncoder; + } + + //// parseArgs + /** + * Provides a higher level API for command-line argument parsing than interacting + * with `process.argv` directly. Takes a specification for the expected arguments + * and returns a structured object with the parsed options and positionals. + * + * ```js + * import { parseArgs } from 'node:util'; + * const args = ['-f', '--bar', 'b']; + * const options = { + * foo: { + * type: 'boolean', + * short: 'f', + * }, + * bar: { + * type: 'string', + * }, + * }; + * const { + * values, + * positionals, + * } = parseArgs({ args, options }); + * console.log(values, positionals); + * // Prints: [Object: null prototype] { foo: true, bar: 'b' } [] + * ``` + * @since v18.3.0, v16.17.0 + * @param config Used to provide arguments for parsing and to configure the parser. `config` supports the following properties: + * @return The parsed command line arguments: + */ + export function parseArgs(config?: T): ParsedResults; + + /** + * Type of argument used in {@link parseArgs}. + */ + export type ParseArgsOptionsType = "boolean" | "string"; + + export interface ParseArgsOptionDescriptor { + /** + * Type of argument. + */ + type: ParseArgsOptionsType; + /** + * Whether this option can be provided multiple times. + * If `true`, all values will be collected in an array. + * If `false`, values for the option are last-wins. + * @default false. + */ + multiple?: boolean | undefined; + /** + * A single character alias for the option. + */ + short?: string | undefined; + /** + * The value to assign to + * the option if it does not appear in the arguments to be parsed. The value + * must match the type specified by the `type` property. If `multiple` is + * `true`, it must be an array. No default value is applied when the option + * does appear in the arguments to be parsed, even if the provided value + * is falsy. + * @since v18.11.0 + */ + default?: string | boolean | string[] | boolean[] | undefined; + } + export interface ParseArgsOptionsConfig { + [longOption: string]: ParseArgsOptionDescriptor; + } + export interface ParseArgsConfig { + /** + * Array of argument strings. + */ + args?: readonly string[] | undefined; + /** + * Used to describe arguments known to the parser. + */ + options?: ParseArgsOptionsConfig | undefined; + /** + * Should an error be thrown when unknown arguments are encountered, + * or when arguments are passed that do not match the `type` configured in `options`. + * @default true + */ + strict?: boolean | undefined; + /** + * Whether this command accepts positional arguments. + */ + allowPositionals?: boolean | undefined; + /** + * If `true`, allows explicitly setting boolean options to `false` by prefixing the option name with `--no-`. + * @default false + * @since v22.4.0 + */ + allowNegative?: boolean | undefined; + /** + * Return the parsed tokens. This is useful for extending the built-in behavior, + * from adding additional checks through to reprocessing the tokens in different ways. + * @default false + */ + tokens?: boolean | undefined; + } + /* + IfDefaultsTrue and IfDefaultsFalse are helpers to handle default values for missing boolean properties. + TypeScript does not have exact types for objects: https://github.com/microsoft/TypeScript/issues/12936 + This means it is impossible to distinguish between "field X is definitely not present" and "field X may or may not be present". + But we expect users to generally provide their config inline or `as const`, which means TS will always know whether a given field is present. + So this helper treats "not definitely present" (i.e., not `extends boolean`) as being "definitely not present", i.e. it should have its default value. + This is technically incorrect but is a much nicer UX for the common case. + The IfDefaultsTrue version is for things which default to true; the IfDefaultsFalse version is for things which default to false. + */ + type IfDefaultsTrue = T extends true ? IfTrue + : T extends false ? IfFalse + : IfTrue; + + // we put the `extends false` condition first here because `undefined` compares like `any` when `strictNullChecks: false` + type IfDefaultsFalse = T extends false ? IfFalse + : T extends true ? IfTrue + : IfFalse; + + type ExtractOptionValue = IfDefaultsTrue< + T["strict"], + O["type"] extends "string" ? string : O["type"] extends "boolean" ? boolean : string | boolean, + string | boolean + >; + + type ApplyOptionalModifiers> = ( + & { -readonly [LongOption in keyof O]?: V[LongOption] } + & { [LongOption in keyof O as O[LongOption]["default"] extends {} ? LongOption : never]: V[LongOption] } + ) extends infer P ? { [K in keyof P]: P[K] } : never; // resolve intersection to object + + type ParsedValues = + & IfDefaultsTrue + & (T["options"] extends ParseArgsOptionsConfig ? ApplyOptionalModifiers< + T["options"], + { + [LongOption in keyof T["options"]]: IfDefaultsFalse< + T["options"][LongOption]["multiple"], + Array>, + ExtractOptionValue + >; + } + > + : {}); + + type ParsedPositionals = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type PreciseTokenForOptions< + K extends string, + O extends ParseArgsOptionDescriptor, + > = O["type"] extends "string" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: string; + inlineValue: boolean; + } + : O["type"] extends "boolean" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: undefined; + inlineValue: undefined; + } + : OptionToken & { name: K }; + + type TokenForOptions< + T extends ParseArgsConfig, + K extends keyof T["options"] = keyof T["options"], + > = K extends unknown + ? T["options"] extends ParseArgsOptionsConfig ? PreciseTokenForOptions + : OptionToken + : never; + + type ParsedOptionToken = IfDefaultsTrue, OptionToken>; + + type ParsedPositionalToken = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type ParsedTokens = Array< + ParsedOptionToken | ParsedPositionalToken | { kind: "option-terminator"; index: number } + >; + + type PreciseParsedResults = IfDefaultsFalse< + T["tokens"], + { + values: ParsedValues; + positionals: ParsedPositionals; + tokens: ParsedTokens; + }, + { + values: ParsedValues; + positionals: ParsedPositionals; + } + >; + + type OptionToken = + | { kind: "option"; index: number; name: string; rawName: string; value: string; inlineValue: boolean } + | { + kind: "option"; + index: number; + name: string; + rawName: string; + value: undefined; + inlineValue: undefined; + }; + + type Token = + | OptionToken + | { kind: "positional"; index: number; value: string } + | { kind: "option-terminator"; index: number }; + + // If ParseArgsConfig extends T, then the user passed config constructed elsewhere. + // So we can't rely on the `"not definitely present" implies "definitely not present"` assumption mentioned above. + type ParsedResults = ParseArgsConfig extends T ? { + values: { + [longOption: string]: undefined | string | boolean | Array; + }; + positionals: string[]; + tokens?: Token[]; + } + : PreciseParsedResults; + + /** + * An implementation of [the MIMEType class](https://bmeck.github.io/node-proposal-mime-api/). + * + * In accordance with browser conventions, all properties of `MIMEType` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. + * + * A MIME string is a structured string containing multiple meaningful + * components. When parsed, a `MIMEType` object is returned containing + * properties for each of these components. + * @since v19.1.0, v18.13.0 + */ + export class MIMEType { + /** + * Creates a new MIMEType object by parsing the input. + * + * A `TypeError` will be thrown if the `input` is not a valid MIME. + * Note that an effort will be made to coerce the given values into strings. + * @param input The input MIME to parse. + */ + constructor(input: string | { toString: () => string }); + + /** + * Gets and sets the type portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript'); + * console.log(myMIME.type); + * // Prints: text + * myMIME.type = 'application'; + * console.log(myMIME.type); + * // Prints: application + * console.log(String(myMIME)); + * // Prints: application/javascript + * ``` + */ + type: string; + /** + * Gets and sets the subtype portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/ecmascript'); + * console.log(myMIME.subtype); + * // Prints: ecmascript + * myMIME.subtype = 'javascript'; + * console.log(myMIME.subtype); + * // Prints: javascript + * console.log(String(myMIME)); + * // Prints: text/javascript + * ``` + */ + subtype: string; + /** + * Gets the essence of the MIME. This property is read only. + * Use `mime.type` or `mime.subtype` to alter the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript;key=value'); + * console.log(myMIME.essence); + * // Prints: text/javascript + * myMIME.type = 'application'; + * console.log(myMIME.essence); + * // Prints: application/javascript + * console.log(String(myMIME)); + * // Prints: application/javascript;key=value + * ``` + */ + readonly essence: string; + /** + * Gets the `MIMEParams` object representing the + * parameters of the MIME. This property is read-only. See `MIMEParams` documentation for details. + */ + readonly params: MIMEParams; + /** + * The `toString()` method on the `MIMEType` object returns the serialized MIME. + * + * Because of the need for standard compliance, this method does not allow users + * to customize the serialization process of the MIME. + */ + toString(): string; + } + /** + * The `MIMEParams` API provides read and write access to the parameters of a `MIMEType`. + * @since v19.1.0, v18.13.0 + */ + export class MIMEParams { + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: string): void; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + * Each item of the iterator is a JavaScript `Array`. The first item of the array + * is the `name`, the second item of the array is the `value`. + */ + entries(): NodeJS.Iterator<[name: string, value: string]>; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: string): boolean; + /** + * Returns an iterator over the names of each name-value pair. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // bar + * ``` + */ + keys(): NodeJS.Iterator; + /** + * Sets the value in the `MIMEParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value`. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * params.set('foo', 'def'); + * params.set('baz', 'xyz'); + * console.log(params.toString()); + * // Prints: foo=def;bar=1;baz=xyz + * ``` + */ + set(name: string, value: string): void; + /** + * Returns an iterator over the values of each name-value pair. + */ + values(): NodeJS.Iterator; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + */ + [Symbol.iterator](): NodeJS.Iterator<[name: string, value: string]>; + } +} +declare module "util/types" { + import { KeyObject, webcrypto } from "node:crypto"; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or + * [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * + * See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`. + * + * ```js + * util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isAnyArrayBuffer(object: unknown): object is ArrayBufferLike; + /** + * Returns `true` if the value is an `arguments` object. + * + * ```js + * function foo() { + * util.types.isArgumentsObject(arguments); // Returns true + * } + * ``` + * @since v10.0.0 + */ + function isArgumentsObject(object: unknown): object is IArguments; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance. + * This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false + * ``` + * @since v10.0.0 + */ + function isArrayBuffer(object: unknown): object is ArrayBuffer; + /** + * Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) views, such as typed + * array objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent to + * [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * + * ```js + * util.types.isArrayBufferView(new Int8Array()); // true + * util.types.isArrayBufferView(Buffer.from('hello world')); // true + * util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true + * util.types.isArrayBufferView(new ArrayBuffer()); // false + * ``` + * @since v10.0.0 + */ + function isArrayBufferView(object: unknown): object is NodeJS.ArrayBufferView; + /** + * Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isAsyncFunction(function foo() {}); // Returns false + * util.types.isAsyncFunction(async function foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isAsyncFunction(object: unknown): boolean; + /** + * Returns `true` if the value is a `BigInt64Array` instance. + * + * ```js + * util.types.isBigInt64Array(new BigInt64Array()); // Returns true + * util.types.isBigInt64Array(new BigUint64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isBigInt64Array(value: unknown): value is BigInt64Array; + /** + * Returns `true` if the value is a BigInt object, e.g. created + * by `Object(BigInt(123))`. + * + * ```js + * util.types.isBigIntObject(Object(BigInt(123))); // Returns true + * util.types.isBigIntObject(BigInt(123)); // Returns false + * util.types.isBigIntObject(123); // Returns false + * ``` + * @since v10.4.0 + */ + function isBigIntObject(object: unknown): object is BigInt; + /** + * Returns `true` if the value is a `BigUint64Array` instance. + * + * ```js + * util.types.isBigUint64Array(new BigInt64Array()); // Returns false + * util.types.isBigUint64Array(new BigUint64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isBigUint64Array(value: unknown): value is BigUint64Array; + /** + * Returns `true` if the value is a boolean object, e.g. created + * by `new Boolean()`. + * + * ```js + * util.types.isBooleanObject(false); // Returns false + * util.types.isBooleanObject(true); // Returns false + * util.types.isBooleanObject(new Boolean(false)); // Returns true + * util.types.isBooleanObject(new Boolean(true)); // Returns true + * util.types.isBooleanObject(Boolean(false)); // Returns false + * util.types.isBooleanObject(Boolean(true)); // Returns false + * ``` + * @since v10.0.0 + */ + function isBooleanObject(object: unknown): object is Boolean; + /** + * Returns `true` if the value is any boxed primitive object, e.g. created + * by `new Boolean()`, `new String()` or `Object(Symbol())`. + * + * For example: + * + * ```js + * util.types.isBoxedPrimitive(false); // Returns false + * util.types.isBoxedPrimitive(new Boolean(false)); // Returns true + * util.types.isBoxedPrimitive(Symbol('foo')); // Returns false + * util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true + * util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true + * ``` + * @since v10.11.0 + */ + function isBoxedPrimitive(object: unknown): object is String | Number | BigInt | Boolean | Symbol; + /** + * Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance. + * + * ```js + * const ab = new ArrayBuffer(20); + * util.types.isDataView(new DataView(ab)); // Returns true + * util.types.isDataView(new Float64Array()); // Returns false + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isDataView(object: unknown): object is DataView; + /** + * Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance. + * + * ```js + * util.types.isDate(new Date()); // Returns true + * ``` + * @since v10.0.0 + */ + function isDate(object: unknown): object is Date; + /** + * Returns `true` if the value is a native `External` value. + * + * A native `External` value is a special type of object that contains a + * raw C++ pointer (`void*`) for access from native code, and has no other + * properties. Such objects are created either by Node.js internals or native + * addons. In JavaScript, they are + * [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a + * `null` prototype. + * + * ```c + * #include + * #include + * napi_value result; + * static napi_value MyNapi(napi_env env, napi_callback_info info) { + * int* raw = (int*) malloc(1024); + * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); + * if (status != napi_ok) { + * napi_throw_error(env, NULL, "napi_create_external failed"); + * return NULL; + * } + * return result; + * } + * ... + * DECLARE_NAPI_PROPERTY("myNapi", MyNapi) + * ... + * ``` + * + * ```js + * import native from 'napi_addon.node'; + * import { types } from 'node:util'; + * + * const data = native.myNapi(); + * types.isExternal(data); // returns true + * types.isExternal(0); // returns false + * types.isExternal(new String('foo')); // returns false + * ``` + * + * For further information on `napi_create_external`, refer to + * [`napi_create_external()`](https://nodejs.org/docs/latest-v22.x/api/n-api.html#napi_create_external). + * @since v10.0.0 + */ + function isExternal(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in `Float16Array` instance. + * + * ```js + * util.types.isFloat16Array(new ArrayBuffer()); // Returns false + * util.types.isFloat16Array(new Float16Array()); // Returns true + * util.types.isFloat16Array(new Float32Array()); // Returns false + * ``` + * @since v22.16.0 + */ + // This does NOT return a type predicate in v22.x. + // The Float16Array feature does not yet exist in this version of Node.js. + function isFloat16Array(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance. + * + * ```js + * util.types.isFloat32Array(new ArrayBuffer()); // Returns false + * util.types.isFloat32Array(new Float32Array()); // Returns true + * util.types.isFloat32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isFloat32Array(object: unknown): object is Float32Array; + /** + * Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance. + * + * ```js + * util.types.isFloat64Array(new ArrayBuffer()); // Returns false + * util.types.isFloat64Array(new Uint8Array()); // Returns false + * util.types.isFloat64Array(new Float64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isFloat64Array(object: unknown): object is Float64Array; + /** + * Returns `true` if the value is a generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isGeneratorFunction(function foo() {}); // Returns false + * util.types.isGeneratorFunction(function* foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorFunction(object: unknown): object is GeneratorFunction; + /** + * Returns `true` if the value is a generator object as returned from a + * built-in generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * function* foo() {} + * const generator = foo(); + * util.types.isGeneratorObject(generator); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorObject(object: unknown): object is Generator; + /** + * Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance. + * + * ```js + * util.types.isInt8Array(new ArrayBuffer()); // Returns false + * util.types.isInt8Array(new Int8Array()); // Returns true + * util.types.isInt8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt8Array(object: unknown): object is Int8Array; + /** + * Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance. + * + * ```js + * util.types.isInt16Array(new ArrayBuffer()); // Returns false + * util.types.isInt16Array(new Int16Array()); // Returns true + * util.types.isInt16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt16Array(object: unknown): object is Int16Array; + /** + * Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance. + * + * ```js + * util.types.isInt32Array(new ArrayBuffer()); // Returns false + * util.types.isInt32Array(new Int32Array()); // Returns true + * util.types.isInt32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt32Array(object: unknown): object is Int32Array; + /** + * Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * util.types.isMap(new Map()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMap( + object: T | {}, + ): object is T extends ReadonlyMap ? (unknown extends T ? never : ReadonlyMap) + : Map; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * const map = new Map(); + * util.types.isMapIterator(map.keys()); // Returns true + * util.types.isMapIterator(map.values()); // Returns true + * util.types.isMapIterator(map.entries()); // Returns true + * util.types.isMapIterator(map[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMapIterator(object: unknown): boolean; + /** + * Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects). + * + * ```js + * import * as ns from './a.js'; + * + * util.types.isModuleNamespaceObject(ns); // Returns true + * ``` + * @since v10.0.0 + */ + function isModuleNamespaceObject(value: unknown): boolean; + /** + * Returns `true` if the value was returned by the constructor of a + * [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects). + * + * ```js + * console.log(util.types.isNativeError(new Error())); // true + * console.log(util.types.isNativeError(new TypeError())); // true + * console.log(util.types.isNativeError(new RangeError())); // true + * ``` + * + * Subclasses of the native error types are also native errors: + * + * ```js + * class MyError extends Error {} + * console.log(util.types.isNativeError(new MyError())); // true + * ``` + * + * A value being `instanceof` a native error class is not equivalent to `isNativeError()` + * returning `true` for that value. `isNativeError()` returns `true` for errors + * which come from a different [realm](https://tc39.es/ecma262/#realm) while `instanceof Error` returns `false` + * for these errors: + * + * ```js + * import { createContext, runInContext } from 'node:vm'; + * import { types } from 'node:util'; + * + * const context = createContext({}); + * const myError = runInContext('new Error()', context); + * console.log(types.isNativeError(myError)); // true + * console.log(myError instanceof Error); // false + * ``` + * + * Conversely, `isNativeError()` returns `false` for all objects which were not + * returned by the constructor of a native error. That includes values + * which are `instanceof` native errors: + * + * ```js + * const myError = { __proto__: Error.prototype }; + * console.log(util.types.isNativeError(myError)); // false + * console.log(myError instanceof Error); // true + * ``` + * @since v10.0.0 + */ + function isNativeError(object: unknown): object is Error; + /** + * Returns `true` if the value is a number object, e.g. created + * by `new Number()`. + * + * ```js + * util.types.isNumberObject(0); // Returns false + * util.types.isNumberObject(new Number(0)); // Returns true + * ``` + * @since v10.0.0 + */ + function isNumberObject(object: unknown): object is Number; + /** + * Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * + * ```js + * util.types.isPromise(Promise.resolve(42)); // Returns true + * ``` + * @since v10.0.0 + */ + function isPromise(object: unknown): object is Promise; + /** + * Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance. + * + * ```js + * const target = {}; + * const proxy = new Proxy(target, {}); + * util.types.isProxy(target); // Returns false + * util.types.isProxy(proxy); // Returns true + * ``` + * @since v10.0.0 + */ + function isProxy(object: unknown): boolean; + /** + * Returns `true` if the value is a regular expression object. + * + * ```js + * util.types.isRegExp(/abc/); // Returns true + * util.types.isRegExp(new RegExp('abc')); // Returns true + * ``` + * @since v10.0.0 + */ + function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * util.types.isSet(new Set()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSet( + object: T | {}, + ): object is T extends ReadonlySet ? (unknown extends T ? never : ReadonlySet) : Set; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * const set = new Set(); + * util.types.isSetIterator(set.keys()); // Returns true + * util.types.isSetIterator(set.values()); // Returns true + * util.types.isSetIterator(set.entries()); // Returns true + * util.types.isSetIterator(set[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSetIterator(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * This does _not_ include [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false + * util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSharedArrayBuffer(object: unknown): object is SharedArrayBuffer; + /** + * Returns `true` if the value is a string object, e.g. created + * by `new String()`. + * + * ```js + * util.types.isStringObject('foo'); // Returns false + * util.types.isStringObject(new String('foo')); // Returns true + * ``` + * @since v10.0.0 + */ + function isStringObject(object: unknown): object is String; + /** + * Returns `true` if the value is a symbol object, created + * by calling `Object()` on a `Symbol` primitive. + * + * ```js + * const symbol = Symbol('foo'); + * util.types.isSymbolObject(symbol); // Returns false + * util.types.isSymbolObject(Object(symbol)); // Returns true + * ``` + * @since v10.0.0 + */ + function isSymbolObject(object: unknown): object is Symbol; + /** + * Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance. + * + * ```js + * util.types.isTypedArray(new ArrayBuffer()); // Returns false + * util.types.isTypedArray(new Uint8Array()); // Returns true + * util.types.isTypedArray(new Float64Array()); // Returns true + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isTypedArray(object: unknown): object is NodeJS.TypedArray; + /** + * Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance. + * + * ```js + * util.types.isUint8Array(new ArrayBuffer()); // Returns false + * util.types.isUint8Array(new Uint8Array()); // Returns true + * util.types.isUint8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8Array(object: unknown): object is Uint8Array; + /** + * Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance. + * + * ```js + * util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false + * util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true + * util.types.isUint8ClampedArray(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8ClampedArray(object: unknown): object is Uint8ClampedArray; + /** + * Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance. + * + * ```js + * util.types.isUint16Array(new ArrayBuffer()); // Returns false + * util.types.isUint16Array(new Uint16Array()); // Returns true + * util.types.isUint16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint16Array(object: unknown): object is Uint16Array; + /** + * Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance. + * + * ```js + * util.types.isUint32Array(new ArrayBuffer()); // Returns false + * util.types.isUint32Array(new Uint32Array()); // Returns true + * util.types.isUint32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint32Array(object: unknown): object is Uint32Array; + /** + * Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance. + * + * ```js + * util.types.isWeakMap(new WeakMap()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakMap(object: unknown): object is WeakMap; + /** + * Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance. + * + * ```js + * util.types.isWeakSet(new WeakSet()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakSet(object: unknown): object is WeakSet; + /** + * Returns `true` if `value` is a `KeyObject`, `false` otherwise. + * @since v16.2.0 + */ + function isKeyObject(object: unknown): object is KeyObject; + /** + * Returns `true` if `value` is a `CryptoKey`, `false` otherwise. + * @since v16.2.0 + */ + function isCryptoKey(object: unknown): object is webcrypto.CryptoKey; +} +declare module "node:util" { + export * from "util"; +} +declare module "node:util/types" { + export * from "util/types"; +} diff --git a/node_modules/@types/node/v8.d.ts b/node_modules/@types/node/v8.d.ts new file mode 100644 index 0000000..34006cd --- /dev/null +++ b/node_modules/@types/node/v8.d.ts @@ -0,0 +1,920 @@ +/** + * The `node:v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: + * + * ```js + * import v8 from 'node:v8'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/v8.js) + */ +declare module "v8" { + import { NonSharedBuffer } from "node:buffer"; + import { Readable } from "node:stream"; + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + number_of_native_contexts: number; + number_of_detached_contexts: number; + total_global_handles_size: number; + used_global_handles_size: number; + external_memory: number; + } + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + interface HeapSnapshotOptions { + /** + * If true, expose internals in the heap snapshot. + * @default false + */ + exposeInternals?: boolean | undefined; + /** + * If true, expose numeric values in artificial fields. + * @default false + */ + exposeNumericValues?: boolean | undefined; + } + /** + * Returns an integer representing a version tag derived from the V8 version, + * command-line flags, and detected CPU features. This is useful for determining + * whether a `vm.Script` `cachedData` buffer is compatible with this instance + * of V8. + * + * ```js + * console.log(v8.cachedDataVersionTag()); // 3947234607 + * // The value returned by v8.cachedDataVersionTag() is derived from the V8 + * // version, command-line flags, and detected CPU features. Test that the value + * // does indeed update when flags are toggled. + * v8.setFlagsFromString('--allow_natives_syntax'); + * console.log(v8.cachedDataVersionTag()); // 183726201 + * ``` + * @since v8.0.0 + */ + function cachedDataVersionTag(): number; + /** + * Returns an object with the following properties: + * + * `does_zap_garbage` is a 0/1 boolean, which signifies whether the `--zap_code_space` option is enabled or not. This makes V8 overwrite heap + * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger + * because it continuously touches all heap pages and that makes them less likely + * to get swapped out by the operating system. + * + * `number_of_native_contexts` The value of native\_context is the number of the + * top-level contexts currently active. Increase of this number over time indicates + * a memory leak. + * + * `number_of_detached_contexts` The value of detached\_context is the number + * of contexts that were detached and not yet garbage collected. This number + * being non-zero indicates a potential memory leak. + * + * `total_global_handles_size` The value of total\_global\_handles\_size is the + * total memory size of V8 global handles. + * + * `used_global_handles_size` The value of used\_global\_handles\_size is the + * used memory size of V8 global handles. + * + * `external_memory` The value of external\_memory is the memory size of array + * buffers and external strings. + * + * ```js + * { + * total_heap_size: 7326976, + * total_heap_size_executable: 4194304, + * total_physical_size: 7326976, + * total_available_size: 1152656, + * used_heap_size: 3476208, + * heap_size_limit: 1535115264, + * malloced_memory: 16384, + * peak_malloced_memory: 1127496, + * does_zap_garbage: 0, + * number_of_native_contexts: 1, + * number_of_detached_contexts: 0, + * total_global_handles_size: 8192, + * used_global_handles_size: 3296, + * external_memory: 318824 + * } + * ``` + * @since v1.0.0 + */ + function getHeapStatistics(): HeapInfo; + /** + * It returns an object with a structure similar to the + * [`cppgc::HeapStatistics`](https://v8docs.nodesource.com/node-22.4/d7/d51/heap-statistics_8h_source.html) + * object. See the [V8 documentation](https://v8docs.nodesource.com/node-22.4/df/d2f/structcppgc_1_1_heap_statistics.html) + * for more information about the properties of the object. + * + * ```js + * // Detailed + * ({ + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 152, + * space_statistics: [ + * { + * name: 'NormalPageSpace0', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace1', + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 152, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace2', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace3', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'LargePageSpace', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * ], + * type_names: [], + * detail_level: 'detailed', + * }); + * ``` + * + * ```js + * // Brief + * ({ + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 128864, + * space_statistics: [], + * type_names: [], + * detail_level: 'brief', + * }); + * ``` + * @since v22.15.0 + * @param detailLevel **Default:** `'detailed'`. Specifies the level of detail in the returned statistics. + * Accepted values are: + * * `'brief'`: Brief statistics contain only the top-level + * allocated and used + * memory statistics for the entire heap. + * * `'detailed'`: Detailed statistics also contain a break + * down per space and page, as well as freelist statistics + * and object type histograms. + */ + function getCppHeapStatistics(detailLevel?: "brief" | "detailed"): object; + /** + * Returns statistics about the V8 heap spaces, i.e. the segments which make up + * the V8 heap. Neither the ordering of heap spaces, nor the availability of a + * heap space can be guaranteed as the statistics are provided via the + * V8 [`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the + * next. + * + * The value returned is an array of objects containing the following properties: + * + * ```json + * [ + * { + * "space_name": "new_space", + * "space_size": 2063872, + * "space_used_size": 951112, + * "space_available_size": 80824, + * "physical_space_size": 2063872 + * }, + * { + * "space_name": "old_space", + * "space_size": 3090560, + * "space_used_size": 2493792, + * "space_available_size": 0, + * "physical_space_size": 3090560 + * }, + * { + * "space_name": "code_space", + * "space_size": 1260160, + * "space_used_size": 644256, + * "space_available_size": 960, + * "physical_space_size": 1260160 + * }, + * { + * "space_name": "map_space", + * "space_size": 1094160, + * "space_used_size": 201608, + * "space_available_size": 0, + * "physical_space_size": 1094160 + * }, + * { + * "space_name": "large_object_space", + * "space_size": 0, + * "space_used_size": 0, + * "space_available_size": 1490980608, + * "physical_space_size": 0 + * } + * ] + * ``` + * @since v6.0.0 + */ + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + /** + * The `v8.setFlagsFromString()` method can be used to programmatically set + * V8 command-line flags. This method should be used with care. Changing settings + * after the VM has started may result in unpredictable behavior, including + * crashes and data loss; or it may simply do nothing. + * + * The V8 options available for a version of Node.js may be determined by running `node --v8-options`. + * + * Usage: + * + * ```js + * // Print GC events to stdout for one minute. + * import v8 from 'node:v8'; + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ + function setFlagsFromString(flags: string): void; + /** + * This is similar to the [`queryObjects()` console API](https://developer.chrome.com/docs/devtools/console/utilities#queryObjects-function) + * provided by the Chromium DevTools console. It can be used to search for objects that have the matching constructor on its prototype chain + * in the heap after a full garbage collection, which can be useful for memory leak regression tests. To avoid surprising results, users should + * avoid using this API on constructors whose implementation they don't control, or on constructors that can be invoked by other parties in the + * application. + * + * To avoid accidental leaks, this API does not return raw references to the objects found. By default, it returns the count of the objects + * found. If `options.format` is `'summary'`, it returns an array containing brief string representations for each object. The visibility provided + * in this API is similar to what the heap snapshot provides, while users can save the cost of serialization and parsing and directly filter the + * target objects during the search. + * + * Only objects created in the current execution context are included in the results. + * + * ```js + * import { queryObjects } from 'node:v8'; + * class A { foo = 'bar'; } + * console.log(queryObjects(A)); // 0 + * const a = new A(); + * console.log(queryObjects(A)); // 1 + * // [ "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * + * class B extends A { bar = 'qux'; } + * const b = new B(); + * console.log(queryObjects(B)); // 1 + * // [ "B { foo: 'bar', bar: 'qux' }" ] + * console.log(queryObjects(B, { format: 'summary' })); + * + * // Note that, when there are child classes inheriting from a constructor, + * // the constructor also shows up in the prototype chain of the child + * // classes's prototoype, so the child classes's prototoype would also be + * // included in the result. + * console.log(queryObjects(A)); // 3 + * // [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * ``` + * @param ctor The constructor that can be used to search on the prototype chain in order to filter target objects in the heap. + * @since v20.13.0 + * @experimental + */ + function queryObjects(ctor: Function): number | string[]; + function queryObjects(ctor: Function, options: { format: "count" }): number; + function queryObjects(ctor: Function, options: { format: "summary" }): string[]; + /** + * Generates a snapshot of the current V8 heap and returns a Readable + * Stream that may be used to read the JSON serialized representation. + * This JSON stream format is intended to be used with tools such as + * Chrome DevTools. The JSON schema is undocumented and specific to the + * V8 engine. Therefore, the schema may change from one version of V8 to the next. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * // Print heap snapshot to the console + * import v8 from 'node:v8'; + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable containing the V8 heap snapshot. + */ + function getHeapSnapshot(options?: HeapSnapshotOptions): Readable; + /** + * Generates a snapshot of the current V8 heap and writes it to a JSON + * file. This file is intended to be used with tools such as Chrome + * DevTools. The JSON schema is undocumented and specific to the V8 + * engine, and may change from one version of V8 to the next. + * + * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will + * not contain any information about the workers, and vice versa. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * import { writeHeapSnapshot } from 'node:v8'; + * import { + * Worker, + * isMainThread, + * parentPort, + * } from 'node:worker_threads'; + * + * if (isMainThread) { + * const worker = new Worker(__filename); + * + * worker.once('message', (filename) => { + * console.log(`worker heapdump: ${filename}`); + * // Now get a heapdump for the main thread. + * console.log(`main thread heapdump: ${writeHeapSnapshot()}`); + * }); + * + * // Tell the worker to create a heapdump. + * worker.postMessage('heapdump'); + * } else { + * parentPort.once('message', (message) => { + * if (message === 'heapdump') { + * // Generate a heapdump for the worker + * // and return the filename to the parent. + * parentPort.postMessage(writeHeapSnapshot()); + * } + * }); + * } + * ``` + * @since v11.13.0 + * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be + * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a + * worker thread. + * @return The filename where the snapshot was saved. + */ + function writeHeapSnapshot(filename?: string, options?: HeapSnapshotOptions): string; + /** + * Get statistics about code and its metadata in the heap, see + * V8 [`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the + * following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794, + * cpu_profiler_metadata_size: 0, + * } + * ``` + * @since v12.8.0 + */ + function getHeapCodeStatistics(): HeapCodeStatistics; + /** + * V8 only supports `Latin-1/ISO-8859-1` and `UTF16` as the underlying representation of a string. + * If the `content` uses `Latin-1/ISO-8859-1` as the underlying representation, this function will return true; + * otherwise, it returns false. + * + * If this method returns false, that does not mean that the string contains some characters not in `Latin-1/ISO-8859-1`. + * Sometimes a `Latin-1` string may also be represented as `UTF16`. + * + * ```js + * const { isStringOneByteRepresentation } = require('node:v8'); + * + * const Encoding = { + * latin1: 1, + * utf16le: 2, + * }; + * const buffer = Buffer.alloc(100); + * function writeString(input) { + * if (isStringOneByteRepresentation(input)) { + * buffer.writeUint8(Encoding.latin1); + * buffer.writeUint32LE(input.length, 1); + * buffer.write(input, 5, 'latin1'); + * } else { + * buffer.writeUint8(Encoding.utf16le); + * buffer.writeUint32LE(input.length * 2, 1); + * buffer.write(input, 5, 'utf16le'); + * } + * } + * writeString('hello'); + * writeString('你好'); + * ``` + * @since v22.15.0 + */ + function isStringOneByteRepresentation(content: string): boolean; + /** + * @since v8.0.0 + */ + class Serializer { + /** + * Writes out a header, which includes the serialization format version. + */ + writeHeader(): void; + /** + * Serializes a JavaScript value and adds the serialized representation to the + * internal buffer. + * + * This throws an error if `value` cannot be serialized. + */ + writeValue(val: any): boolean; + /** + * Returns the stored internal buffer. This serializer should not be used once + * the buffer is released. Calling this method results in undefined behavior + * if a previous write has failed. + */ + releaseBuffer(): NonSharedBuffer; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Write a raw 32-bit unsigned integer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint32(value: number): void; + /** + * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint64(hi: number, lo: number): void; + /** + * Write a JS `number` value. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeDouble(value: number): void; + /** + * Write raw bytes into the serializer's internal buffer. The deserializer + * will require a way to compute the length of the buffer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeRawBytes(buffer: NodeJS.ArrayBufferView): void; + } + /** + * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only + * stores the part of their underlying `ArrayBuffer`s that they are referring to. + * @since v8.0.0 + */ + class DefaultSerializer extends Serializer {} + /** + * @since v8.0.0 + */ + class Deserializer { + constructor(data: NodeJS.TypedArray); + /** + * Reads and validates a header (including the format version). + * May, for example, reject an invalid or unsupported wire format. In that case, + * an `Error` is thrown. + */ + readHeader(): boolean; + /** + * Deserializes a JavaScript value from the buffer and returns it. + */ + readValue(): any; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of + * `SharedArrayBuffer`s). + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Reads the underlying wire format version. Likely mostly to be useful to + * legacy code reading old wire format versions. May not be called before `.readHeader()`. + */ + getWireFormatVersion(): number; + /** + * Read a raw 32-bit unsigned integer and return it. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint32(): number; + /** + * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]` with two 32-bit unsigned integer entries. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint64(): [number, number]; + /** + * Read a JS `number` value. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readDouble(): number; + /** + * Read raw bytes from the deserializer's internal buffer. The `length` parameter + * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readRawBytes(length: number): Buffer; + } + /** + * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`. + * @since v8.0.0 + */ + class DefaultDeserializer extends Deserializer {} + /** + * Uses a `DefaultSerializer` to serialize `value` into a buffer. + * + * `ERR_BUFFER_TOO_LARGE` will be thrown when trying to + * serialize a huge object which requires buffer + * larger than `buffer.constants.MAX_LENGTH`. + * @since v8.0.0 + */ + function serialize(value: any): NonSharedBuffer; + /** + * Uses a `DefaultDeserializer` with default options to read a JS value + * from a buffer. + * @since v8.0.0 + * @param buffer A buffer returned by {@link serialize}. + */ + function deserialize(buffer: NodeJS.ArrayBufferView): any; + /** + * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple + * times during the lifetime of the process. Each time the execution counter will + * be reset and a new coverage report will be written to the directory specified + * by `NODE_V8_COVERAGE`. + * + * When the process is about to exit, one last coverage will still be written to + * disk unless {@link stopCoverage} is invoked before the process exits. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function takeCoverage(): void; + /** + * The `v8.stopCoverage()` method allows the user to stop the coverage collection + * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count + * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function stopCoverage(): void; + /** + * The API is a no-op if `--heapsnapshot-near-heap-limit` is already set from the command line or the API is called more than once. + * `limit` must be a positive integer. See [`--heapsnapshot-near-heap-limit`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--heapsnapshot-near-heap-limitmax_count) for more information. + * @since v18.10.0, v16.18.0 + */ + function setHeapSnapshotNearHeapLimit(limit: number): void; + /** + * This API collects GC data in current thread. + * @since v19.6.0, v18.15.0 + */ + class GCProfiler { + /** + * Start collecting GC data. + * @since v19.6.0, v18.15.0 + */ + start(): void; + /** + * Stop collecting GC data and return an object. The content of object + * is as follows. + * + * ```json + * { + * "version": 1, + * "startTime": 1674059033862, + * "statistics": [ + * { + * "gcType": "Scavenge", + * "beforeGC": { + * "heapStatistics": { + * "totalHeapSize": 5005312, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5226496, + * "totalAvailableSize": 4341325216, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4883840, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * }, + * "cost": 1574.14, + * "afterGC": { + * "heapStatistics": { + * "totalHeapSize": 6053888, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5500928, + * "totalAvailableSize": 4341101384, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4059096, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * } + * } + * ], + * "endTime": 1674059036865 + * } + * ``` + * + * Here's an example. + * + * ```js + * import { GCProfiler } from 'node:v8'; + * const profiler = new GCProfiler(); + * profiler.start(); + * setTimeout(() => { + * console.log(profiler.stop()); + * }, 1000); + * ``` + * @since v19.6.0, v18.15.0 + */ + stop(): GCProfilerResult; + } + interface GCProfilerResult { + version: number; + startTime: number; + endTime: number; + statistics: Array<{ + gcType: string; + cost: number; + beforeGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + afterGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + }>; + } + interface HeapStatistics { + totalHeapSize: number; + totalHeapSizeExecutable: number; + totalPhysicalSize: number; + totalAvailableSize: number; + totalGlobalHandlesSize: number; + usedGlobalHandlesSize: number; + usedHeapSize: number; + heapSizeLimit: number; + mallocedMemory: number; + externalMemory: number; + peakMallocedMemory: number; + } + interface HeapSpaceStatistics { + spaceName: string; + spaceSize: number; + spaceUsedSize: number; + spaceAvailableSize: number; + physicalSpaceSize: number; + } + /** + * Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will + * happen if a promise is created without ever getting a continuation. + * @since v17.1.0, v16.14.0 + * @param promise The promise being created. + * @param parent The promise continued from, if applicable. + */ + interface Init { + (promise: Promise, parent: Promise): void; + } + /** + * Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming. + * + * The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise. + * The before callback may be called many times in the case where many continuations have been made from the same promise. + * @since v17.1.0, v16.14.0 + */ + interface Before { + (promise: Promise): void; + } + /** + * Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await. + * @since v17.1.0, v16.14.0 + */ + interface After { + (promise: Promise): void; + } + /** + * Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or + * {@link Promise.reject()}. + * @since v17.1.0, v16.14.0 + */ + interface Settled { + (promise: Promise): void; + } + /** + * Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or + * around an await, and when the promise resolves or rejects. + * + * Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and + * `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop. + * @since v17.1.0, v16.14.0 + */ + interface HookCallbacks { + init?: Init; + before?: Before; + after?: After; + settled?: Settled; + } + interface PromiseHooks { + /** + * The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param init The {@link Init | `init` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onInit: (init: Init) => Function; + /** + * The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param settled The {@link Settled | `settled` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onSettled: (settled: Settled) => Function; + /** + * The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param before The {@link Before | `before` callback} to call before a promise continuation executes. + * @return Call to stop the hook. + */ + onBefore: (before: Before) => Function; + /** + * The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param after The {@link After | `after` callback} to call after a promise continuation executes. + * @return Call to stop the hook. + */ + onAfter: (after: After) => Function; + /** + * Registers functions to be called for different lifetime events of each promise. + * The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime. + * All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed. + * The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param callbacks The {@link HookCallbacks | Hook Callbacks} to register + * @return Used for disabling hooks + */ + createHook: (callbacks: HookCallbacks) => Function; + } + /** + * The `promiseHooks` interface can be used to track promise lifecycle events. + * @since v17.1.0, v16.14.0 + */ + const promiseHooks: PromiseHooks; + type StartupSnapshotCallbackFn = (args: any) => any; + /** + * The `v8.startupSnapshot` interface can be used to add serialization and deserialization hooks for custom startup snapshots. + * + * ```bash + * $ node --snapshot-blob snapshot.blob --build-snapshot entry.js + * # This launches a process with the snapshot + * $ node --snapshot-blob snapshot.blob + * ``` + * + * In the example above, `entry.js` can use methods from the `v8.startupSnapshot` interface to specify how to save information for custom objects + * in the snapshot during serialization and how the information can be used to synchronize these objects during deserialization of the snapshot. + * For example, if the `entry.js` contains the following script: + * + * ```js + * 'use strict'; + * + * import fs from 'node:fs'; + * import zlib from 'node:zlib'; + * import path from 'node:path'; + * import assert from 'node:assert'; + * + * import v8 from 'node:v8'; + * + * class BookShelf { + * storage = new Map(); + * + * // Reading a series of files from directory and store them into storage. + * constructor(directory, books) { + * for (const book of books) { + * this.storage.set(book, fs.readFileSync(path.join(directory, book))); + * } + * } + * + * static compressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gzipSync(content)); + * } + * } + * + * static decompressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gunzipSync(content)); + * } + * } + * } + * + * // __dirname here is where the snapshot script is placed + * // during snapshot building time. + * const shelf = new BookShelf(__dirname, [ + * 'book1.en_US.txt', + * 'book1.es_ES.txt', + * 'book2.zh_CN.txt', + * ]); + * + * assert(v8.startupSnapshot.isBuildingSnapshot()); + * // On snapshot serialization, compress the books to reduce size. + * v8.startupSnapshot.addSerializeCallback(BookShelf.compressAll, shelf); + * // On snapshot deserialization, decompress the books. + * v8.startupSnapshot.addDeserializeCallback(BookShelf.decompressAll, shelf); + * v8.startupSnapshot.setDeserializeMainFunction((shelf) => { + * // process.env and process.argv are refreshed during snapshot + * // deserialization. + * const lang = process.env.BOOK_LANG || 'en_US'; + * const book = process.argv[1]; + * const name = `${book}.${lang}.txt`; + * console.log(shelf.storage.get(name)); + * }, shelf); + * ``` + * + * The resulted binary will get print the data deserialized from the snapshot during start up, using the refreshed `process.env` and `process.argv` of the launched process: + * + * ```bash + * $ BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1 + * # Prints content of book1.es_ES.txt deserialized from the snapshot. + * ``` + * + * Currently the application deserialized from a user-land snapshot cannot be snapshotted again, so these APIs are only available to applications that are not deserialized from a user-land snapshot. + * + * @since v18.6.0, v16.17.0 + */ + namespace startupSnapshot { + /** + * Add a callback that will be called when the Node.js instance is about to get serialized into a snapshot and exit. + * This can be used to release resources that should not or cannot be serialized or to convert user data into a form more suitable for serialization. + * @since v18.6.0, v16.17.0 + */ + function addSerializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Add a callback that will be called when the Node.js instance is deserialized from a snapshot. + * The `callback` and the `data` (if provided) will be serialized into the snapshot, they can be used to re-initialize the state of the application or + * to re-acquire resources that the application needs when the application is restarted from the snapshot. + * @since v18.6.0, v16.17.0 + */ + function addDeserializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * This sets the entry point of the Node.js application when it is deserialized from a snapshot. This can be called only once in the snapshot building script. + * If called, the deserialized application no longer needs an additional entry point script to start up and will simply invoke the callback along with the deserialized + * data (if provided), otherwise an entry point script still needs to be provided to the deserialized application. + * @since v18.6.0, v16.17.0 + */ + function setDeserializeMainFunction(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Returns true if the Node.js instance is run to build a snapshot. + * @since v18.6.0, v16.17.0 + */ + function isBuildingSnapshot(): boolean; + } +} +declare module "node:v8" { + export * from "v8"; +} diff --git a/node_modules/@types/node/vm.d.ts b/node_modules/@types/node/vm.d.ts new file mode 100644 index 0000000..a2609bf --- /dev/null +++ b/node_modules/@types/node/vm.d.ts @@ -0,0 +1,1000 @@ +/** + * The `node:vm` module enables compiling and running code within V8 Virtual + * Machine contexts. + * + * **The `node:vm` module is not a security** + * **mechanism. Do not use it to run untrusted code.** + * + * JavaScript code can be compiled and run immediately or + * compiled, saved, and run later. + * + * A common use case is to run the code in a different V8 Context. This means + * invoked code has a different global object than the invoking code. + * + * One can provide the context by `contextifying` an + * object. The invoked code treats any property in the context like a + * global variable. Any changes to global variables caused by the invoked + * code are reflected in the context object. + * + * ```js + * import vm from 'node:vm'; + * + * const x = 1; + * + * const context = { x: 2 }; + * vm.createContext(context); // Contextify the object. + * + * const code = 'x += 40; var y = 17;'; + * // `x` and `y` are global variables in the context. + * // Initially, x has the value 2 because that is the value of context.x. + * vm.runInContext(code, context); + * + * console.log(context.x); // 42 + * console.log(context.y); // 17 + * + * console.log(x); // 1; y is not defined. + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/vm.js) + */ +declare module "vm" { + import { NonSharedBuffer } from "node:buffer"; + import { ImportAttributes } from "node:module"; + interface Context extends NodeJS.Dict {} + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * @default '' + */ + filename?: string | undefined; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + lineOffset?: number | undefined; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + columnOffset?: number | undefined; + } + type DynamicModuleLoader = ( + specifier: string, + referrer: T, + importAttributes: ImportAttributes, + ) => Module | Promise; + interface ScriptOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: NodeJS.ArrayBufferView | undefined; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean | undefined; + /** + * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is + * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see + * [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v22.x/api/vm.html#support-of-dynamic-import-in-compilation-apis). + */ + importModuleDynamically?: + | DynamicModuleLoader` + ].join("") + result2.join(""); + return { value: html2, size: html2.length }; + }); + return { html, pageId: snapshot3.pageId, frameId: snapshot3.frameId, index: this._index }; + } + resourceByUrl(url2, method) { + const snapshot3 = this._snapshot; + let sameFrameResource; + let otherFrameResource; + for (const resource of this._resources) { + if (typeof resource._monotonicTime === "number" && resource._monotonicTime >= snapshot3.timestamp) + break; + if (resource.response.status === 304) { + continue; + } + if (resource.request.url === url2 && resource.request.method === method) { + if (resource._frameref === snapshot3.frameId) + sameFrameResource = resource; + else + otherFrameResource = resource; + } + } + let result2 = sameFrameResource ?? otherFrameResource; + if (result2 && method.toUpperCase() === "GET") { + let override = snapshot3.resourceOverrides.find((o) => o.url === url2); + if (override?.ref) { + const index = this._index - override.ref; + if (index >= 0 && index < this._snapshots.length) + override = this._snapshots[index].resourceOverrides.find((o) => o.url === url2); + } + if (override?.sha1) { + result2 = { + ...result2, + response: { + ...result2.response, + content: { + ...result2.response.content, + _sha1: override.sha1 + } + } + }; + } + } + return result2; + } + }; + autoClosing = /* @__PURE__ */ new Set(["AREA", "BASE", "BR", "COL", "COMMAND", "EMBED", "HR", "IMG", "INPUT", "KEYGEN", "LINK", "MENUITEM", "META", "PARAM", "SOURCE", "TRACK", "WBR"]); + kAllowedMetaHttpEquivs = /* @__PURE__ */ new Set(["content-type", "content-language", "default-style", "x-ua-compatible"]); + schemas = ["about:", "blob:", "data:", "file:", "ftp:", "http:", "https:", "mailto:", "sftp:", "ws:", "wss:"]; + kLegacyBlobPrefix = "http://playwright.bloburl/#"; + urlInCSSRegex = /url\(['"]?([\w-]+:)\/\//ig; + urlToEscapeRegex1 = /url\(\s*'([^']*)'\s*\)/ig; + urlToEscapeRegex2 = /url\(\s*"([^"]*)"\s*\)/ig; + blankSnapshotUrl = "data:text/html;base64," + btoa(``); + } +}); + +// packages/isomorphic/lruCache.ts +var LRUCache; +var init_lruCache = __esm({ + "packages/isomorphic/lruCache.ts"() { + "use strict"; + LRUCache = class { + constructor(maxSize) { + this._maxSize = maxSize; + this._map = /* @__PURE__ */ new Map(); + this._size = 0; + } + getOrCompute(key, compute) { + if (this._map.has(key)) { + const result3 = this._map.get(key); + this._map.delete(key); + this._map.set(key, result3); + return result3.value; + } + const result2 = compute(); + while (this._map.size && this._size + result2.size > this._maxSize) { + const [firstKey, firstValue] = this._map.entries().next().value; + this._size -= firstValue.size; + this._map.delete(firstKey); + } + this._map.set(key, result2); + this._size += result2.size; + return result2.value; + } + }; + } +}); + +// packages/isomorphic/trace/snapshotStorage.ts +var SnapshotStorage; +var init_snapshotStorage = __esm({ + "packages/isomorphic/trace/snapshotStorage.ts"() { + "use strict"; + init_snapshotRenderer(); + init_lruCache(); + SnapshotStorage = class { + constructor() { + this._frameSnapshots = /* @__PURE__ */ new Map(); + this._cache = new LRUCache(1e8); + // 100MB per each trace + this._contextToResources = /* @__PURE__ */ new Map(); + this._resourceUrlsWithOverrides = /* @__PURE__ */ new Set(); + } + addResource(contextId4, resource) { + resource.request.url = rewriteURLForCustomProtocol(resource.request.url); + this._ensureResourcesForContext(contextId4).push(resource); + } + addFrameSnapshot(contextId4, snapshot3, screencastFrames) { + for (const override of snapshot3.resourceOverrides) + override.url = rewriteURLForCustomProtocol(override.url); + let frameSnapshots = this._frameSnapshots.get(snapshot3.frameId); + if (!frameSnapshots) { + frameSnapshots = { + raw: [], + renderers: [] + }; + this._frameSnapshots.set(snapshot3.frameId, frameSnapshots); + if (snapshot3.isMainFrame) + this._frameSnapshots.set(snapshot3.pageId, frameSnapshots); + } + frameSnapshots.raw.push(snapshot3); + const resources = this._ensureResourcesForContext(contextId4); + const renderer = new SnapshotRenderer(this._cache, resources, frameSnapshots.raw, screencastFrames, frameSnapshots.raw.length - 1); + frameSnapshots.renderers.push(renderer); + return renderer; + } + snapshotByName(pageOrFrameId, snapshotName) { + const snapshot3 = this._frameSnapshots.get(pageOrFrameId); + return snapshot3?.renderers.find((r) => r.snapshotName === snapshotName); + } + snapshotsForTest() { + return [...this._frameSnapshots.keys()]; + } + finalize() { + for (const resources of this._contextToResources.values()) + resources.sort((a, b) => (a._monotonicTime || 0) - (b._monotonicTime || 0)); + for (const frameSnapshots of this._frameSnapshots.values()) { + for (const snapshot3 of frameSnapshots.raw) { + for (const override of snapshot3.resourceOverrides) + this._resourceUrlsWithOverrides.add(override.url); + } + } + } + hasResourceOverride(url2) { + return this._resourceUrlsWithOverrides.has(url2); + } + _ensureResourcesForContext(contextId4) { + let resources = this._contextToResources.get(contextId4); + if (!resources) { + resources = []; + this._contextToResources.set(contextId4, resources); + } + return resources; + } + }; + } +}); + +// packages/isomorphic/trace/traceUtils.ts +function parseClientSideCallMetadata(data) { + const result2 = /* @__PURE__ */ new Map(); + const { files, stacks } = data; + for (const s of stacks) { + const [id, ff] = s; + result2.set(`call@${id}`, ff.map((f) => ({ file: files[f[0]], line: f[1], column: f[2], function: f[3] }))); + } + return result2; +} +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 }; +} +var init_traceUtils = __esm({ + "packages/isomorphic/trace/traceUtils.ts"() { + "use strict"; + } +}); + +// packages/isomorphic/trace/traceModernizer.ts +var TraceVersionError, latestVersion, TraceModernizer; +var init_traceModernizer = __esm({ + "packages/isomorphic/trace/traceModernizer.ts"() { + "use strict"; + TraceVersionError = class extends Error { + constructor(message) { + super(message); + this.name = "TraceVersionError"; + } + }; + latestVersion = 8; + TraceModernizer = class { + constructor(contextEntry, snapshotStorage) { + this._actionMap = /* @__PURE__ */ new Map(); + this._pageEntries = /* @__PURE__ */ new Map(); + this._jsHandles = /* @__PURE__ */ new Map(); + this._consoleObjects = /* @__PURE__ */ new Map(); + this._contextEntry = contextEntry; + this._snapshotStorage = snapshotStorage; + } + appendTrace(trace) { + for (const line of trace.split("\n")) + this._appendEvent(line); + } + actions() { + return [...this._actionMap.values()]; + } + _pageEntry(pageId4) { + let pageEntry = this._pageEntries.get(pageId4); + if (!pageEntry) { + pageEntry = { + pageId: pageId4, + screencastFrames: [] + }; + this._pageEntries.set(pageId4, pageEntry); + this._contextEntry.pages.push(pageEntry); + } + return pageEntry; + } + _appendEvent(line) { + if (!line) + return; + const events = this._modernize(JSON.parse(line)); + for (const event of events) + this._innerAppendEvent(event); + } + _innerAppendEvent(event) { + const contextEntry = this._contextEntry; + switch (event.type) { + case "context-options": { + if (event.version > latestVersion) + throw new TraceVersionError("The trace was created by a newer version of Playwright and is not supported by this version of the viewer. Please use latest Playwright to open the trace."); + this._version = event.version; + contextEntry.origin = event.origin; + contextEntry.browserName = event.browserName; + contextEntry.channel = event.channel; + contextEntry.title = event.title; + contextEntry.platform = event.platform; + contextEntry.playwrightVersion = event.playwrightVersion; + contextEntry.wallTime = event.wallTime; + contextEntry.startTime = event.monotonicTime; + contextEntry.sdkLanguage = event.sdkLanguage; + contextEntry.options = event.options; + contextEntry.testIdAttributeName = event.testIdAttributeName; + contextEntry.contextId = event.contextId ?? ""; + contextEntry.testTimeout = event.testTimeout; + break; + } + case "screencast-frame": { + this._pageEntry(event.pageId).screencastFrames.push(event); + break; + } + case "before": { + this._actionMap.set(event.callId, { ...event, type: "action", endTime: 0, log: [] }); + break; + } + case "input": { + const existing = this._actionMap.get(event.callId); + existing.inputSnapshot = event.inputSnapshot; + existing.point = event.point; + break; + } + case "log": { + const existing = this._actionMap.get(event.callId); + if (!existing) + return; + existing.log.push({ + time: event.time, + message: event.message + }); + break; + } + case "after": { + const existing = this._actionMap.get(event.callId); + existing.afterSnapshot = event.afterSnapshot; + existing.endTime = event.endTime; + existing.result = event.result; + existing.error = event.error; + existing.attachments = event.attachments; + existing.annotations = event.annotations; + if (event.point) + existing.point = event.point; + break; + } + case "action": { + this._actionMap.set(event.callId, { ...event, log: [] }); + break; + } + case "event": { + contextEntry.events.push(event); + break; + } + case "stdout": { + contextEntry.stdio.push(event); + break; + } + case "stderr": { + contextEntry.stdio.push(event); + break; + } + case "error": { + contextEntry.errors.push(event); + break; + } + case "console": { + contextEntry.events.push(event); + break; + } + case "resource-snapshot": + this._snapshotStorage.addResource(this._contextEntry.contextId, event.snapshot); + contextEntry.resources.push(event.snapshot); + break; + case "frame-snapshot": + this._snapshotStorage.addFrameSnapshot(this._contextEntry.contextId, event.snapshot, this._pageEntry(event.snapshot.pageId).screencastFrames); + break; + } + if ("pageId" in event && event.pageId) + this._pageEntry(event.pageId); + if (event.type === "action" || event.type === "before") + contextEntry.startTime = Math.min(contextEntry.startTime, event.startTime); + if (event.type === "action" || event.type === "after") + contextEntry.endTime = Math.max(contextEntry.endTime, event.endTime); + if (event.type === "event") { + contextEntry.startTime = Math.min(contextEntry.startTime, event.time); + contextEntry.endTime = Math.max(contextEntry.endTime, event.time); + } + if (event.type === "screencast-frame") { + contextEntry.startTime = Math.min(contextEntry.startTime, event.timestamp); + contextEntry.endTime = Math.max(contextEntry.endTime, event.timestamp); + } + } + _processedContextCreatedEvent() { + return this._version !== void 0; + } + _modernize(event) { + let version3 = this._version ?? event.version ?? 6; + let events = [event]; + for (; version3 < latestVersion; ++version3) + events = this[`_modernize_${version3}_to_${version3 + 1}`].call(this, events); + return events; + } + _modernize_0_to_1(events) { + for (const event of events) { + if (event.type !== "action") + continue; + if (typeof event.metadata.error === "string") + event.metadata.error = { error: { name: "Error", message: event.metadata.error } }; + } + return events; + } + _modernize_1_to_2(events) { + for (const event of events) { + if (event.type !== "frame-snapshot" || !event.snapshot.isMainFrame) + continue; + event.snapshot.viewport = this._contextEntry.options?.viewport || { width: 1280, height: 720 }; + } + return events; + } + _modernize_2_to_3(events) { + for (const event of events) { + if (event.type !== "resource-snapshot" || event.snapshot.request) + continue; + const resource = event.snapshot; + event.snapshot = { + _frameref: resource.frameId, + request: { + url: resource.url, + method: resource.method, + headers: resource.requestHeaders, + postData: resource.requestSha1 ? { _sha1: resource.requestSha1 } : void 0 + }, + response: { + status: resource.status, + headers: resource.responseHeaders, + content: { + mimeType: resource.contentType, + _sha1: resource.responseSha1 + } + }, + _monotonicTime: resource.timestamp + }; + } + return events; + } + _modernize_3_to_4(events) { + const result2 = []; + for (const event of events) { + const e = this._modernize_event_3_to_4(event); + if (e) + result2.push(e); + } + return result2; + } + _modernize_event_3_to_4(event) { + if (event.type !== "action" && event.type !== "event") { + return event; + } + const metadata = event.metadata; + if (metadata.internal || metadata.method.startsWith("tracing")) + return null; + if (event.type === "event") { + if (metadata.method === "__create__" && metadata.type === "ConsoleMessage") { + return { + type: "object", + class: metadata.type, + guid: metadata.params.guid, + initializer: metadata.params.initializer + }; + } + return { + type: "event", + time: metadata.startTime, + class: metadata.type, + method: metadata.method, + params: metadata.params, + pageId: metadata.pageId + }; + } + return { + type: "action", + callId: metadata.id, + startTime: metadata.startTime, + endTime: metadata.endTime, + apiName: metadata.apiName || metadata.type + "." + metadata.method, + class: metadata.type, + method: metadata.method, + params: metadata.params, + // eslint-disable-next-line no-restricted-globals + wallTime: metadata.wallTime || Date.now(), + log: metadata.log, + beforeSnapshot: metadata.snapshots.find((s) => s.title === "before")?.snapshotName, + inputSnapshot: metadata.snapshots.find((s) => s.title === "input")?.snapshotName, + afterSnapshot: metadata.snapshots.find((s) => s.title === "after")?.snapshotName, + error: metadata.error?.error, + result: metadata.result, + point: metadata.point, + pageId: metadata.pageId + }; + } + _modernize_4_to_5(events) { + const result2 = []; + for (const event of events) { + const e = this._modernize_event_4_to_5(event); + if (e) + result2.push(e); + } + return result2; + } + _modernize_event_4_to_5(event) { + if (event.type === "event" && event.method === "__create__" && event.class === "JSHandle") + this._jsHandles.set(event.params.guid, event.params.initializer); + if (event.type === "object") { + if (event.class !== "ConsoleMessage") + return null; + const args = event.initializer.args?.map((arg) => { + if (arg.guid) { + const handle = this._jsHandles.get(arg.guid); + return { preview: handle?.preview || "", value: "" }; + } + return { preview: arg.preview || "", value: arg.value || "" }; + }); + this._consoleObjects.set(event.guid, { + type: event.initializer.type, + text: event.initializer.text, + location: event.initializer.location, + args + }); + return null; + } + if (event.type === "event" && event.method === "console") { + const consoleMessage = this._consoleObjects.get(event.params.message?.guid || ""); + if (!consoleMessage) + return null; + return { + type: "console", + time: event.time, + pageId: event.pageId, + messageType: consoleMessage.type, + text: consoleMessage.text, + args: consoleMessage.args, + location: consoleMessage.location + }; + } + return event; + } + _modernize_5_to_6(events) { + const result2 = []; + for (const event of events) { + result2.push(event); + if (event.type !== "after" || !event.log.length) + continue; + for (const log2 of event.log) { + result2.push({ + type: "log", + callId: event.callId, + message: log2, + time: -1 + }); + } + } + return result2; + } + _modernize_6_to_7(events) { + const result2 = []; + if (!this._processedContextCreatedEvent() && events[0].type !== "context-options") { + const event = { + type: "context-options", + origin: "testRunner", + version: 6, + browserName: "", + options: {}, + platform: "unknown", + wallTime: 0, + monotonicTime: 0, + sdkLanguage: "javascript", + contextId: "" + }; + result2.push(event); + } + for (const event of events) { + if (event.type === "context-options") { + result2.push({ ...event, monotonicTime: 0, origin: "library", contextId: "" }); + continue; + } + if (event.type === "before" || event.type === "action") { + if (!this._contextEntry.wallTime) + this._contextEntry.wallTime = event.wallTime; + const eventAsV6 = event; + const eventAsV7 = event; + eventAsV7.stepId = `${eventAsV6.apiName}@${eventAsV6.wallTime}`; + result2.push(eventAsV7); + } else { + result2.push(event); + } + } + return result2; + } + _modernize_7_to_8(events) { + const result2 = []; + for (const event of events) { + if (event.type === "before" || event.type === "action") { + const eventAsV7 = event; + const eventAsV8 = event; + if (eventAsV7.apiName) { + eventAsV8.title = eventAsV7.apiName; + delete eventAsV8.apiName; + } + eventAsV8.stepId = eventAsV7.stepId ?? eventAsV7.callId; + result2.push(eventAsV8); + } else { + result2.push(event); + } + } + return result2; + } + }; + } +}); + +// packages/isomorphic/trace/traceLoader.ts +function stripEncodingFromContentType(contentType) { + const charset = contentType.match(/^(.*);\s*charset=.*$/); + if (charset) + return charset[1]; + return contentType; +} +function createEmptyContext() { + return { + origin: "testRunner", + startTime: Number.MAX_SAFE_INTEGER, + wallTime: Number.MAX_SAFE_INTEGER, + endTime: 0, + browserName: "", + options: { + deviceScaleFactor: 1, + isMobile: false, + viewport: { width: 1280, height: 800 } + }, + pages: [], + resources: [], + actions: [], + events: [], + errors: [], + stdio: [], + hasSource: false, + contextId: "" + }; +} +var TraceLoader; +var init_traceLoader = __esm({ + "packages/isomorphic/trace/traceLoader.ts"() { + "use strict"; + init_traceUtils(); + init_snapshotStorage(); + init_traceModernizer(); + TraceLoader = class { + constructor() { + this.contextEntries = []; + this._resourceToContentType = /* @__PURE__ */ new Map(); + } + async load(backend, traceFile, unzipProgress) { + this._backend = backend; + const prefix = traceFile?.match(/(.+)\.trace$/)?.[1]; + const prefixes = []; + let hasSource = false; + for (const entryName of await this._backend.entryNames()) { + const match = entryName.match(/(.+)\.trace$/); + if (match && (!prefix || prefix === match[1])) + prefixes.push(match[1] || ""); + if (entryName.includes("src@")) + hasSource = true; + } + if (!prefixes.length) + throw new Error("Cannot find .trace file"); + this._snapshotStorage = new SnapshotStorage(); + const total = prefixes.length * 3; + let done = 0; + for (const prefix2 of prefixes) { + const contextEntry = createEmptyContext(); + contextEntry.hasSource = hasSource; + const modernizer = new TraceModernizer(contextEntry, this._snapshotStorage); + const trace = await this._backend.readText(prefix2 + ".trace") || ""; + modernizer.appendTrace(trace); + unzipProgress?.(++done, total); + const network = await this._backend.readText(prefix2 + ".network") || ""; + modernizer.appendTrace(network); + unzipProgress?.(++done, total); + contextEntry.actions = modernizer.actions().sort((a1, a2) => a1.startTime - a2.startTime); + if (!backend.isLive()) { + for (const action of contextEntry.actions.slice().reverse()) { + if (!action.endTime && !action.error) { + for (const a of contextEntry.actions) { + if (a.parentId === action.callId && action.endTime < a.endTime) + action.endTime = a.endTime; + } + } + } + } + const stacks = await this._backend.readText(prefix2 + ".stacks"); + if (stacks) { + const callMetadata = parseClientSideCallMetadata(JSON.parse(stacks)); + for (const action of contextEntry.actions) + action.stack = action.stack || callMetadata.get(action.callId); + } + unzipProgress?.(++done, total); + for (const resource of contextEntry.resources) { + if (resource.request.postData?._sha1) + this._resourceToContentType.set(resource.request.postData._sha1, stripEncodingFromContentType(resource.request.postData.mimeType)); + if (resource.response.content?._sha1) + this._resourceToContentType.set(resource.response.content._sha1, stripEncodingFromContentType(resource.response.content.mimeType)); + } + this.contextEntries.push(contextEntry); + } + this._snapshotStorage.finalize(); + } + async hasEntry(filename) { + return this._backend.hasEntry(filename); + } + async resourceForSha1(sha1) { + const blob = await this._backend.readBlob("resources/" + sha1); + const contentType = this._resourceToContentType.get(sha1); + if (!blob || contentType === void 0 || contentType === "x-unknown") + return blob; + return new Blob([blob], { type: contentType }); + } + storage() { + return this._snapshotStorage; + } + }; + } +}); + +// packages/isomorphic/trace/traceModel.ts +function indexModel(context2) { + for (const page of context2.pages) + page[contextSymbol] = context2; + for (let i = 0; i < context2.actions.length; ++i) { + const action = context2.actions[i]; + action[contextSymbol] = context2; + } + let lastNonRouteAction = void 0; + for (let i = context2.actions.length - 1; i >= 0; i--) { + const action = context2.actions[i]; + action[nextInContextSymbol] = lastNonRouteAction; + if (action.class !== "Route") + lastNonRouteAction = action; + } + for (const event of context2.events) + event[contextSymbol] = context2; + for (const resource of context2.resources) + resource[contextSymbol] = context2; +} +function mergeActionsAndUpdateTiming(contexts) { + const result2 = []; + const actions = mergeActionsAndUpdateTimingSameTrace(contexts); + result2.push(...actions); + result2.sort((a1, a2) => { + if (a2.parentId === a1.callId) + return 1; + if (a1.parentId === a2.callId) + return -1; + return a1.endTime - a2.endTime; + }); + for (let i = 1; i < result2.length; ++i) + result2[i][prevByEndTimeSymbol] = result2[i - 1]; + result2.sort((a1, a2) => { + if (a2.parentId === a1.callId) + return -1; + if (a1.parentId === a2.callId) + return 1; + return a1.startTime - a2.startTime; + }); + for (let i = 0; i + 1 < result2.length; ++i) + result2[i][nextByStartTimeSymbol] = result2[i + 1]; + return result2; +} +function mergeActionsAndUpdateTimingSameTrace(contexts) { + const map = /* @__PURE__ */ new Map(); + const libraryContexts = contexts.filter((context2) => context2.origin === "library"); + const testRunnerContexts = contexts.filter((context2) => context2.origin === "testRunner"); + if (!testRunnerContexts.length || !libraryContexts.length) { + return contexts.map((context2) => { + return context2.actions.map((action) => ({ ...action, context: context2 })); + }).flat(); + } + for (const context2 of libraryContexts) { + for (const action of context2.actions) { + map.set(action.stepId || `tmp-step@${++lastTmpStepId}`, { ...action, context: context2 }); + } + } + const delta = monotonicTimeDeltaBetweenLibraryAndRunner(testRunnerContexts, map); + if (delta) + adjustMonotonicTime(libraryContexts, delta); + const nonPrimaryIdToPrimaryId = /* @__PURE__ */ new Map(); + for (const context2 of testRunnerContexts) { + for (const action of context2.actions) { + const existing = action.stepId && map.get(action.stepId); + if (existing) { + nonPrimaryIdToPrimaryId.set(action.callId, existing.callId); + if (action.error) + existing.error = action.error; + if (action.attachments) + existing.attachments = action.attachments; + if (action.annotations) + existing.annotations = action.annotations; + if (action.parentId) + existing.parentId = nonPrimaryIdToPrimaryId.get(action.parentId) ?? action.parentId; + if (action.group) + existing.group = action.group; + existing.startTime = action.startTime; + existing.endTime = action.endTime; + continue; + } + if (action.parentId) + action.parentId = nonPrimaryIdToPrimaryId.get(action.parentId) ?? action.parentId; + map.set(action.stepId || `tmp-step@${++lastTmpStepId}`, { ...action, context: context2 }); + } + } + return [...map.values()]; +} +function adjustMonotonicTime(contexts, monotonicTimeDelta) { + for (const context2 of contexts) { + context2.startTime += monotonicTimeDelta; + context2.endTime += monotonicTimeDelta; + for (const action of context2.actions) { + if (action.startTime) + action.startTime += monotonicTimeDelta; + if (action.endTime) + action.endTime += monotonicTimeDelta; + } + for (const event of context2.events) + event.time += monotonicTimeDelta; + for (const event of context2.stdio) + event.timestamp += monotonicTimeDelta; + for (const page of context2.pages) { + for (const frame of page.screencastFrames) + frame.timestamp += monotonicTimeDelta; + } + for (const resource of context2.resources) { + if (resource._monotonicTime) + resource._monotonicTime += monotonicTimeDelta; + } + } +} +function monotonicTimeDeltaBetweenLibraryAndRunner(nonPrimaryContexts, libraryActions) { + for (const context2 of nonPrimaryContexts) { + for (const action of context2.actions) { + if (!action.startTime) + continue; + const libraryAction = action.stepId ? libraryActions.get(action.stepId) : void 0; + if (libraryAction) + return action.startTime - libraryAction.startTime; + } + } + return 0; +} +function buildActionTree(actions) { + const itemMap = /* @__PURE__ */ new Map(); + for (const action of actions) { + itemMap.set(action.callId, { + id: action.callId, + parent: void 0, + children: [], + action + }); + } + const rootItem = { action: { ...kFakeRootAction }, id: "", parent: void 0, children: [] }; + for (const item of itemMap.values()) { + rootItem.action.startTime = Math.min(rootItem.action.startTime, item.action.startTime); + rootItem.action.endTime = Math.max(rootItem.action.endTime, item.action.endTime); + const parent = item.action.parentId ? itemMap.get(item.action.parentId) || rootItem : rootItem; + parent.children.push(item); + item.parent = parent; + } + const inheritStack = (item) => { + for (const child of item.children) { + child.action.stack = child.action.stack ?? item.action.stack; + inheritStack(child); + } + }; + inheritStack(rootItem); + return { rootItem, itemMap }; +} +function context(action) { + return action[contextSymbol]; +} +function nextInContext(action) { + return action[nextInContextSymbol]; +} +function previousActionByEndTime(action) { + return action[prevByEndTimeSymbol]; +} +function nextActionByStartTime(action) { + return action[nextByStartTimeSymbol]; +} +function stats(action) { + let errors = 0; + let warnings = 0; + for (const event of eventsForAction(action)) { + if (event.type === "console") { + const type3 = event.messageType; + if (type3 === "warning") + ++warnings; + else if (type3 === "error") + ++errors; + } + if (event.type === "event" && event.method === "pageError") + ++errors; + } + return { errors, warnings }; +} +function eventsForAction(action) { + let result2 = action[eventsSymbol]; + if (result2) + return result2; + const nextAction = nextInContext(action); + result2 = context(action).events.filter((event) => { + return event.time >= action.startTime && (!nextAction || event.time < nextAction.startTime); + }); + action[eventsSymbol] = result2; + return result2; +} +function collectSources(actions, errorDescriptors) { + const result2 = /* @__PURE__ */ new Map(); + for (const action of actions) { + for (const frame of action.stack || []) { + let source8 = result2.get(frame.file); + if (!source8) { + source8 = { errors: [], content: void 0 }; + result2.set(frame.file, source8); + } + } + } + for (const error of errorDescriptors) { + const { action, stack, message } = error; + if (!action || !stack) + continue; + result2.get(stack[0].file)?.errors.push({ + line: stack[0].line || 0, + message + }); + } + return result2; +} +var contextSymbol, nextInContextSymbol, prevByEndTimeSymbol, nextByStartTimeSymbol, eventsSymbol, TraceModel, lastTmpStepId, kFakeRootAction; +var init_traceModel = __esm({ + "packages/isomorphic/trace/traceModel.ts"() { + "use strict"; + init_protocolFormatter(); + contextSymbol = Symbol("context"); + nextInContextSymbol = Symbol("nextInContext"); + prevByEndTimeSymbol = Symbol("prevByEndTime"); + nextByStartTimeSymbol = Symbol("nextByStartTime"); + eventsSymbol = Symbol("events"); + TraceModel = class { + constructor(traceUri, contexts) { + contexts.forEach((contextEntry) => indexModel(contextEntry)); + const libraryContext = contexts.find((context2) => context2.origin === "library"); + this.traceUri = traceUri; + this.browserName = libraryContext?.browserName || ""; + this.sdkLanguage = libraryContext?.sdkLanguage; + this.channel = libraryContext?.channel; + this.testIdAttributeName = libraryContext?.testIdAttributeName; + this.platform = libraryContext?.platform || ""; + this.playwrightVersion = contexts.find((c) => c.playwrightVersion)?.playwrightVersion; + this.title = libraryContext?.title || ""; + this.options = libraryContext?.options || {}; + this.testTimeout = contexts.find((c) => c.origin === "testRunner")?.testTimeout; + this.actions = mergeActionsAndUpdateTiming(contexts); + this.pages = [].concat(...contexts.map((c) => c.pages)); + this.wallTime = contexts.map((c) => c.wallTime).reduce((prev, cur) => Math.min(prev || Number.MAX_VALUE, cur), Number.MAX_VALUE); + this.startTime = contexts.map((c) => c.startTime).reduce((prev, cur) => Math.min(prev, cur), Number.MAX_VALUE); + this.endTime = contexts.map((c) => c.endTime).reduce((prev, cur) => Math.max(prev, cur), Number.MIN_VALUE); + this.events = [].concat(...contexts.map((c) => c.events)); + this.stdio = [].concat(...contexts.map((c) => c.stdio)); + this.errors = [].concat(...contexts.map((c) => c.errors)); + this.hasSource = contexts.some((c) => c.hasSource); + this.hasStepData = contexts.some((context2) => context2.origin === "testRunner"); + this.resources = [...contexts.map((c) => c.resources)].flat().map((entry) => ({ ...entry, id: `${entry.pageref}-${entry.startedDateTime}-${entry.request.url}` })); + this.attachments = this.actions.flatMap((action) => action.attachments?.map((attachment) => ({ ...attachment, callId: action.callId, traceUri })) ?? []); + this.visibleAttachments = this.attachments.filter((attachment) => !attachment.name.startsWith("_")); + this.events.sort((a1, a2) => a1.time - a2.time); + this.resources.sort((a1, a2) => a1._monotonicTime - a2._monotonicTime); + this.errorDescriptors = this.hasStepData ? this._errorDescriptorsFromTestRunner() : this._errorDescriptorsFromActions(); + this.sources = collectSources(this.actions, this.errorDescriptors); + this.actionCounters = /* @__PURE__ */ new Map(); + for (const action of this.actions) { + action.group = action.group ?? getActionGroup({ type: action.class, method: action.method }); + if (action.group) + this.actionCounters.set(action.group, 1 + (this.actionCounters.get(action.group) || 0)); + } + } + createRelativeUrl(path59) { + const url2 = new URL("http://localhost/" + path59); + url2.searchParams.set("trace", this.traceUri); + return url2.toString().substring("http://localhost/".length); + } + failedAction() { + return this.actions.findLast((a) => a.error); + } + filteredActions(actionsFilter) { + const filter = new Set(actionsFilter); + return this.actions.filter((action) => !action.group || filter.has(action.group)); + } + renderActionTree(filter) { + const actions = this.filteredActions(filter ?? []); + const { rootItem } = buildActionTree(actions); + const actionTree = []; + const visit = (actionItem, indent) => { + const title = renderTitleForCall({ ...actionItem.action, type: actionItem.action.class }); + actionTree.push(`${indent}${title || actionItem.id}`); + for (const child of actionItem.children) + visit(child, indent + " "); + }; + rootItem.children.forEach((a) => visit(a, "")); + return actionTree; + } + _errorDescriptorsFromActions() { + const errors = []; + for (const action of this.actions || []) { + if (!action.error?.message) + continue; + errors.push({ + action, + stack: action.stack, + message: action.error.message + }); + } + return errors; + } + _errorDescriptorsFromTestRunner() { + return this.errors.filter((e) => !!e.message).map((error, i) => ({ + stack: error.stack, + message: error.message + })); + } + }; + lastTmpStepId = 0; + kFakeRootAction = { + type: "action", + callId: "", + startTime: 0, + endTime: 0, + class: "", + method: "", + params: {}, + log: [], + context: { + origin: "library", + startTime: 0, + endTime: 0, + browserName: "", + wallTime: 0, + options: {}, + pages: [], + resources: [], + actions: [], + events: [], + stdio: [], + errors: [], + hasSource: false, + contextId: "" + } + }; + } +}); + +// packages/isomorphic/yaml.ts +function yamlEscapeKeyIfNeeded(str) { + if (!yamlStringNeedsQuotes(str)) + return str; + return `'` + str.replace(/'/g, `''`) + `'`; +} +function yamlEscapeValueIfNeeded(str) { + if (!yamlStringNeedsQuotes(str)) + return str; + return '"' + str.replace(/[\\"\x00-\x1f\x7f-\x9f]/g, (c) => { + switch (c) { + case "\\": + return "\\\\"; + case '"': + return '\\"'; + case "\b": + return "\\b"; + case "\f": + return "\\f"; + case "\n": + return "\\n"; + case "\r": + return "\\r"; + case " ": + return "\\t"; + default: + const code = c.charCodeAt(0); + return "\\x" + code.toString(16).padStart(2, "0"); + } + }) + '"'; +} +function yamlStringNeedsQuotes(str) { + if (str.length === 0) + return true; + if (/^\s|\s$/.test(str)) + return true; + if (/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/.test(str)) + return true; + if (/^-/.test(str)) + return true; + if (/[\n:](\s|$)/.test(str)) + return true; + if (/\s#/.test(str)) + return true; + if (/[\n\r]/.test(str)) + return true; + if (/^[&*\],?!>|@"'#%]/.test(str)) + return true; + if (/[{}`]/.test(str)) + return true; + if (/^\[/.test(str)) + return true; + if (!isNaN(Number(str)) || ["y", "n", "yes", "no", "true", "false", "on", "off", "null"].includes(str.toLowerCase())) + return true; + return false; +} +var init_yaml = __esm({ + "packages/isomorphic/yaml.ts"() { + "use strict"; + } +}); + +// packages/isomorphic/index.ts +var isomorphic_exports = {}; +__export(isomorphic_exports, { + CSharpLocatorFactory: () => CSharpLocatorFactory, + DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT: () => DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT, + DEFAULT_PLAYWRIGHT_TIMEOUT: () => DEFAULT_PLAYWRIGHT_TIMEOUT, + InvalidSelectorError: () => InvalidSelectorError, + JavaLocatorFactory: () => JavaLocatorFactory, + JavaScriptLocatorFactory: () => JavaScriptLocatorFactory, + JsonlLocatorFactory: () => JsonlLocatorFactory, + KeyParser: () => KeyParser, + LongStandingScope: () => LongStandingScope, + ManualPromise: () => ManualPromise, + MultiMap: () => MultiMap, + ParserError: () => ParserError, + PythonLocatorFactory: () => PythonLocatorFactory, + Semaphore: () => Semaphore, + SnapshotServer: () => SnapshotServer, + SnapshotStorage: () => SnapshotStorage, + TraceLoader: () => TraceLoader, + TraceModel: () => TraceModel, + ansiRegex: () => ansiRegex, + ariaNodesEqual: () => ariaNodesEqual, + asLocator: () => asLocator, + asLocatorDescription: () => asLocatorDescription, + asLocators: () => asLocators, + assert: () => assert, + buildActionTree: () => buildActionTree, + bytesToString: () => bytesToString, + cacheNormalizedWhitespaces: () => cacheNormalizedWhitespaces, + captureRawStack: () => captureRawStack, + constructURLBasedOnBaseURL: () => constructURLBasedOnBaseURL, + context: () => context, + customCSSNames: () => customCSSNames, + deserializeURLMatch: () => deserializeURLMatch, + escapeForAttributeSelector: () => escapeForAttributeSelector, + escapeForTextSelector: () => escapeForTextSelector, + escapeHTML: () => escapeHTML, + escapeHTMLAttribute: () => escapeHTMLAttribute, + escapeRegExp: () => escapeRegExp, + escapeTemplateString: () => escapeTemplateString, + escapeWithQuotes: () => escapeWithQuotes, + eventsForAction: () => eventsForAction, + findNewNode: () => findNewNode, + formatObject: () => formatObject, + formatObjectOrVoid: () => formatObjectOrVoid, + formatProtocolParam: () => formatProtocolParam, + getActionGroup: () => getActionGroup, + getExtensionForMimeType: () => getExtensionForMimeType, + getMetainfo: () => getMetainfo, + getMimeTypeForPath: () => getMimeTypeForPath, + globToRegexPattern: () => globToRegexPattern, + hasPointerCursor: () => hasPointerCursor, + headersArrayToObject: () => headersArrayToObject, + headersObjectToArray: () => headersObjectToArray, + isError: () => isError, + isHttpUrl: () => isHttpUrl, + isInvalidSelectorError: () => isInvalidSelectorError, + isJsonMimeType: () => isJsonMimeType, + isObject: () => isObject, + isRegExp: () => isRegExp, + isString: () => isString, + isTextualMimeType: () => isTextualMimeType, + isURLPattern: () => isURLPattern, + isXmlMimeType: () => isXmlMimeType, + locatorCustomDescription: () => locatorCustomDescription, + locatorOrSelectorAsSelector: () => locatorOrSelectorAsSelector, + longestCommonSubstring: () => longestCommonSubstring, + methodMetainfo: () => methodMetainfo, + monotonicTime: () => monotonicTime, + msToString: () => msToString, + nextActionByStartTime: () => nextActionByStartTime, + noColors: () => noColors, + normalizeEscapedRegexQuotes: () => normalizeEscapedRegexQuotes, + normalizeWhiteSpace: () => normalizeWhiteSpace, + padImageToSize: () => padImageToSize, + parseAriaSnapshot: () => parseAriaSnapshot, + parseAriaSnapshotUnsafe: () => parseAriaSnapshotUnsafe, + parseAttributeSelector: () => parseAttributeSelector, + parseCSS: () => parseCSS, + parseClientSideCallMetadata: () => parseClientSideCallMetadata, + parseErrorStack: () => parseErrorStack, + parseRegex: () => parseRegex, + parseSelector: () => parseSelector, + parseStackFrame: () => parseStackFrame, + pollAgainstDeadline: () => pollAgainstDeadline, + previousActionByEndTime: () => previousActionByEndTime, + quoteCSSAttributeValue: () => quoteCSSAttributeValue, + raceAgainstDeadline: () => raceAgainstDeadline, + renderTitleForCall: () => renderTitleForCall, + resolveGlobToRegexPattern: () => resolveGlobToRegexPattern, + rewriteErrorMessage: () => rewriteErrorMessage, + scaleImageToSize: () => scaleImageToSize, + serializeClientSideCallMetadata: () => serializeClientSideCallMetadata, + serializeExpectedTextValues: () => serializeExpectedTextValues, + serializeSelector: () => serializeSelector, + serializeURLMatch: () => serializeURLMatch, + serializeURLPattern: () => serializeURLPattern, + setTimeOrigin: () => setTimeOrigin, + signalToPromise: () => signalToPromise, + splitErrorMessage: () => splitErrorMessage, + splitSelectorByFrame: () => splitSelectorByFrame, + stats: () => stats, + stringifySelector: () => stringifySelector, + stringifyStackFrames: () => stringifyStackFrames, + stripAnsiEscapes: () => stripAnsiEscapes, + textValue: () => textValue, + timeOrigin: () => timeOrigin, + toSnakeCase: () => toSnakeCase, + toTitleCase: () => toTitleCase, + trimString: () => trimString, + trimStringWithEllipsis: () => trimStringWithEllipsis, + unsafeLocatorOrSelectorAsSelector: () => unsafeLocatorOrSelectorAsSelector, + urlMatches: () => urlMatches, + urlMatchesEqual: () => urlMatchesEqual, + validate: () => validate, + visitAllSelectorParts: () => visitAllSelectorParts, + webColors: () => webColors, + yamlEscapeKeyIfNeeded: () => yamlEscapeKeyIfNeeded, + yamlEscapeValueIfNeeded: () => yamlEscapeValueIfNeeded +}); +var init_isomorphic = __esm({ + "packages/isomorphic/index.ts"() { + "use strict"; + init_ariaSnapshot(); + init_expectUtils(); + init_assert(); + init_colors(); + init_headers(); + init_imageUtils(); + init_jsonSchema(); + init_locatorGenerators(); + init_manualPromise(); + init_mimeType(); + init_multimap(); + init_protocolFormatter(); + init_protocolMetainfo(); + init_rtti(); + init_semaphore(); + init_stackTrace(); + init_stringUtils(); + init_formatUtils(); + init_time(); + init_timeoutRunner(); + init_snapshotServer(); + init_urlMatch(); + init_cssParser(); + init_locatorParser(); + init_selectorParser(); + init_snapshotStorage(); + init_traceLoader(); + init_traceModel(); + init_traceUtils(); + init_yaml(); + } +}); + +// packages/utils/ascii.ts +function wrapInASCIIBox(text2, padding = 0) { + const lines = text2.split("\n"); + const maxLength = Math.max(...lines.map((line) => line.length)); + return [ + "\u2554" + "\u2550".repeat(maxLength + padding * 2) + "\u2557", + ...lines.map((line) => "\u2551" + " ".repeat(padding) + line + " ".repeat(maxLength - line.length + padding) + "\u2551"), + "\u255A" + "\u2550".repeat(maxLength + padding * 2) + "\u255D" + ].join("\n"); +} +function jsonStringifyForceASCII(object) { + return JSON.stringify(object).replace( + /[\u007f-\uffff]/g, + (c) => "\\u" + ("0000" + c.charCodeAt(0).toString(16)).slice(-4) + ); +} +var init_ascii = __esm({ + "packages/utils/ascii.ts"() { + "use strict"; + } +}); + +// packages/utils/chromiumChannels.ts +function defaultUserDataDirForChannel(channel) { + return channelToDefaultUserDataDir.get(channel)?.[process.platform]; +} +function isChromiumChannelName(channel) { + return channelToDefaultUserDataDir.has(channel); +} +var import_os, import_path, channelToDefaultUserDataDir; +var init_chromiumChannels = __esm({ + "packages/utils/chromiumChannels.ts"() { + "use strict"; + import_os = __toESM(require("os")); + import_path = __toESM(require("path")); + channelToDefaultUserDataDir = /* @__PURE__ */ new Map([ + ["chrome", { + "linux": import_path.default.join(import_os.default.homedir(), ".config", "google-chrome"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Google", "Chrome"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Google", "Chrome", "User Data") + }], + ["chrome-beta", { + "linux": import_path.default.join(import_os.default.homedir(), ".config", "google-chrome-beta"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Google", "Chrome Beta"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Google", "Chrome Beta", "User Data") + }], + ["chrome-dev", { + "linux": import_path.default.join(import_os.default.homedir(), ".config", "google-chrome-unstable"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Google", "Chrome Dev"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Google", "Chrome Dev", "User Data") + }], + ["chrome-canary", { + "linux": import_path.default.join(import_os.default.homedir(), ".config", "google-chrome-canary"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Google", "Chrome Canary"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Google", "Chrome SxS", "User Data") + }], + ["msedge", { + "linux": import_path.default.join(import_os.default.homedir(), ".config", "microsoft-edge"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Microsoft Edge"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Microsoft", "Edge", "User Data") + }], + ["msedge-beta", { + "linux": import_path.default.join(import_os.default.homedir(), ".config", "microsoft-edge-beta"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Microsoft Edge Beta"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Microsoft", "Edge Beta", "User Data") + }], + ["msedge-dev", { + "linux": import_path.default.join(import_os.default.homedir(), ".config", "microsoft-edge-dev"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Microsoft Edge Dev"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Microsoft", "Edge Dev", "User Data") + }], + ["msedge-canary", { + "linux": import_path.default.join(import_os.default.homedir(), ".config", "microsoft-edge-canary"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Microsoft Edge Canary"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Microsoft", "Edge SxS", "User Data") + }] + ]); + } +}); + +// packages/utils/third_party/pixelmatch.js +var require_pixelmatch = __commonJS({ + "packages/utils/third_party/pixelmatch.js"(exports2, module2) { + "use strict"; + module2.exports = pixelmatch2; + var defaultOptions = { + 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({}, defaultOptions, 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 diff2 = 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); + } + diff2++; + } + } else if (output) { + if (!options2.diffMask) drawGrayPixel(img1, pos, options2.alpha, output); + } + } + } + return diff2; + } + 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 min = 0; + let max = 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 < min) { + min = delta; + minX = x; + minY = y; + } else if (delta > max) { + max = delta; + maxX = x; + maxY = y; + } + } + } + if (min === 0 || max === 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); + } + } +}); + +// packages/utils/image_tools/colorUtils.ts +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 + ]; +} +function xyz2lab(xyz) { + const x = xyz[0] / 0.950489; + const y = xyz[1]; + const z30 = 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 = z30 > sigma_pow3 ? z30 ** (1 / 3) : z30 / 3 / sigma_pow2 + 4 / 29; + const l = 116 * fy - 16; + const a = 500 * (fx - fy); + const b = 200 * (fy - fz); + return [l, a, b]; +} +var sigma_pow2, sigma_pow3; +var init_colorUtils = __esm({ + "packages/utils/image_tools/colorUtils.ts"() { + "use strict"; + sigma_pow2 = 6 * 6 / 29 / 29; + sigma_pow3 = 6 * 6 * 6 / 29 / 29 / 29; + } +}); + +// packages/utils/image_tools/imageChannel.ts +var ImageChannel; +var init_imageChannel = __esm({ + "packages/utils/image_tools/imageChannel.ts"() { + "use strict"; + init_colorUtils(); + ImageChannel = class _ImageChannel { + static intoRGB(width, height, data, 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 index = y * newWidth + x; + if (y >= paddingSize && y < newHeight - paddingSize && x >= paddingSize && x < newWidth - paddingSize) { + const offset = ((y - paddingSize) * width + (x - paddingSize)) * 4; + const alpha = data[offset + 3] === 255 ? 1 : data[offset + 3] / 255; + r[index] = blendWithWhite(data[offset], alpha); + g[index] = blendWithWhite(data[offset + 1], alpha); + b[index] = blendWithWhite(data[offset + 2], alpha); + } else { + const color = (y + x) % 2 === 0 ? paddingColorEven : paddingColorOdd; + r[index] = color[0]; + g[index] = color[1]; + b[index] = color[2]; + } + } + } + return [ + new _ImageChannel(newWidth, newHeight, r), + new _ImageChannel(newWidth, newHeight, g), + new _ImageChannel(newWidth, newHeight, b) + ]; + } + constructor(width, height, data) { + this.data = data; + 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) + ]; + } + }; + } +}); + +// packages/utils/image_tools/stats.ts +function ssim(stats2, x1, y1, x2, y2) { + const mean1 = stats2.meanC1(x1, y1, x2, y2); + const mean2 = stats2.meanC2(x1, y1, x2, y2); + const var1 = stats2.varianceC1(x1, y1, x2, y2); + const var2 = stats2.varianceC2(x1, y1, x2, y2); + const cov = stats2.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); +} +var DYNAMIC_RANGE, FastStats; +var init_stats = __esm({ + "packages/utils/image_tools/stats.ts"() { + "use strict"; + DYNAMIC_RANGE = 2 ** 8 - 1; + FastStats = class { + 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 result2 = partialSum[y2 * width + x2]; + if (y1 > 0) + result2 -= partialSum[(y1 - 1) * width + x2]; + if (x1 > 0) + result2 -= partialSum[y2 * width + x1 - 1]; + if (x1 > 0 && y1 > 0) + result2 += partialSum[(y1 - 1) * width + x1 - 1]; + return result2; + } + 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; + } + }; + } +}); + +// packages/utils/image_tools/compare.ts +function drawPixel(width, data, x, y, r, g, b) { + const idx = (y * width + x) * 4; + data[idx + 0] = r; + data[idx + 1] = g; + data[idx + 2] = b; + data[idx + 3] = 255; +} +function compare(actual, expected, diff2, 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 noop = (x, y) => { + }; + const drawRedPixel = diff2 ? (x, y) => drawPixel(width, diff2, x - paddingSize, y - paddingSize, 255, 0, 0) : noop; + const drawYellowPixel = diff2 ? (x, y) => drawPixel(width, diff2, x - paddingSize, y - paddingSize, 255, 255, 0) : noop; + const drawGrayPixel = diff2 ? (x, y) => { + const gray = rgb2gray(r1.get(x, y), g1.get(x, y), b1.get(x, y)); + const value2 = blendWithWhite(gray, 0.1); + drawPixel(width, diff2, x - paddingSize, y - paddingSize, value2, value2, value2); + } : noop; + let fastR; + let fastG; + let 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 SSIM_WINDOW_RADIUS, VARIANCE_WINDOW_RADIUS; +var init_compare = __esm({ + "packages/utils/image_tools/compare.ts"() { + "use strict"; + init_colorUtils(); + init_imageChannel(); + init_stats(); + SSIM_WINDOW_RADIUS = 15; + VARIANCE_WINDOW_RADIUS = 1; + } +}); + +// packages/utils/comparators.ts +function getComparator(mimeType) { + if (mimeType === "image/png") + return compareImages.bind(null, "image/png"); + if (mimeType === "image/jpeg") + return compareImages.bind(null, "image/jpeg"); + if (mimeType === "text/plain") + return compareText; + return compareBuffersOrStrings; +} +function compareBuffersOrStrings(actualBuffer, expectedBuffer) { + if (typeof actualBuffer === "string") + return compareText(actualBuffer, expectedBuffer); + if (!actualBuffer || !(actualBuffer instanceof Buffer)) + return { errorMessage: "Actual result should be a Buffer or a string." }; + if (Buffer.compare(actualBuffer, expectedBuffer)) + return { errorMessage: "Buffers differ" }; + return null; +} +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 = padImageToSize(actual, size); + expected = padImageToSize(expected, size); + } + const diff2 = new PNG({ width: size.width, height: size.height }); + let count; + if (options2.comparator === "ssim-cie94") { + count = compare(expected.data, actual.data, diff2.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 = (0, import_pixelmatch.default)(expected.data, actual.data, diff2.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(diff2) }; + return null; +} +function validateBuffer(buffer, mimeType) { + if (mimeType === "image/png") { + const pngMagicNumber = [137, 80, 78, 71, 13, 10, 26, 10]; + if (buffer.length < pngMagicNumber.length || !pngMagicNumber.every((byte, index) => buffer[index] === byte)) + throw new Error("Could not decode expected image as PNG."); + } else if (mimeType === "image/jpeg") { + const jpegMagicNumber = [255, 216]; + if (buffer.length < jpegMagicNumber.length || !jpegMagicNumber.every((byte, index) => buffer[index] === byte)) + throw new Error("Could not decode expected image as JPEG."); + } +} +function compareText(actual, expectedBuffer) { + if (typeof actual !== "string") + return { errorMessage: "Actual result should be a string" }; + let expected = expectedBuffer.toString("utf-8"); + if (expected === actual) + return null; + if (!actual.endsWith("\n")) + actual += "\n"; + if (!expected.endsWith("\n")) + expected += "\n"; + const lines = diff.createPatch("file", expected, actual, void 0, void 0, { context: 5 }).split("\n"); + const coloredLines = lines.slice(4).map((line) => { + if (line.startsWith("-")) + return colors.green(line); + if (line.startsWith("+")) + return colors.red(line); + if (line.startsWith("@@")) + return colors.dim(line); + return line; + }); + const errorMessage = coloredLines.join("\n"); + return { errorMessage }; +} +var import_pixelmatch, jpegjs, colors, diff, PNG, JPEG_JS_MAX_BUFFER_SIZE_IN_MB; +var init_comparators = __esm({ + "packages/utils/comparators.ts"() { + "use strict"; + init_imageUtils(); + import_pixelmatch = __toESM(require_pixelmatch()); + init_compare(); + jpegjs = require("./utilsBundle").jpegjs; + colors = require("./utilsBundle").colors; + diff = require("./utilsBundle").diff; + ({ PNG } = require("./utilsBundle")); + JPEG_JS_MAX_BUFFER_SIZE_IN_MB = 5 * 1024; + } +}); + +// packages/utils/crypto.ts +function createGuid() { + return import_crypto.default.randomBytes(16).toString("hex"); +} +function calculateSha1(buffer) { + const hash = import_crypto.default.createHash("sha1"); + hash.update(buffer); + return hash.digest("hex"); +} +function encodeBase128(value2) { + const bytes = []; + do { + let byte = value2 & 127; + value2 >>>= 7; + if (bytes.length > 0) + byte |= 128; + bytes.push(byte); + } while (value2 > 0); + return Buffer.from(bytes.reverse()); +} +function generateSelfSignedCertificate() { + const { privateKey, publicKey } = import_crypto.default.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 signature = import_crypto.default.sign("sha256", tbsCertificate, privateKey); + const certificate = DER.encodeSequence([ + tbsCertificate, + DER.encodeSequence([ + DER.encodeObjectIdentifier("1.2.840.113549.1.1.11"), + // sha256WithRSAEncryption PKCS #1 + DER.encodeNull() + ]), + DER.encodeBitString(signature) + ]); + const certPem = [ + "-----BEGIN CERTIFICATE-----", + // Split the base64 string into lines of 64 characters + certificate.toString("base64").match(/.{1,64}/g).join("\n"), + "-----END CERTIFICATE-----" + ].join("\n"); + return { + cert: certPem, + key: privateKey.export({ type: "pkcs1", format: "pem" }) + }; +} +var import_crypto, DER; +var init_crypto = __esm({ + "packages/utils/crypto.ts"() { + "use strict"; + import_crypto = __toESM(require("crypto")); + init_assert(); + DER = class { + static encodeSequence(data) { + return this._encode(48, Buffer.concat(data)); + } + static encodeInteger(data) { + assert(data >= -128 && data <= 127); + return this._encode(2, Buffer.from([data])); + } + 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(data) { + assert(data.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(data)); + } + static encodeExplicitContextDependent(tag, data) { + return this._encode(160 + tag, data); + } + static encodePrintableString(data) { + return this._encode(19, Buffer.from(data)); + } + static encodeBitString(data) { + const unusedBits = 0; + const content = Buffer.concat([Buffer.from([unusedBits]), data]); + 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, data) { + const lengthBytes = this._encodeLength(data.length); + return Buffer.concat([Buffer.from([tag]), lengthBytes, data]); + } + 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]); + } + } + }; + } +}); + +// packages/utils/env.ts +function getFromENV(name) { + let value2 = process.env[name]; + value2 = value2 === void 0 ? process.env[`npm_config_${name.toLowerCase()}`] : value2; + value2 = value2 === void 0 ? process.env[`npm_package_config_${name.toLowerCase()}`] : value2; + return value2; +} +function getAsBooleanFromENV(name, defaultValue) { + const value2 = getFromENV(name); + if (value2 === "false" || value2 === "0") + return false; + if (value2) + return true; + return !!defaultValue; +} +function getPackageManager() { + const env = process.env.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"; +} +function isLikelyNpxGlobal() { + return process.argv.length >= 2 && process.argv[1].includes("_npx"); +} +function setPlaywrightTestProcessEnv() { + return process.env["PLAYWRIGHT_TEST"] = "1"; +} +function guessClientName() { + if (process.env.CLAUDECODE) + return "Claude Code"; + if (process.env.COPILOT_CLI) + return "GitHub Copilot"; + return "playwright-cli"; +} +function isCodingAgent() { + return !!process.env.CLAUDECODE || !!process.env.COPILOT_CLI; +} +var init_env = __esm({ + "packages/utils/env.ts"() { + "use strict"; + } +}); + +// packages/utils/debug.ts +function debugMode() { + if (_debugMode === "console") + return "console"; + if (_debugMode === "0" || _debugMode === "false") + return ""; + return _debugMode ? "inspector" : ""; +} +function isUnderTest() { + return _isUnderTest; +} +var _debugMode, _isUnderTest; +var init_debug = __esm({ + "packages/utils/debug.ts"() { + "use strict"; + init_env(); + _debugMode = getFromENV("PWDEBUG") || ""; + _isUnderTest = getAsBooleanFromENV("PWTEST_UNDER_TEST"); + } +}); + +// packages/utils/debugLogger.ts +var import_fs, debug, debugLoggerColorMap, DebugLogger, debugLogger, kLogCount, RecentLogsCollector; +var init_debugLogger = __esm({ + "packages/utils/debugLogger.ts"() { + "use strict"; + import_fs = __toESM(require("fs")); + debug = require("./utilsBundle").debug; + 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 + }; + DebugLogger = class { + constructor() { + this._debuggers = /* @__PURE__ */ new Map(); + if (process.env.DEBUG_FILE) { + const ansiRegex2 = 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 stream3 = import_fs.default.createWriteStream(process.env.DEBUG_FILE); + debug.log = (data) => { + stream3.write(data.replace(ansiRegex2, "")); + stream3.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}`); + } + }; + debugLogger = new DebugLogger(); + kLogCount = 150; + RecentLogsCollector = class { + constructor() { + this._logs = []; + this._listeners = []; + } + log(message) { + this._logs.push(message); + if (this._logs.length === kLogCount * 2) + this._logs.splice(0, kLogCount); + for (const listener of this._listeners) + listener(message); + } + recentLogs() { + if (this._logs.length > kLogCount) + return this._logs.slice(-kLogCount); + return this._logs; + } + onMessage(listener) { + for (const message of this._logs) + listener(message); + this._listeners.push(listener); + } + }; + } +}); + +// packages/utils/eventsHelper.ts +var EventsHelper, eventsHelper; +var init_eventsHelper = __esm({ + "packages/utils/eventsHelper.ts"() { + "use strict"; + EventsHelper = class { + static addEventListener(emitter, eventName, handler) { + emitter.on(eventName, handler); + return { emitter, eventName, handler, dispose: async () => { + emitter.removeListener(eventName, handler); + } }; + } + static removeEventListeners(listeners) { + for (const listener of listeners) + listener.emitter.removeListener(listener.eventName, listener.handler); + listeners.splice(0, listeners.length); + } + }; + eventsHelper = EventsHelper; + } +}); + +// packages/utils/fileUtils.ts +async function mkdirIfNeeded(filePath) { + await import_fs2.default.promises.mkdir(import_path2.default.dirname(filePath), { recursive: true }).catch(() => { + }); +} +async function removeFolders(dirs) { + return await Promise.all(dirs.map( + (dir) => import_fs2.default.promises.rm(dir, { recursive: true, force: true, maxRetries: 10 }).catch((e) => e) + )); +} +function canAccessFile(file) { + if (!file) + return false; + try { + import_fs2.default.accessSync(file); + return true; + } catch (e) { + return false; + } +} +function isWritable(file) { + try { + import_fs2.default.accessSync(file, import_fs2.default.constants.W_OK); + return true; + } catch { + return false; + } +} +function isSystemDirectory(dir) { + const resolved = import_path2.default.resolve(dir); + if (process.platform === "win32") { + const systemRoot = import_path2.default.resolve(process.env.SystemRoot || "C:\\Windows"); + return isPathInside(systemRoot.toLowerCase(), resolved.toLowerCase()); + } + return resolved === "/"; +} +async function copyFileAndMakeWritable(from, to) { + await import_fs2.default.promises.copyFile(from, to); + await import_fs2.default.promises.chmod(to, 436); +} +function addSuffixToFilePath(filePath, suffix) { + const ext = import_path2.default.extname(filePath); + const base = filePath.substring(0, filePath.length - ext.length); + return base + suffix + ext; +} +function sanitizeForFilePath(s) { + return s.replace(/[\x00-\x2C\x2E-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+/g, "-"); +} +function isPathInside(root, candidate) { + const resolvedRoot = import_path2.default.resolve(root); + const resolvedCandidate = import_path2.default.resolve(candidate); + if (resolvedCandidate === resolvedRoot) + return true; + return resolvedCandidate.startsWith(resolvedRoot + import_path2.default.sep); +} +function resolveWithinRoot(root, fileName) { + if (import_path2.default.isAbsolute(fileName)) + return null; + const resolvedFile = import_path2.default.resolve(root, fileName); + return isPathInside(root, resolvedFile) ? resolvedFile : null; +} +function toPosixPath(aPath) { + return aPath.split(import_path2.default.sep).join(import_path2.default.posix.sep); +} +function makeSocketPath(domain, name) { + const userNameHash = calculateSha1(process.env.USERNAME || process.env.USER || "default").slice(0, 8); + if (process.platform === "win32") { + const socketsDir = process.env.PLAYWRIGHT_SOCKETS_DIR; + const suffix = socketsDir ? `-${calculateSha1(socketsDir).slice(0, 8)}` : ""; + return `\\\\.\\pipe\\pw-${userNameHash}-${domain}-${name}${suffix}`; + } + const baseDir = process.env.PLAYWRIGHT_SOCKETS_DIR || import_path2.default.join(import_os2.default.tmpdir(), `pw-${userNameHash}`); + const dir = import_path2.default.join(baseDir, domain); + const result2 = import_path2.default.join(dir, `${name}.sock`); + import_fs2.default.mkdirSync(dir, { recursive: true }); + return result2; +} +var import_fs2, import_os2, import_path2, existsAsync; +var init_fileUtils = __esm({ + "packages/utils/fileUtils.ts"() { + "use strict"; + import_fs2 = __toESM(require("fs")); + import_os2 = __toESM(require("os")); + import_path2 = __toESM(require("path")); + init_crypto(); + existsAsync = (path59) => new Promise((resolve) => import_fs2.default.stat(path59, (err) => resolve(!err))); + } +}); + +// packages/utils/linuxUtils.ts +function getLinuxDistributionInfoSync() { + if (process.platform !== "linux") + return void 0; + if (!osRelease && !didFailToReadOSRelease) { + try { + const osReleaseText = import_fs3.default.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 value2 = tokens.join("=").trim(); + if (value2.startsWith('"') && value2.endsWith('"')) + value2 = value2.substring(1, value2.length - 1); + if (!name) + continue; + fields.set(name.toLowerCase(), value2); + } + return fields; +} +var import_fs3, didFailToReadOSRelease, osRelease; +var init_linuxUtils = __esm({ + "packages/utils/linuxUtils.ts"() { + "use strict"; + import_fs3 = __toESM(require("fs")); + didFailToReadOSRelease = false; + } +}); + +// packages/utils/hostPlatform.ts +function calculatePlatform() { + if (process.env.PLAYWRIGHT_HOST_PLATFORM_OVERRIDE) { + return { + hostPlatform: process.env.PLAYWRIGHT_HOST_PLATFORM_OVERRIDE, + isOfficiallySupportedPlatform: false + }; + } + const platform = import_os3.default.platform(); + if (platform === "darwin") { + const ver = import_os3.default.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 if (ver[0] < 25) { + macVersion = "mac" + (ver[0] - 9); + if (import_os3.default.cpus().some((cpu) => cpu.model.includes("Apple"))) + macVersion += "-arm64"; + } else { + const LAST_STABLE_MACOS_MAJOR_VERSION = 26; + macVersion = "mac" + Math.min(ver[0] + 1, LAST_STABLE_MACOS_MAJOR_VERSION); + if (import_os3.default.cpus().some((cpu) => cpu.model.includes("Apple"))) + macVersion += "-arm64"; + } + return { hostPlatform: macVersion, isOfficiallySupportedPlatform: true }; + } + if (platform === "linux") { + if (!["x64", "arm64"].includes(import_os3.default.arch())) + return { hostPlatform: "", isOfficiallySupportedPlatform: false }; + const archSuffix = "-" + import_os3.default.arch(); + const distroInfo = getLinuxDistributionInfoSync(); + if (distroInfo?.id === "ubuntu" || distroInfo?.id === "pop" || distroInfo?.id === "neon" || distroInfo?.id === "tuxedo") { + const isUbuntu = distroInfo?.id === "ubuntu"; + const version3 = 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 && version3 === "20.04" }; + if (major < 24) + return { hostPlatform: "ubuntu22.04" + archSuffix, isOfficiallySupportedPlatform: isUbuntu && version3 === "22.04" }; + if (major < 26) + return { hostPlatform: "ubuntu24.04" + archSuffix, isOfficiallySupportedPlatform: isUbuntu && version3 === "24.04" }; + return { hostPlatform: "ubuntu" + distroInfo.version + archSuffix, isOfficiallySupportedPlatform: false }; + } + if (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?.id === "debian" || distroInfo?.id === "raspbian") { + const isOfficiallySupportedPlatform2 = distroInfo?.id === "debian"; + if (distroInfo?.version === "11") + return { hostPlatform: "debian11" + archSuffix, isOfficiallySupportedPlatform: isOfficiallySupportedPlatform2 }; + if (distroInfo?.version === "12") + return { hostPlatform: "debian12" + archSuffix, isOfficiallySupportedPlatform: isOfficiallySupportedPlatform2 }; + if (distroInfo?.version === "13") + return { hostPlatform: "debian13" + archSuffix, isOfficiallySupportedPlatform: isOfficiallySupportedPlatform2 }; + if (distroInfo?.version === "") + return { hostPlatform: "debian13" + archSuffix, isOfficiallySupportedPlatform: isOfficiallySupportedPlatform2 }; + } + return { hostPlatform: "ubuntu24.04" + archSuffix, isOfficiallySupportedPlatform: false }; + } + if (platform === "win32") + return { hostPlatform: "win64", isOfficiallySupportedPlatform: true }; + return { hostPlatform: "", isOfficiallySupportedPlatform: false }; +} +function toShortPlatform(hostPlatform2) { + if (hostPlatform2 === "") + return ""; + if (hostPlatform2 === "win64") + return "win-x64"; + if (hostPlatform2.startsWith("mac")) + return hostPlatform2.endsWith("arm64") ? "mac-arm64" : "mac-x64"; + return hostPlatform2.endsWith("arm64") ? "linux-arm64" : "linux-x64"; +} +var import_os3, hostPlatform, isOfficiallySupportedPlatform, shortPlatform; +var init_hostPlatform = __esm({ + "packages/utils/hostPlatform.ts"() { + "use strict"; + import_os3 = __toESM(require("os")); + init_linuxUtils(); + ({ hostPlatform, isOfficiallySupportedPlatform } = calculatePlatform()); + shortPlatform = toShortPlatform(hostPlatform); + } +}); + +// packages/utils/happyEyeballs.ts +async function createSocket(host, port) { + return new Promise((resolve, reject) => { + if (import_net.default.isIP(host)) { + const socket = import_net.default.createConnection({ host, port }); + socket.on("connect", () => resolve(socket)); + socket.on("error", (error) => reject(error)); + } else { + createConnectionAsync( + { host, port }, + (err, socket) => { + if (err) + reject(err); + if (socket) + resolve(socket); + }, + /* useTLS */ + false + ).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 ??= err; + if (errorCount === addresses.length) + oncreate?.(firstError); + }; + const connected = new ManualPromise(); + for (const { address } of addresses) { + const socket = useTLS ? import_tls.default.connect({ + ...options2, + port: options2.port, + host: address, + servername: hostname + }) : import_net.default.createConnection({ + ...options2, + port: options2.port, + host: address + }); + socket[kDNSLookupAt] = dnsLookupAt; + socket.on("connect", () => { + socket[kTCPConnectionAt] = monotonicTime(); + connected.resolve(); + 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 [v4Result, v6Result] = await Promise.allSettled([ + import_dns.default.promises.lookup(hostname, { all: true, family: 4 }), + import_dns.default.promises.lookup(hostname, { all: true, family: 6 }) + ]); + const v4Addresses = v4Result.status === "fulfilled" ? v4Result.value : []; + const v6Addresses = v6Result.status === "fulfilled" ? v6Result.value : []; + if (!v4Addresses.length && !v6Addresses.length) { + if (v4Result.status === "rejected") + throw v4Result.reason; + throw v6Result.reason; + } + const result2 = []; + for (let i = 0; i < Math.max(v4Addresses.length, v6Addresses.length); i++) { + if (v6Addresses[i]) + result2.push(v6Addresses[i]); + if (v4Addresses[i]) + result2.push(v4Addresses[i]); + } + return result2; +} +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] + }; +} +var import_dns, import_http, import_https, import_net, import_tls, connectionAttemptDelayMs, kDNSLookupAt, kTCPConnectionAt, HttpHappyEyeballsAgent, HttpsHappyEyeballsAgent, httpsHappyEyeballsAgent, httpHappyEyeballsAgent; +var init_happyEyeballs = __esm({ + "packages/utils/happyEyeballs.ts"() { + "use strict"; + import_dns = __toESM(require("dns")); + import_http = __toESM(require("http")); + import_https = __toESM(require("https")); + import_net = __toESM(require("net")); + import_tls = __toESM(require("tls")); + init_assert(); + init_manualPromise(); + init_time(); + connectionAttemptDelayMs = 300; + kDNSLookupAt = Symbol("kDNSLookupAt"); + kTCPConnectionAt = Symbol("kTCPConnectionAt"); + HttpHappyEyeballsAgent = class extends import_http.default.Agent { + createConnection(options2, oncreate) { + if (import_net.default.isIP(clientRequestArgsToHostName(options2))) + return import_net.default.createConnection(options2); + createConnectionAsync( + options2, + oncreate, + /* useTLS */ + false + ).catch((err) => oncreate?.(err)); + } + }; + HttpsHappyEyeballsAgent = class extends import_https.default.Agent { + createConnection(options2, oncreate) { + if (import_net.default.isIP(clientRequestArgsToHostName(options2))) + return import_tls.default.connect(options2); + createConnectionAsync( + options2, + oncreate, + /* useTLS */ + true + ).catch((err) => oncreate?.(err)); + } + }; + httpsHappyEyeballsAgent = new HttpsHappyEyeballsAgent({ keepAlive: true }); + httpHappyEyeballsAgent = new HttpHappyEyeballsAgent({ keepAlive: true }); + } +}); + +// packages/utils/network.ts +function httpRequest(params2, onResponse, onError) { + let url2 = new URL(params2.url); + const options2 = { + method: params2.method || "GET", + headers: params2.headers + }; + if (params2.rejectUnauthorized !== void 0) + options2.rejectUnauthorized = params2.rejectUnauthorized; + const proxyURL = getProxyForUrl(params2.url); + if (proxyURL) { + const parsedProxyURL = normalizeProxyURL(proxyURL); + if (params2.url.startsWith("http:")) { + options2.path = url2.toString(); + url2 = parsedProxyURL; + } else { + options2.agent = new HttpsProxyAgent(parsedProxyURL); + } + } + options2.agent ??= url2.protocol === "https:" ? httpsHappyEyeballsAgent : httpHappyEyeballsAgent; + let cancelRequest; + const requestCallback = (res) => { + const statusCode = res.statusCode || 0; + if (statusCode >= 300 && statusCode < 400 && res.headers.location) { + request2.destroy(); + cancelRequest = httpRequest({ ...params2, url: new URL(res.headers.location, params2.url).toString() }, onResponse, onError).cancel; + } else { + onResponse(res); + } + }; + const request2 = url2.protocol === "https:" ? import_https2.default.request(url2, options2, requestCallback) : import_http2.default.request(url2, options2, requestCallback); + request2.on("error", onError); + if (params2.socketTimeout !== void 0) { + request2.setTimeout(params2.socketTimeout, () => { + onError(new Error(`Request to ${params2.url} timed out after ${params2.socketTimeout}ms`)); + request2.abort(); + }); + } + cancelRequest = (e) => { + try { + request2.destroy(e); + } catch { + } + }; + request2.end(params2.data); + return { cancel: (e) => cancelRequest(e) }; +} +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 normalizeProxyURL(proxy) { + proxy = proxy.trim(); + if (!/^\w+:\/\//.test(proxy)) + proxy = "http://" + proxy; + return new URL(proxy); +} +function createProxyAgent(proxy, forUrl) { + if (!proxy) + return; + if (forUrl && proxy.bypass && shouldBypassProxy(forUrl, proxy.bypass)) + return; + const proxyURL = normalizeProxyURL(proxy.server); + if (proxyURL.protocol?.startsWith("socks")) { + if (proxyURL.protocol === "socks5:") + proxyURL.protocol = "socks5h:"; + else if (proxyURL.protocol === "socks4:") + proxyURL.protocol = "socks4a:"; + return new SocksProxyAgent(proxyURL); + } + if (proxy.username) { + proxyURL.username = proxy.username; + proxyURL.password = proxy.password || ""; + } + if (forUrl && ["ws:", "wss:"].includes(forUrl.protocol)) { + return new HttpsProxyAgent(proxyURL); + } + return new HttpsProxyAgent(proxyURL); +} +function createHttpServer(...args) { + const server = import_http2.default.createServer(...args); + decorateServer(server); + return server; +} +function createHttpsServer(...args) { + const server = import_https2.default.createServer(...args); + decorateServer(server); + return server; +} +function createHttp2Server(...args) { + const server = import_http22.default.createSecureServer(...args); + decorateServer(server); + return server; +} +async function startHttpServer(server, options2) { + const { host = "localhost", port = 0 } = options2; + const errorPromise = new ManualPromise(); + const errorListener = (error) => errorPromise.reject(error); + server.on("error", errorListener); + try { + server.listen(port, host); + await Promise.race([ + new Promise((cb) => server.once("listening", cb)), + errorPromise + ]); + } finally { + server.removeListener("error", errorListener); + } +} +async function isURLAvailable(url2, ignoreHTTPSErrors, onLog, onStdErr) { + let statusCode = await httpStatusCode(url2, ignoreHTTPSErrors, onLog, onStdErr); + if (statusCode === 404 && url2.pathname === "/") { + const indexUrl = new URL(url2); + indexUrl.pathname = "/index.html"; + statusCode = await httpStatusCode(indexUrl, ignoreHTTPSErrors, onLog, onStdErr); + } + return statusCode >= 200 && statusCode < 404; +} +async function httpStatusCode(url2, ignoreHTTPSErrors, onLog, onStdErr) { + return new Promise((resolve) => { + onLog?.(`HTTP GET: ${url2}`); + httpRequest({ + url: url2.toString(), + headers: { Accept: "*/*" }, + rejectUnauthorized: !ignoreHTTPSErrors + }, (res) => { + res.resume(); + const statusCode = res.statusCode ?? 0; + onLog?.(`HTTP Status: ${statusCode}`); + resolve(statusCode); + }, (error) => { + if (error.code === "DEPTH_ZERO_SELF_SIGNED_CERT") + onStdErr?.(`[WebServer] Self-signed certificate detected. Try adding ignoreHTTPSErrors: true to config.webServer.`); + onLog?.(`Error while checking if ${url2} is available: ${error.message}`); + resolve(0); + }); + }); +} +function decorateServer(server) { + const sockets = /* @__PURE__ */ new Set(); + server.on("connection", (socket) => { + sockets.add(socket); + socket.once("close", () => sockets.delete(socket)); + }); + const close3 = server.close; + server.close = (callback) => { + for (const socket of sockets) + socket.destroy(); + sockets.clear(); + return close3.call(server, callback); + }; +} +var import_http2, import_http22, import_https2, HttpsProxyAgent, SocksProxyAgent, getProxyForUrl, NET_DEFAULT_TIMEOUT; +var init_network = __esm({ + "packages/utils/network.ts"() { + "use strict"; + import_http2 = __toESM(require("http")); + import_http22 = __toESM(require("http2")); + import_https2 = __toESM(require("https")); + init_manualPromise(); + init_happyEyeballs(); + ({ HttpsProxyAgent } = require("./utilsBundle")); + ({ SocksProxyAgent } = require("./utilsBundle")); + ({ getProxyForUrl } = require("./utilsBundle")); + NET_DEFAULT_TIMEOUT = 3e4; + } +}); + +// packages/utils/httpServer.ts +function computeAllowedHosts(requested, bound) { + const loopback = /* @__PURE__ */ new Set(["127.0.0.1", "::1", "localhost"]); + const isLoopback = (h) => h !== void 0 && loopback.has(h.toLowerCase()); + if (!isLoopback(requested) && requested !== void 0) + return null; + if (!isLoopback(bound) && requested === void 0) + return null; + return /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]); +} +function urlHostFromAddress(address) { + return address.family === "IPv6" ? `[${address.address}]` : address.address; +} +function hostnameFromHostHeader(host) { + if (host.startsWith("[")) { + const end = host.indexOf("]"); + return end < 0 ? host : host.substring(0, end + 1); + } + const colon = host.indexOf(":"); + return colon < 0 ? host : host.substring(0, colon); +} +function serveFolder(folder) { + const server = new HttpServer(); + const folderRoot = import_path3.default.resolve(folder); + server.routePrefix("/", (request2, response2) => { + let relativePath = new URL("http://localhost" + request2.url).pathname; + if (relativePath.startsWith("/trace/file")) { + const url2 = new URL("http://localhost" + request2.url); + const requested = url2.searchParams.get("path"); + if (!requested) + return false; + const resolved = import_path3.default.resolve(requested); + if (!isPathInside(folderRoot, resolved)) { + response2.statusCode = 403; + response2.end(); + return true; + } + try { + return server.serveFile(request2, response2, resolved); + } catch (e) { + return false; + } + } + if (relativePath === "/") + relativePath = "/index.html"; + const absolutePath = import_path3.default.join(folder, ...relativePath.split("/")); + return server.serveFile(request2, response2, absolutePath); + }); + return server; +} +var import_fs4, import_path3, mime, wsServer, HttpServer; +var init_httpServer = __esm({ + "packages/utils/httpServer.ts"() { + "use strict"; + import_fs4 = __toESM(require("fs")); + import_path3 = __toESM(require("path")); + init_assert(); + init_crypto(); + init_fileUtils(); + init_network(); + mime = require("./utilsBundle").mime; + ({ wsServer } = require("./utilsBundle")); + HttpServer = class { + constructor() { + this._urlPrefixPrecise = ""; + this._urlPrefixHumanReadable = ""; + this._port = 0; + this._started = false; + this._routes = []; + // Allowed Host headers; null disables the check (host bound to a public address). + this._allowedHosts = null; + this._server = createHttpServer(this._onRequest.bind(this)); + } + server() { + return this._server; + } + routePrefix(prefix, handler) { + this._routes.push({ prefix, handler }); + } + routePath(path59, handler) { + this._routes.push({ exact: path59, handler }); + } + port() { + return this._port; + } + createWebSocket(transportFactory, guid) { + assert(!this._wsGuid, "can only create one main websocket transport per server"); + this._wsGuid = guid || createGuid(); + const wsPath = "/" + this._wsGuid; + const wss = new wsServer({ noServer: true }); + this._server.on("upgrade", (request2, socket, head) => { + const pathname = new URL(request2.url ?? "/", "http://localhost").pathname; + if (pathname !== wsPath) + return; + wss.handleUpgrade(request2, socket, head, (ws3) => wss.emit("connection", ws3, request2)); + }); + wss.on("connection", (ws3, request2) => { + const url2 = new URL(request2.url ?? "/", "http://localhost"); + const transport = transportFactory(url2); + transport.sendEvent = (method, params2) => ws3.send(JSON.stringify({ method, params: params2 })); + transport.close = () => ws3.close(); + transport.onconnect(); + ws3.on("message", async (message) => { + const { id, method, params: params2 } = JSON.parse(String(message)); + try { + const result2 = await transport.dispatch(method, params2); + ws3.send(JSON.stringify({ id, result: result2 })); + } catch (e) { + ws3.send(JSON.stringify({ id, error: String(e) })); + } + }); + ws3.on("close", () => transport.onclose()); + ws3.on("error", () => transport.onclose()); + }); + } + wsGuid() { + return this._wsGuid; + } + async createViteDevServer(options2) { + const loadVite = new Function('return import("vite")'); + const vite = await loadVite(); + return await vite.createServer({ + root: options2.root, + base: options2.base, + server: { + middlewareMode: true, + // Dedicated path so Vite's HMR websocket does not collide with any + // websocket HttpServer owns via createWebSocket(). + hmr: { path: "/__vite_hmr", server: this._server } + }, + appType: "spa", + clearScreen: false + }); + } + // HMR end + // Vite's middleware `next` callback for the "no middleware matched" case; + // emits a 404 only if nothing downstream already responded. + static notFoundFallback(response2) { + return () => { + if (!response2.headersSent) { + response2.statusCode = 404; + response2.end(); + } + }; + } + async start(options2 = {}) { + assert(!this._started, "server already started"); + this._started = true; + const host = options2.host; + if (options2.preferredPort) { + try { + await startHttpServer(this._server, { port: options2.preferredPort, host }); + } catch (e) { + if (!e || !e.message || !e.message.includes("EADDRINUSE")) + throw e; + await startHttpServer(this._server, { host }); + } + } else { + await startHttpServer(this._server, { port: options2.port, host }); + } + const address = this._server.address(); + assert(address, "Could not bind server socket"); + if (typeof address === "string") { + this._urlPrefixPrecise = address; + this._urlPrefixHumanReadable = address; + } else { + this._port = address.port; + this._urlPrefixPrecise = `http://${urlHostFromAddress(address)}:${address.port}`; + this._urlPrefixHumanReadable = `http://${host ?? "localhost"}:${address.port}`; + this._allowedHosts = computeAllowedHosts(host, address.address); + } + } + async stop() { + await new Promise((cb) => this._server.close(cb)); + } + urlPrefix(purpose) { + return purpose === "human-readable" ? this._urlPrefixHumanReadable : this._urlPrefixPrecise; + } + serveFile(request2, response2, absoluteFilePath, headers) { + try { + for (const [name, value2] of Object.entries(headers || {})) + response2.setHeader(name, value2); + if (request2.headers.range) + this._serveRangeFile(request2, response2, absoluteFilePath); + else + this._serveFile(response2, absoluteFilePath); + return true; + } catch (e) { + return false; + } + } + _serveFile(response2, absoluteFilePath) { + const content = import_fs4.default.readFileSync(absoluteFilePath); + response2.statusCode = 200; + const contentType = mime.getType(import_path3.default.extname(absoluteFilePath)) || "application/octet-stream"; + response2.setHeader("Content-Type", contentType); + response2.setHeader("Content-Length", content.byteLength); + response2.end(content); + } + _serveRangeFile(request2, response2, absoluteFilePath) { + const range = request2.headers.range; + if (!range || !range.startsWith("bytes=") || range.includes(", ") || [...range].filter((char) => char === "-").length !== 1) { + response2.statusCode = 400; + return response2.end("Bad request"); + } + const [startStr, endStr] = range.replace(/bytes=/, "").split("-"); + let start3; + let end; + const size = import_fs4.default.statSync(absoluteFilePath).size; + if (startStr !== "" && endStr === "") { + start3 = +startStr; + end = size - 1; + } else if (startStr === "" && endStr !== "") { + start3 = size - +endStr; + end = size - 1; + } else { + start3 = +startStr; + end = +endStr; + } + if (Number.isNaN(start3) || Number.isNaN(end) || start3 >= size || end >= size || start3 > end) { + response2.writeHead(416, { + "Content-Range": `bytes */${size}` + }); + return response2.end(); + } + response2.writeHead(206, { + "Content-Range": `bytes ${start3}-${end}/${size}`, + "Accept-Ranges": "bytes", + "Content-Length": end - start3 + 1, + "Content-Type": mime.getType(import_path3.default.extname(absoluteFilePath)) + }); + const readable = import_fs4.default.createReadStream(absoluteFilePath, { start: start3, end }); + readable.pipe(response2); + } + _onRequest(request2, response2) { + if (request2.method === "OPTIONS") { + response2.writeHead(200); + response2.end(); + return; + } + if (this._allowedHosts) { + const host = request2.headers.host?.toLowerCase(); + const hostname = host ? hostnameFromHostHeader(host) : void 0; + if (!hostname || !this._allowedHosts.has(hostname)) { + response2.statusCode = 403; + response2.end(); + return; + } + } + request2.on("error", () => response2.end()); + try { + if (!request2.url) { + response2.end(); + return; + } + const url2 = new URL("http://localhost" + request2.url); + for (const route2 of this._routes) { + if (route2.exact && url2.pathname === route2.exact && route2.handler(request2, response2)) + return; + if (route2.prefix && url2.pathname.startsWith(route2.prefix) && route2.handler(request2, response2)) + return; + } + response2.statusCode = 404; + response2.end(); + } catch (e) { + response2.end(); + } + } + }; + } +}); + +// packages/utils/zones.ts +function currentZone() { + return asyncLocalStorage.getStore() ?? emptyZone; +} +var import_async_hooks, asyncLocalStorage, Zone, emptyZone; +var init_zones = __esm({ + "packages/utils/zones.ts"() { + "use strict"; + import_async_hooks = require("async_hooks"); + asyncLocalStorage = new import_async_hooks.AsyncLocalStorage(); + Zone = class _Zone { + constructor(asyncLocalStorage2, store) { + this._asyncLocalStorage = asyncLocalStorage2; + this._data = store; + } + with(type3, data) { + return new _Zone(this._asyncLocalStorage, new Map(this._data).set(type3, data)); + } + without(type3) { + const data = type3 ? new Map(this._data) : /* @__PURE__ */ new Map(); + data.delete(type3); + return new _Zone(this._asyncLocalStorage, data); + } + run(func) { + return this._asyncLocalStorage.run(this, func); + } + data(type3) { + return this._data.get(type3); + } + }; + emptyZone = new Zone(asyncLocalStorage, /* @__PURE__ */ new Map()); + } +}); + +// packages/utils/nodePlatform.ts +function setBoxedStackPrefixes(prefixes) { + boxedStackPrefixes = prefixes; +} +var import_crypto4, import_fs5, import_path4, util, import_stream, import_events, colors2, pipelineAsync, NodeZone, boxedStackPrefixes, nodePlatform, ReadableStreamImpl, WritableStreamImpl; +var init_nodePlatform = __esm({ + "packages/utils/nodePlatform.ts"() { + "use strict"; + import_crypto4 = __toESM(require("crypto")); + import_fs5 = __toESM(require("fs")); + import_path4 = __toESM(require("path")); + util = __toESM(require("util")); + import_stream = require("stream"); + import_events = require("events"); + init_debugLogger(); + init_zones(); + init_debug(); + colors2 = require("./utilsBundle").colors; + pipelineAsync = util.promisify(import_stream.pipeline); + NodeZone = class _NodeZone { + constructor(zone) { + this._zone = zone; + } + push(data) { + return new _NodeZone(this._zone.with("apiZone", data)); + } + pop() { + return new _NodeZone(this._zone.without("apiZone")); + } + run(func) { + return this._zone.run(func); + } + data() { + return this._zone.data("apiZone"); + } + }; + boxedStackPrefixes = []; + nodePlatform = (coreDir) => ({ + name: "node", + boxedStackPrefixes: () => { + if (process.env.PWDEBUGIMPL) + return []; + return [coreDir, ...boxedStackPrefixes]; + }, + calculateSha1: (text2) => { + const sha1 = import_crypto4.default.createHash("sha1"); + sha1.update(text2); + return Promise.resolve(sha1.digest("hex")); + }, + colors: colors2, + coreDir, + createGuid: () => import_crypto4.default.randomBytes(16).toString("hex"), + defaultMaxListeners: () => import_events.EventEmitter.defaultMaxListeners, + fs: () => import_fs5.default, + env: process.env, + inspectCustom: util.inspect.custom, + isDebugMode: () => debugMode() === "inspector", + isJSDebuggerAttached: () => !!require("inspector").url(), + isLogEnabled(name) { + return debugLogger.isEnabled(name); + }, + isUnderTest: () => isUnderTest(), + log(name, message) { + debugLogger.log(name, message); + }, + path: () => import_path4.default, + pathSeparator: import_path4.default.sep, + showInternalStackFrames: () => !!process.env.PWDEBUGIMPL, + async streamFile(path59, stream3) { + await pipelineAsync(import_fs5.default.createReadStream(path59), stream3); + }, + streamReadable: (channel) => { + return new ReadableStreamImpl(channel); + }, + streamWritable: (channel) => { + return new WritableStreamImpl(channel); + }, + zones: { + current: () => new NodeZone(currentZone()), + empty: new NodeZone(emptyZone) + } + }); + ReadableStreamImpl = class extends import_stream.Readable { + constructor(channel) { + super(); + this._channel = channel; + } + async _read() { + const result2 = await this._channel.read({ size: 1024 * 1024 }); + if (result2.binary.byteLength) + this.push(result2.binary); + else + this.push(null); + } + _destroy(error, callback) { + this._channel.close().catch((e) => null); + super._destroy(error, callback); + } + }; + WritableStreamImpl = class extends import_stream.Writable { + constructor(channel) { + super(); + this._channel = channel; + } + async _write(chunk, encoding, callback) { + const error = await this._channel.write({ binary: typeof chunk === "string" ? Buffer.from(chunk) : chunk }).catch((e) => e); + callback(error || null); + } + async _final(callback) { + const error = await this._channel.close().catch((e) => e); + callback(error || null); + } + }; + } +}); + +// packages/utils/processLauncher.ts +async function gracefullyCloseAll() { + await Promise.all(Array.from(gracefullyCloseSet).map((gracefullyClose) => gracefullyClose().catch((e) => { + }))); +} +function gracefullyProcessExitDoNotHang(code, onExit2) { + const beforeExit = onExit2 ? () => onExit2().catch(() => { + }) : () => Promise.resolve(); + const callback = () => beforeExit().then(() => process.exit(code)); + setTimeout(callback, 3e4); + gracefullyCloseAll().then(callback); +} +function exitHandler() { + for (const kill of killSet) + kill(); +} +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(); +} +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) { + const stdio = options2.stdio === "pipe" ? ["ignore", "pipe", "pipe", "pipe", "pipe"] : ["pipe", "pipe", "pipe"]; + options2.log(` ${options2.command} ${options2.args ? options2.args.join(" ") : ""}`); + const spawnOptions = { + // 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, + stdio + }; + const spawnedProcess = childProcess.spawn(options2.command, options2.args || [], spawnOptions); + const cleanup = async () => { + options2.log(`[pid=${spawnedProcess.pid || "N/A"}] starting temporary directories cleanup`); + const errors = await removeFolders(options2.tempDirectories); + for (let i = 0; i < options2.tempDirectories.length; ++i) { + if (errors[i]) + options2.log(`[pid=${spawnedProcess.pid || "N/A"}] exception while removing ${options2.tempDirectories[i]}: ${errors[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", (error) => { + failed(new Error("Failed to launch: " + error)); + }); + return failedPromise.then(async (error) => { + await cleanup(); + throw error; + }); + } + options2.log(` pid=${spawnedProcess.pid}`); + const stdout = readline.createInterface({ input: spawnedProcess.stdout }); + stdout.on("line", (data) => { + options2.log(`[pid=${spawnedProcess.pid}][out] ` + data); + }); + const stderr = readline.createInterface({ input: spawnedProcess.stderr }); + stderr.on("line", (data) => { + options2.log(`[pid=${spawnedProcess.pid}][err] ` + data); + }); + 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 = childProcess.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 { + import_fs6.default.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 result2 = {}; + for (const { name, value: value2 } of env) + result2[name] = value2; + return result2; +} +var childProcess, import_fs6, readline, gracefullyCloseSet, killSet, sigintHandlerCalled, installedHandlers, processHandlers; +var init_processLauncher = __esm({ + "packages/utils/processLauncher.ts"() { + "use strict"; + childProcess = __toESM(require("child_process")); + import_fs6 = __toESM(require("fs")); + readline = __toESM(require("readline")); + init_fileUtils(); + init_debug(); + gracefullyCloseSet = /* @__PURE__ */ new Set(); + killSet = /* @__PURE__ */ new Set(); + sigintHandlerCalled = false; + installedHandlers = /* @__PURE__ */ new Set(); + processHandlers = { + exit: exitHandler, + SIGINT: sigintHandler, + SIGTERM: sigtermHandler, + SIGHUP: sighupHandler + }; + } +}); + +// packages/utils/profiler.ts +async function startProfiling() { + if (!profileDir) + return; + session = new (require("inspector")).Session(); + session.connect(); + await new Promise((f) => { + session.post("Profiler.enable", () => { + session.post("Profiler.start", f); + }); + }); +} +async function stopProfiling(profileName) { + if (!profileDir) + return; + await new Promise((f) => session.post("Profiler.stop", (err, { profile }) => { + if (!err) { + import_fs7.default.mkdirSync(profileDir, { recursive: true }); + import_fs7.default.writeFileSync(import_path5.default.join(profileDir, profileName + ".json"), JSON.stringify(profile)); + } + f(); + })); +} +var import_fs7, import_path5, profileDir, session; +var init_profiler = __esm({ + "packages/utils/profiler.ts"() { + "use strict"; + import_fs7 = __toESM(require("fs")); + import_path5 = __toESM(require("path")); + profileDir = process.env.PWTEST_PROFILE_DIR || ""; + } +}); + +// packages/utils/serializedFS.ts +var import_fs8, yazl, APPEND_CHUNK_SIZE, SerializedFS; +var init_serializedFS = __esm({ + "packages/utils/serializedFS.ts"() { + "use strict"; + import_fs8 = __toESM(require("fs")); + init_manualPromise(); + yazl = require("./utilsBundle").yazl; + APPEND_CHUNK_SIZE = 64 * 1024; + SerializedFS = class { + 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, text2, flush) { + if (!this._buffers.has(file)) + this._buffers.set(file, []); + const buffer = this._buffers.get(file); + buffer.push(text2); + let size = 0; + for (const chunk of buffer) + size += chunk.length; + if (flush || size >= APPEND_CHUNK_SIZE) + this._flushFile(file); + } + _flushFile(file) { + const buffer = this._buffers.get(file); + if (buffer === void 0) + return; + const content = buffer.join(""); + this._buffers.delete(file); + this._appendOperation({ op: "appendFile", file, content }); + } + copyFile(from, to) { + this._flushFile(from); + this._buffers.delete(to); + this._appendOperation({ op: "copyFile", from, 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?.op === "appendFile" && op.op === "appendFile" && last.file === op.file && last.content.length < APPEND_CHUNK_SIZE) { + 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 import_fs8.default.promises.mkdir(op.dir, { recursive: true }); + return; + } + case "writeFile": { + if (op.skipIfExists) + await import_fs8.default.promises.writeFile(op.file, op.content, { flag: "wx" }).catch(() => { + }); + else + await import_fs8.default.promises.writeFile(op.file, op.content); + return; + } + case "copyFile": { + await import_fs8.default.promises.copyFile(op.from, op.to); + return; + } + case "appendFile": { + await import_fs8.default.promises.appendFile(op.file, op.content); + return; + } + case "zip": { + const zipFile = new yazl.ZipFile(); + const result2 = new ManualPromise(); + zipFile.on("error", (error) => result2.reject(error)); + for (const entry of op.entries) + zipFile.addFile(entry.value, entry.name); + zipFile.end(); + zipFile.outputStream.pipe(import_fs8.default.createWriteStream(op.zipFileName)).on("close", () => result2.resolve()).on("error", (error) => result2.reject(error)); + await result2; + return; + } + } + } + }; + } +}); + +// packages/utils/socksProxy.ts +function hexToNumber(hex) { + return [...hex].reduce((value2, digit2) => { + const code = digit2.charCodeAt(0); + if (code >= 48 && code <= 57) + return value2 + code; + if (code >= 97 && code <= 102) + return value2 + (code - 97) + 10; + if (code >= 65 && code <= 70) + return value2 + (code - 65) + 10; + throw new Error("Invalid IPv6 token " + hex); + }, 0); +} +function ipToSocksAddress(address) { + if (import_net2.default.isIPv4(address)) { + return [ + 1, + // IPv4 + ...address.split(".", 4).map((t) => +t & 255) + // Address + ]; + } + if (import_net2.default.isIPv6(address)) { + const result2 = [4]; + const tokens = address.split(":", 8); + while (tokens.length < 8) + tokens.unshift(""); + for (const token of tokens) { + const value2 = hexToNumber(token); + result2.push(value2 >> 8 & 255, value2 & 255); + } + return result2; + } + throw new Error("Only IPv4 and IPv6 addresses are supported"); +} +function starMatchToRegex(pattern) { + const source8 = pattern.split("*").map((s) => { + return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + }).join(".*"); + return new RegExp("^" + source8 + "$"); +} +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 (import_net2.default.isIPv4(tokenHost) || import_net2.default.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 (import_net2.default.isIPv4(host) || import_net2.default.isIPv6(host)) + return false; + return !!host.match(tokenRegex); + }; + }); + return (host, port) => matchers.some((matcher) => matcher(host, port)); +} +var import_events2, import_net2, SocksConnection, SocksProxy, SocksProxyHandler; +var init_socksProxy = __esm({ + "packages/utils/socksProxy.ts"() { + "use strict"; + import_events2 = __toESM(require("events")); + import_net2 = __toESM(require("net")); + init_assert(); + init_crypto(); + init_debugLogger(); + init_happyEyeballs(); + SocksConnection = class { + 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, host, port } = await this._parseRequest(); + if (command !== 1 /* CONNECT */) { + this._writeBytes(Buffer.from([ + 5, + 7 /* CommandNotSupported */, + 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 version3 = await this._readByte(); + assert(version3 === 5, "The VER field must be set to x05 for this version of the protocol, was " + version3); + 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([version3, method])); + return true; + } + } + this._writeBytes(Buffer.from([version3, 255 /* NO_ACCEPTABLE_METHODS */])); + return false; + } + async _parseRequest() { + const version3 = await this._readByte(); + assert(version3 === 5, "The VER field must be set to x05 for this version of the protocol, was " + version3); + const command = await this._readByte(); + await this._readByte(); + const addressType = await this._readByte(); + let host = ""; + switch (addressType) { + case 1 /* IPv4 */: + host = (await this._readBytes(4)).join("."); + break; + case 3 /* FqName */: + const length = await this._readByte(); + host = (await this._readBytes(length)).toString(); + break; + case 4 /* IPv6 */: + 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, + host, + port + }; + } + async _readByte() { + const buffer = await this._readBytes(1); + return buffer[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(buffer) { + if (this._socket.writable) + this._socket.write(buffer); + } + _onClose() { + this._client.onSocketClosed({ uid: this._uid }); + } + _onData(buffer) { + this._buffer = Buffer.concat([this._buffer, buffer]); + 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 /* Succeeded */, + 0, + // RSV + ...ipToSocksAddress(host), + // ATYP, Address + port >> 8, + port & 255 + // Port + ])); + this._socket.on("data", (data) => this._client.onSocketData({ uid: this._uid, data })); + } + socketFailed(errorCode) { + const buffer = 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": + buffer[1] = 4 /* HostUnreachable */; + break; + case "ENETUNREACH": + buffer[1] = 3 /* NetworkUnreachable */; + break; + case "ECONNREFUSED": + buffer[1] = 5 /* ConnectionRefused */; + break; + case "ERULESET": + buffer[1] = 2 /* NotAllowedByRuleSet */; + break; + } + this._writeBytes(buffer); + this._socket.end(); + } + sendData(data) { + this._socket.write(data); + } + end() { + this._socket.end(); + } + error(error) { + this._socket.destroy(new Error(error)); + } + }; + SocksProxy = class _SocksProxy extends import_events2.default { + 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 import_net2.default.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)); + }); + } + static { + this.Events = { + SocksRequested: "socksRequested", + SocksData: "socksData", + SocksClosed: "socksClosed" + }; + } + setPattern(pattern) { + try { + this._patternMatcher = parsePattern(pattern); + } catch (e) { + this._patternMatcher = () => false; + } + } + async _handleDirect(request2) { + try { + const socket = await createSocket(request2.host, request2.port); + socket.on("data", (data) => this._connections.get(request2.uid)?.sendData(data)); + socket.on("error", (error) => { + this._connections.get(request2.uid)?.error(error.message); + this._directSockets.delete(request2.uid); + }); + socket.on("end", () => { + this._connections.get(request2.uid)?.end(); + this._directSockets.delete(request2.uid); + }); + const localAddress = socket.localAddress; + const localPort = socket.localPort; + this._directSockets.set(request2.uid, socket); + this._connections.get(request2.uid)?.socketConnected(localAddress, localPort); + } catch (error) { + this._connections.get(request2.uid)?.socketFailed(error.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(_SocksProxy.Events.SocksRequested, payload); + } + onSocketData(payload) { + const direct = this._directSockets.get(payload.uid); + if (direct) { + direct.write(payload.data); + return; + } + this.emit(_SocksProxy.Events.SocksData, payload); + } + onSocketClosed(payload) { + const direct = this._directSockets.get(payload.uid); + if (direct) { + direct.destroy(); + this._directSockets.delete(payload.uid); + return; + } + this.emit(_SocksProxy.Events.SocksClosed, payload); + } + socketConnected({ uid, host, port }) { + this._connections.get(uid)?.socketConnected(host, port); + } + socketFailed({ uid, errorCode }) { + this._connections.get(uid)?.socketFailed(errorCode); + } + sendSocketData({ uid, data }) { + this._connections.get(uid)?.sendData(data); + } + sendSocketEnd({ uid }) { + this._connections.get(uid)?.end(); + } + sendSocketError({ uid, error }) { + this._connections.get(uid)?.error(error); + } + }; + SocksProxyHandler = class _SocksProxyHandler extends import_events2.default { + constructor(pattern, redirectPortForTest) { + super(); + this._sockets = /* @__PURE__ */ new Map(); + this._patternMatcher = () => false; + this._patternMatcher = parsePattern(pattern); + this._redirectPortForTest = redirectPortForTest; + } + static { + this.Events = { + SocksConnected: "socksConnected", + SocksData: "socksData", + SocksError: "socksError", + SocksFailed: "socksFailed", + SocksEnd: "socksEnd" + }; + } + 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(_SocksProxyHandler.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", (data) => { + const payload2 = { uid, data }; + this.emit(_SocksProxyHandler.Events.SocksData, payload2); + }); + socket.on("error", (error) => { + const payload2 = { uid, error: error.message }; + debugLogger.log("socks", `[${uid}] <= network socket error ${payload2.error}`); + this.emit(_SocksProxyHandler.Events.SocksError, payload2); + this._sockets.delete(uid); + }); + socket.on("end", () => { + const payload2 = { uid }; + debugLogger.log("socks", `[${uid}] <= network socket closed`); + this.emit(_SocksProxyHandler.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(_SocksProxyHandler.Events.SocksConnected, payload); + } catch (error) { + const payload = { uid, errorCode: error.code }; + debugLogger.log("socks", `[${uid}] <= connect error ${payload.errorCode}`); + this.emit(_SocksProxyHandler.Events.SocksFailed, payload); + } + } + sendSocketData({ uid, data }) { + this._sockets.get(uid)?.write(data); + } + socketClosed({ uid }) { + debugLogger.log("socks", `[${uid}] <= browser socket closed`); + this._sockets.get(uid)?.destroy(); + this._sockets.delete(uid); + } + }; + } +}); + +// packages/utils/spawnAsync.ts +function spawnAsync(cmd, args, options2 = {}) { + const process2 = (0, import_child_process.spawn)(cmd, args, Object.assign({ windowsHide: true }, options2)); + return new Promise((resolve) => { + let stdout = ""; + let stderr = ""; + if (process2.stdout) + process2.stdout.on("data", (data) => stdout += data.toString()); + if (process2.stderr) + process2.stderr.on("data", (data) => stderr += data.toString()); + process2.on("close", (code) => resolve({ stdout, stderr, code })); + process2.on("error", (error) => resolve({ stdout, stderr, code: 0, error })); + }); +} +var import_child_process; +var init_spawnAsync = __esm({ + "packages/utils/spawnAsync.ts"() { + "use strict"; + import_child_process = require("child_process"); + } +}); + +// packages/utils/stringWidth.ts +function characterWidth(c) { + return getEastAsianWidth.eastAsianWidth(c.codePointAt(0)); +} +function stringWidth(v) { + let width = 0; + for (const { segment } of new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(v)) + width += characterWidth(segment); + return width; +} +function suffixOfWidth(v, width) { + const segments = [...new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(v)]; + let suffixBegin = v.length; + for (const { segment, index } of segments.reverse()) { + const segmentWidth = stringWidth(segment); + if (segmentWidth > width) + break; + width -= segmentWidth; + suffixBegin = index; + } + return v.substring(suffixBegin); +} +function fitToWidth(line, width, prefix) { + const prefixLength = prefix ? stripAnsiEscapes(prefix).length : 0; + width -= prefixLength; + if (stringWidth(line) <= width) + return line; + const parts = line.split(ansiRegex); + const taken = []; + for (let i = parts.length - 1; i >= 0; i--) { + if (i % 2) { + taken.push(parts[i]); + } else { + let part = suffixOfWidth(parts[i], width); + const wasTruncated = part.length < parts[i].length; + if (wasTruncated && parts[i].length > 0) { + part = "\u2026" + suffixOfWidth(parts[i], width - 1); + } + taken.push(part); + width -= stringWidth(part); + } + } + return taken.reverse().join(""); +} +var getEastAsianWidth; +var init_stringWidth = __esm({ + "packages/utils/stringWidth.ts"() { + "use strict"; + init_stringUtils(); + getEastAsianWidth = require("./utilsBundle").getEastAsianWidth; + } +}); + +// packages/utils/task.ts +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); + } + }; +} +var init_task = __esm({ + "packages/utils/task.ts"() { + "use strict"; + } +}); + +// packages/utils/wsServer.ts +var wsServer2, lastConnectionId, kConnectionSymbol, perMessageDeflate, WSServer; +var init_wsServer = __esm({ + "packages/utils/wsServer.ts"() { + "use strict"; + init_httpServer(); + init_network(); + init_debugLogger(); + ({ wsServer: wsServer2 } = require("./utilsBundle")); + lastConnectionId = 0; + kConnectionSymbol = Symbol("kConnection"); + perMessageDeflate = { + serverNoContextTakeover: true, + zlibDeflateOptions: { + level: 3 + }, + zlibInflateOptions: { + chunkSize: 10 * 1024 + }, + threshold: 10 * 1024 + }; + WSServer = class { + constructor(delegate) { + // Allowed Host headers for HTTP requests. null disables the check (server bound to a public address). + this._allowedHosts = null; + this._delegate = delegate; + } + async listen(port = 0, hostname, path59) { + debugLogger.log("server", `Server started at ${/* @__PURE__ */ new Date()}`); + hostname ??= "localhost"; + const server = createHttpServer((request2, response2) => this._onRequest(request2, response2)); + server.on("error", (error) => debugLogger.log("server", String(error))); + this.server = server; + const wsEndpoint = await new Promise((resolve, reject) => { + server.listen(port, hostname, () => { + const address = server.address(); + if (!address) { + reject(new Error("Could not bind server socket")); + return; + } + if (typeof address === "string") { + resolve(`${address}${path59}`); + return; + } + this._allowedHosts = computeAllowedHosts(hostname, address.address); + resolve(`ws://${urlHostFromAddress(address)}:${address.port}${path59}`); + }).on("error", reject); + }); + debugLogger.log("server", "Listening at " + wsEndpoint); + this._wsServer = new wsServer2({ + noServer: true, + perMessageDeflate + }); + this._wsServer.on("headers", (headers) => this._delegate.onHeaders(headers)); + server.on("upgrade", (request2, socket, head) => { + const pathname = new URL("http://localhost" + request2.url).pathname; + if (pathname !== path59) { + socket.write(`HTTP/${request2.httpVersion} 400 Bad Request\r +\r +`); + socket.destroy(); + return; + } + if (this._allowedHosts && !this._isAllowedOrigin(request2.headers.origin)) { + socket.write(`HTTP/${request2.httpVersion} 403 Forbidden\r +\r +`); + socket.destroy(); + return; + } + const upgradeResult = this._delegate.onUpgrade(request2, socket); + if (upgradeResult) { + socket.write(upgradeResult.error); + socket.destroy(); + return; + } + this._wsServer.handleUpgrade(request2, socket, head, (ws3) => this._wsServer.emit("connection", ws3, request2)); + }); + this._wsServer.on("connection", (ws3, request2) => { + debugLogger.log("server", "Connected client ws.extension=" + ws3.extensions); + const url2 = new URL("http://localhost" + (request2.url || "")); + const id = String(++lastConnectionId); + debugLogger.log("server", `[${id}] serving connection: ${request2.url}`); + const connection = this._delegate.onConnection(request2, url2, ws3, id); + ws3[kConnectionSymbol] = connection; + }); + return wsEndpoint; + } + _onRequest(request2, response2) { + if (this._allowedHosts) { + const host = request2.headers.host?.toLowerCase(); + const hostname = host ? hostnameFromHostHeader(host) : void 0; + if (!hostname || !this._allowedHosts.has(hostname)) { + response2.statusCode = 403; + response2.end(); + return; + } + } + this._delegate.onRequest(request2, response2); + } + _isAllowedOrigin(origin) { + if (!origin) + return true; + try { + const hostname = new URL(origin).hostname.toLowerCase(); + const bracketed = hostname.includes(":") ? `[${hostname}]` : hostname; + return this._allowedHosts.has(hostname) || this._allowedHosts.has(bracketed); + } catch { + return false; + } + } + async close() { + const server = this._wsServer; + if (!server) + return; + debugLogger.log("server", "closing websocket server"); + const waitForClose = new Promise((f) => server.close(f)); + await Promise.all(Array.from(server.clients).map(async (ws3) => { + const connection = ws3[kConnectionSymbol]; + if (connection) + await connection.close(); + try { + ws3.terminate(); + } catch (e) { + } + })); + await waitForClose; + debugLogger.log("server", "closing http server"); + if (this.server) + await new Promise((f) => this.server.close(f)); + this._wsServer = void 0; + this.server = void 0; + debugLogger.log("server", "closed server"); + } + }; + } +}); + +// packages/utils/third_party/yauzl/pend.js +var require_pend = __commonJS({ + "packages/utils/third_party/yauzl/pend.js"(exports2, module2) { + "use strict"; + module2.exports = 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(self) { + self.pending += 1; + var called = false; + return onCb; + function onCb(err) { + if (called) throw new Error("callback called twice"); + called = true; + self.error = self.error || err; + self.pending -= 1; + if (self.waiting.length > 0 && self.pending < self.max) { + pendGo(self, self.waiting.shift()); + } else if (self.pending === 0) { + var listeners = self.listeners; + self.listeners = []; + listeners.forEach(cbListener); + } + } + function cbListener(listener) { + listener(self.error); + } + } + function pendGo(self, fn) { + fn(pendHold(self)); + } + } +}); + +// packages/utils/third_party/yauzl/fd-slicer.js +var require_fd_slicer = __commonJS({ + "packages/utils/third_party/yauzl/fd-slicer.js"(exports2) { + "use strict"; + var fs61 = require("fs"); + var util3 = require("util"); + var stream3 = require("stream"); + var Readable2 = stream3.Readable; + var Writable2 = stream3.Writable; + var PassThrough = stream3.PassThrough; + var Pend = require_pend(); + var EventEmitter21 = require("events").EventEmitter; + exports2.createFromBuffer = createFromBuffer; + exports2.createFromFd = createFromFd; + exports2.BufferSlicer = BufferSlicer; + exports2.FdSlicer = FdSlicer; + util3.inherits(FdSlicer, EventEmitter21); + function FdSlicer(fd, options2) { + options2 = options2 || {}; + EventEmitter21.call(this); + this.fd = fd; + this.pend = new Pend(); + this.pend.max = 1; + this.refCount = 0; + this.autoClose = !!options2.autoClose; + } + FdSlicer.prototype.read = function(buffer, offset, length, position, callback) { + var self = this; + self.pend.go(function(cb) { + fs61.read(self.fd, buffer, offset, length, position, function(err, bytesRead, buffer2) { + cb(); + callback(err, bytesRead, buffer2); + }); + }); + }; + FdSlicer.prototype.write = function(buffer, offset, length, position, callback) { + var self = this; + self.pend.go(function(cb) { + fs61.write(self.fd, buffer, offset, length, position, function(err, written, buffer2) { + cb(); + callback(err, written, buffer2); + }); + }); + }; + FdSlicer.prototype.createReadStream = function(options2) { + return new ReadStream(this, options2); + }; + FdSlicer.prototype.createWriteStream = function(options2) { + return new WriteStream(this, options2); + }; + FdSlicer.prototype.ref = function() { + this.refCount += 1; + }; + FdSlicer.prototype.unref = function() { + var self = this; + self.refCount -= 1; + if (self.refCount > 0) return; + if (self.refCount < 0) throw new Error("invalid unref"); + if (self.autoClose) { + fs61.close(self.fd, onCloseDone); + } + function onCloseDone(err) { + if (err) { + self.emit("error", err); + } else { + self.emit("close"); + } + } + }; + util3.inherits(ReadStream, Readable2); + function ReadStream(context2, options2) { + options2 = options2 || {}; + Readable2.call(this, options2); + this.context = context2; + this.context.ref(); + this.start = options2.start || 0; + this.endOffset = options2.end; + this.pos = this.start; + this._destroyed = false; + } + ReadStream.prototype._read = function(n) { + var self = this; + if (self._destroyed) return; + var toRead = Math.min(self._readableState.highWaterMark, n); + if (self.endOffset != null) { + toRead = Math.min(toRead, self.endOffset - self.pos); + } + if (toRead <= 0) { + self._destroyed = true; + self.push(null); + self.context.unref(); + return; + } + self.context.pend.go(function(cb) { + if (self._destroyed) return cb(); + var buffer = Buffer.allocUnsafe(toRead); + fs61.read(self.context.fd, buffer, 0, toRead, self.pos, function(err, bytesRead) { + if (self._destroyed) return cb(); + if (err) { + self.destroy(err); + } else if (bytesRead === 0) { + self._destroyed = true; + self.push(null); + self.context.unref(); + } else { + self.pos += bytesRead; + self.push(buffer.slice(0, bytesRead)); + } + cb(); + }); + }); + }; + ReadStream.prototype.destroy = function(err) { + if (err == null && !this.readableEnded) { + err = new Error("stream destroyed"); + } + return Readable2.prototype.destroy.call(this, err); + }; + ReadStream.prototype._destroy = function(err, cb) { + if (!this._destroyed) { + this._destroyed = true; + this.context.unref(); + } + cb(err); + }; + util3.inherits(WriteStream, Writable2); + function WriteStream(context2, options2) { + options2 = options2 || {}; + Writable2.call(this, options2); + this.context = context2; + 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)); + } + WriteStream.prototype._write = function(buffer, encoding, callback) { + var self = this; + if (self._destroyed) return; + if (self.pos + buffer.length > self.endOffset) { + var err = new Error("maximum file length exceeded"); + err.code = "ETOOBIG"; + self.destroy(); + callback(err); + return; + } + self.context.pend.go(function(cb) { + if (self._destroyed) return cb(); + fs61.write(self.context.fd, buffer, 0, buffer.length, self.pos, function(err2, bytes) { + if (err2) { + self.destroy(); + cb(); + callback(err2); + } else { + self.bytesWritten += bytes; + self.pos += bytes; + self.emit("progress"); + cb(); + callback(); + } + }); + }); + }; + WriteStream.prototype._destroy = function(err, cb) { + if (!this._destroyed) { + this._destroyed = true; + this.context.unref(); + } + cb(err); + }; + util3.inherits(BufferSlicer, EventEmitter21); + function BufferSlicer(buffer, options2) { + EventEmitter21.call(this); + options2 = options2 || {}; + this.refCount = 0; + this.buffer = buffer; + this.maxChunkSize = options2.maxChunkSize || Number.MAX_SAFE_INTEGER; + } + BufferSlicer.prototype.read = function(buffer, offset, length, position, callback) { + if (!(0 <= offset && offset <= buffer.length)) throw new RangeError("offset outside buffer: 0 <= " + offset + " <= " + buffer.length); + if (position < 0) throw new RangeError("position is negative: " + position); + if (offset + length > buffer.length) { + length = buffer.length - offset; + } + if (position + length > this.buffer.length) { + length = this.buffer.length - position; + } + if (length <= 0) { + setImmediate(function() { + callback(null, 0); + }); + return; + } + this.buffer.copy(buffer, offset, position, position + length); + setImmediate(function() { + callback(null, length); + }); + }; + BufferSlicer.prototype.write = function(buffer, offset, length, position, callback) { + buffer.copy(this.buffer, position, offset, offset + length); + setImmediate(function() { + callback(null, length, buffer); + }); + }; + 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 offset = 0; + while (true) { + var nextOffset = offset + this.maxChunkSize; + if (nextOffset >= entireSlice.length) { + if (offset < entireSlice.length) { + readStream.write(entireSlice.slice(offset, entireSlice.length)); + } + break; + } + readStream.write(entireSlice.slice(offset, nextOffset)); + offset = nextOffset; + } + readStream.end(); + readStream._destroy = function(err, cb) { + readStream._destroyed = true; + PassThrough.prototype._destroy.call(readStream, err, cb); + }; + return readStream; + }; + BufferSlicer.prototype.createWriteStream = function(options2) { + var bufferSlicer = this; + options2 = options2 || {}; + var writeStream = new Writable2(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(buffer, encoding, callback) { + if (writeStream._destroyed) return; + var end = writeStream.pos + buffer.length; + if (end > writeStream.endOffset) { + var err = new Error("maximum file length exceeded"); + err.code = "ETOOBIG"; + writeStream._destroyed = true; + callback(err); + return; + } + buffer.copy(bufferSlicer.buffer, writeStream.pos, 0, buffer.length); + writeStream.bytesWritten += buffer.length; + writeStream.pos = end; + writeStream.emit("progress"); + callback(); + }; + writeStream._destroy = function(err, cb) { + writeStream._destroyed = true; + cb(err); + }; + 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(buffer, options2) { + return new BufferSlicer(buffer, options2); + } + function createFromFd(fd, options2) { + return new FdSlicer(fd, options2); + } + } +}); + +// packages/utils/third_party/yauzl/buffer-crc32.js +var require_buffer_crc32 = __commonJS({ + "packages/utils/third_party/yauzl/buffer-crc32.js"(exports2, module2) { + "use strict"; + var Buffer2 = require("buffer").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 crc = ~~previous ^ -1; + for (var n = 0; n < buf.length; n++) { + crc = CRC_TABLE[(crc ^ buf[n]) & 255] ^ crc >>> 8; + } + return crc ^ -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; + }; + module2.exports = crc32; + } +}); + +// packages/utils/third_party/yauzl/index.js +var require_yauzl = __commonJS({ + "packages/utils/third_party/yauzl/index.js"(exports2) { + "use strict"; + var fs61 = require("fs"); + var zlib2 = require("zlib"); + var fd_slicer = require_fd_slicer(); + var crc32 = require_buffer_crc32(); + var util3 = require("util"); + var EventEmitter21 = require("events").EventEmitter; + var Transform2 = require("stream").Transform; + var PassThrough = require("stream").PassThrough; + var Writable2 = require("stream").Writable; + exports2.open = open7; + exports2.fromFd = fromFd; + exports2.fromBuffer = fromBuffer; + exports2.fromRandomAccessReader = fromRandomAccessReader; + exports2.dosDateTimeToDate = dosDateTimeToDate; + exports2.getFileNameLowLevel = getFileNameLowLevel; + exports2.validateFileName = validateFileName; + exports2.parseExtraFields = parseExtraFields; + exports2.ZipFile = ZipFile2; + exports2.Entry = Entry; + exports2.LocalFileHeader = LocalFileHeader; + exports2.RandomAccessReader = RandomAccessReader; + function open7(path59, 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; + fs61.open(path59, "r", function(err, fd) { + if (err) return callback(err); + fromFd(fd, options2, function(err2, zipfile) { + if (err2) fs61.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; + fs61.fstat(fd, function(err, stats2) { + if (err) return callback(err); + var reader = fd_slicer.createFromFd(fd, { autoClose: true }); + fromRandomAccessReader(reader, stats2.size, options2, callback); + }); + } + function fromBuffer(buffer, 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(buffer, { maxChunkSize: 65536 }); + fromRandomAccessReader(reader, buffer.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 buffer = newBuffer(bufferSize); + var bufferReadStart = totalSize - buffer.length; + readAndAssertNoEof(reader, buffer, 0, bufferSize, bufferReadStart, function(err) { + if (err) return callback(err); + for (var i = bufferSize - eocdrWithoutCommentSize; i >= 0; i -= 1) { + if (buffer.readUInt32LE(i) !== 101010256) continue; + var eocdrBuffer = buffer.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\u263A\u263B` in the comment?")); + } + var comment = decodeStrings ? decodeBuffer(eocdrBuffer.subarray(22), false) : eocdrBuffer.subarray(22); + if (i - zip64EocdlSize >= 0 && buffer.readUInt32LE(i - zip64EocdlSize) === 117853008) { + var zip64EocdlBuffer = buffer.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, comment, 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, comment, 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.")); + }); + } + util3.inherits(ZipFile2, EventEmitter21); + function ZipFile2(reader, centralDirectoryOffset, fileSize, entryCount, comment, autoClose, lazyEntries, decodeStrings, validateEntrySizes, strictFileNames) { + var self = this; + EventEmitter21.call(self); + self.reader = reader; + self.reader.on("error", function(err) { + emitError(self, err); + }); + self.reader.once("close", function() { + self.emit("close"); + }); + self.readEntryCursor = centralDirectoryOffset; + self.fileSize = fileSize; + self.entryCount = entryCount; + self.comment = comment; + self.entriesRead = 0; + self.autoClose = !!autoClose; + self.lazyEntries = !!lazyEntries; + self.decodeStrings = !!decodeStrings; + self.validateEntrySizes = !!validateEntrySizes; + self.strictFileNames = !!strictFileNames; + self.isOpen = true; + self.emittedError = false; + if (!self.lazyEntries) self._readEntry(); + } + ZipFile2.prototype.close = function() { + if (!this.isOpen) return; + this.isOpen = false; + this.reader.unref(); + }; + function emitErrorAndAutoClose(self, err) { + if (self.autoClose) self.close(); + emitError(self, err); + } + function emitError(self, err) { + if (self.emittedError) return; + self.emittedError = true; + self.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 self = this; + if (self.entryCount === self.entriesRead) { + setImmediate(function() { + if (self.autoClose) self.close(); + if (self.emittedError) return; + self.emit("end"); + }); + return; + } + if (self.emittedError) return; + var buffer = newBuffer(46); + readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err) { + if (err) return emitErrorAndAutoClose(self, err); + if (self.emittedError) return; + var entry = new Entry(); + var signature = buffer.readUInt32LE(0); + if (signature !== 33639248) return emitErrorAndAutoClose(self, new Error("invalid central directory file header signature: 0x" + signature.toString(16))); + entry.versionMadeBy = buffer.readUInt16LE(4); + entry.versionNeededToExtract = buffer.readUInt16LE(6); + entry.generalPurposeBitFlag = buffer.readUInt16LE(8); + entry.compressionMethod = buffer.readUInt16LE(10); + entry.lastModFileTime = buffer.readUInt16LE(12); + entry.lastModFileDate = buffer.readUInt16LE(14); + entry.crc32 = buffer.readUInt32LE(16); + entry.compressedSize = buffer.readUInt32LE(20); + entry.uncompressedSize = buffer.readUInt32LE(24); + entry.fileNameLength = buffer.readUInt16LE(28); + entry.extraFieldLength = buffer.readUInt16LE(30); + entry.fileCommentLength = buffer.readUInt16LE(32); + entry.internalFileAttributes = buffer.readUInt16LE(36); + entry.externalFileAttributes = buffer.readUInt32LE(38); + entry.relativeOffsetOfLocalHeader = buffer.readUInt32LE(42); + if (entry.generalPurposeBitFlag & 64) return emitErrorAndAutoClose(self, new Error("strong encryption is not supported")); + self.readEntryCursor += 46; + buffer = newBuffer(entry.fileNameLength + entry.extraFieldLength + entry.fileCommentLength); + readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err2) { + if (err2) return emitErrorAndAutoClose(self, err2); + if (self.emittedError) return; + entry.fileNameRaw = buffer.subarray(0, entry.fileNameLength); + var fileCommentStart = entry.fileNameLength + entry.extraFieldLength; + entry.extraFieldRaw = buffer.subarray(entry.fileNameLength, fileCommentStart); + entry.fileCommentRaw = buffer.subarray(fileCommentStart, fileCommentStart + entry.fileCommentLength); + try { + entry.extraFields = parseExtraFields(entry.extraFieldRaw); + } catch (err3) { + return emitErrorAndAutoClose(self, err3); + } + if (self.decodeStrings) { + var isUtf8 = (entry.generalPurposeBitFlag & 2048) !== 0; + entry.fileComment = decodeBuffer(entry.fileCommentRaw, isUtf8); + entry.fileName = getFileNameLowLevel(entry.generalPurposeBitFlag, entry.fileNameRaw, entry.extraFields, self.strictFileNames); + var errorMessage = validateFileName(entry.fileName); + if (errorMessage != null) return emitErrorAndAutoClose(self, new Error(errorMessage)); + } else { + entry.fileComment = entry.fileCommentRaw; + entry.fileName = entry.fileNameRaw; + } + entry.comment = entry.fileComment; + self.readEntryCursor += buffer.length; + self.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 index = 0; + if (entry.uncompressedSize === 4294967295) { + if (index + 8 > zip64EiefBuffer.length) { + return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include uncompressed size")); + } + entry.uncompressedSize = readUInt64LE(zip64EiefBuffer, index); + index += 8; + } + if (entry.compressedSize === 4294967295) { + if (index + 8 > zip64EiefBuffer.length) { + return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include compressed size")); + } + entry.compressedSize = readUInt64LE(zip64EiefBuffer, index); + index += 8; + } + if (entry.relativeOffsetOfLocalHeader === 4294967295) { + if (index + 8 > zip64EiefBuffer.length) { + return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include relative header offset")); + } + entry.relativeOffsetOfLocalHeader = readUInt64LE(zip64EiefBuffer, index); + index += 8; + } + break; + } + if (self.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(self, new Error(msg)); + } + } + self.emit("entry", entry); + if (!self.lazyEntries) self._readEntry(); + }); + }); + }; + ZipFile2.prototype.openReadStream = function(entry, options2, callback) { + var self = 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 (!self.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)); + } + self.readLocalFileHeader(entry, { minimal: true }, function(err, localFileHeader) { + if (err) return callback(err); + self.openReadStreamLowLevel( + localFileHeader.fileDataStart, + entry.compressedSize, + relativeStart, + relativeEnd, + decompress, + entry.uncompressedSize, + callback + ); + }); + }; + ZipFile2.prototype.openReadStreamLowLevel = function(fileDataStart, compressedSize, relativeStart, relativeEnd, decompress, uncompressedSize, callback) { + var self = this; + var fileDataEnd = fileDataStart + compressedSize; + var readStream = self.reader.createReadStream({ + start: fileDataStart + relativeStart, + end: fileDataStart + relativeEnd + }); + var endpointStream = readStream; + if (decompress) { + var destroyed = false; + var inflateFilter = zlib2.createInflateRaw(); + readStream.on("error", function(err) { + setImmediate(function() { + if (!destroyed) inflateFilter.emit("error", err); + }); + }); + readStream.pipe(inflateFilter); + if (self.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 self = this; + if (callback == null) { + callback = options2; + options2 = null; + } + if (options2 == null) options2 = {}; + self.reader.ref(); + var buffer = newBuffer(30); + readAndAssertNoEof(self.reader, buffer, 0, buffer.length, entry.relativeOffsetOfLocalHeader, function(err) { + try { + if (err) return callback(err); + var signature = buffer.readUInt32LE(0); + if (signature !== 67324752) { + return callback(new Error("invalid local file header signature: 0x" + signature.toString(16))); + } + var fileNameLength = buffer.readUInt16LE(26); + var extraFieldLength = buffer.readUInt16LE(28); + var fileDataStart = entry.relativeOffsetOfLocalHeader + 30 + fileNameLength + extraFieldLength; + if (fileDataStart + entry.compressedSize > self.fileSize) { + return callback(new Error("file data overflows file bounds: " + fileDataStart + " + " + entry.compressedSize + " > " + self.fileSize)); + } + if (options2.minimal) { + return callback(null, { fileDataStart }); + } + var localFileHeader = new LocalFileHeader(); + localFileHeader.fileDataStart = fileDataStart; + localFileHeader.versionNeededToExtract = buffer.readUInt16LE(4); + localFileHeader.generalPurposeBitFlag = buffer.readUInt16LE(6); + localFileHeader.compressionMethod = buffer.readUInt16LE(8); + localFileHeader.lastModFileTime = buffer.readUInt16LE(10); + localFileHeader.lastModFileDate = buffer.readUInt16LE(12); + localFileHeader.crc32 = buffer.readUInt32LE(14); + localFileHeader.compressedSize = buffer.readUInt32LE(18); + localFileHeader.uncompressedSize = buffer.readUInt32LE(22); + localFileHeader.fileNameLength = fileNameLength; + localFileHeader.extraFieldLength = extraFieldLength; + buffer = newBuffer(fileNameLength + extraFieldLength); + self.reader.ref(); + readAndAssertNoEof(self.reader, buffer, 0, buffer.length, entry.relativeOffsetOfLocalHeader + 30, function(err2) { + try { + if (err2) return callback(err2); + localFileHeader.fileName = buffer.subarray(0, fileNameLength); + localFileHeader.extraField = buffer.subarray(fileNameLength); + return callback(null, localFileHeader); + } finally { + self.reader.unref(); + } + }); + } finally { + self.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 data = extraField.data; + if (data.length < 5) continue; + var flags = data[0]; + var HAS_MTIME = 1; + if (!(flags & HAS_MTIME)) continue; + var posixTimestamp = data.readInt32LE(1); + return new Date(posixTimestamp * 1e3); + } else if (extraField.id === 10) { + var data = extraField.data; + if (data.length !== 32) continue; + if (data.readUInt16LE(4) !== 1) continue; + if (data.readUInt16LE(6) !== 24) continue; + var hundredNanoSecondsSince1601 = data.readUInt32LE(8) + 4294967296 * data.readInt32LE(12); + 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, buffer, offset, length, position, callback) { + if (length === 0) { + return setImmediate(function() { + callback(null, newBuffer(0)); + }); + } + reader.read(buffer, offset, length, position, function(err, bytesRead) { + if (err) return callback(err); + if (bytesRead < length) { + return callback(new Error("unexpected EOF")); + } + callback(); + }); + } + util3.inherits(AssertByteCountStream, Transform2); + function AssertByteCountStream(byteCount) { + Transform2.call(this); + this.actualByteCount = 0; + this.expectedByteCount = byteCount; + } + AssertByteCountStream.prototype._transform = function(chunk, encoding, 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(); + }; + util3.inherits(RandomAccessReader, EventEmitter21); + function RandomAccessReader() { + EventEmitter21.call(this); + this.refCount = 0; + } + RandomAccessReader.prototype.ref = function() { + this.refCount += 1; + }; + RandomAccessReader.prototype.unref = function() { + var self = this; + self.refCount -= 1; + if (self.refCount > 0) return; + if (self.refCount < 0) throw new Error("invalid unref"); + self.close(onCloseDone); + function onCloseDone(err) { + if (err) return self.emit("error", err); + self.emit("close"); + } + }; + RandomAccessReader.prototype.createReadStream = function(options2) { + if (options2 == null) options2 = {}; + var start3 = options2.start; + var end = options2.end; + if (start3 === end) { + var emptyStream = new PassThrough(); + setImmediate(function() { + emptyStream.end(); + }); + return emptyStream; + } + var stream3 = this._readStreamForRange(start3, end); + var destroyed = false; + var refUnrefFilter = new RefUnrefFilter(this); + stream3.on("error", function(err) { + setImmediate(function() { + if (!destroyed) refUnrefFilter.emit("error", err); + }); + }); + installDestroyFn(refUnrefFilter, function() { + stream3.unpipe(refUnrefFilter); + refUnrefFilter.unref(); + stream3.destroy(); + }); + var byteCounter = new AssertByteCountStream(end - start3); + refUnrefFilter.on("error", function(err) { + setImmediate(function() { + if (!destroyed) byteCounter.emit("error", err); + }); + }); + installDestroyFn(byteCounter, function() { + destroyed = true; + refUnrefFilter.unpipe(byteCounter); + refUnrefFilter.destroy(); + }); + return stream3.pipe(refUnrefFilter).pipe(byteCounter); + }; + RandomAccessReader.prototype._readStreamForRange = function(start3, end) { + throw new Error("not implemented"); + }; + RandomAccessReader.prototype.read = function(buffer, offset, length, position, callback) { + var readStream = this.createReadStream({ start: position, end: position + length }); + var writeStream = new Writable2(); + var written = 0; + writeStream._write = function(chunk, encoding, cb) { + chunk.copy(buffer, offset + written, 0, chunk.length); + written += chunk.length; + cb(); + }; + writeStream.on("finish", callback); + readStream.on("error", function(error) { + callback(error); + }); + readStream.pipe(writeStream); + }; + RandomAccessReader.prototype.close = function(callback) { + setImmediate(callback); + }; + util3.inherits(RefUnrefFilter, PassThrough); + function RefUnrefFilter(context2) { + PassThrough.call(this); + this.context = context2; + 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\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C\u25BA\u25C4\u2195\u203C\xB6\xA7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"; + function decodeBuffer(buffer, isUtf8) { + if (isUtf8) { + return buffer.toString("utf8"); + } else { + var result2 = ""; + for (var i = 0; i < buffer.length; i++) { + result2 += cp437[buffer[i]]; + } + return result2; + } + } + function readUInt64LE(buffer, offset) { + var lower32 = buffer.readUInt32LE(offset); + var upper32 = buffer.readUInt32LE(offset + 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(stream3, fn) { + if (typeof stream3.destroy === "function") { + stream3._destroy = function(err, cb) { + fn(); + if (cb != null) cb(err); + }; + } else { + stream3.destroy = fn; + } + } + function defaultCallback(err) { + if (err) throw err; + } + } +}); + +// packages/utils/zipFile.ts +var yauzl, ZipFile; +var init_zipFile = __esm({ + "packages/utils/zipFile.ts"() { + "use strict"; + yauzl = __toESM(require_yauzl()); + ZipFile = class { + 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, z30) => { + if (e) { + reject(e); + return; + } + this._zipFile = z30; + 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, (error, readStream) => { + if (error || !readStream) { + reject(error || "Entry not found"); + return; + } + const buffers = []; + readStream.on("data", (data) => buffers.push(data)); + readStream.on("end", () => resolve(Buffer.concat(buffers))); + }); + }); + } + close() { + this._zipFile?.close(); + } + }; + } +}); + +// packages/utils/third_party/extractZip.ts +async function extractZip(zipPath, opts) { + debug2("creating target directory", opts.dir); + if (!import_path6.default.isAbsolute(opts.dir)) + throw new Error("Target directory is expected to be absolute"); + await import_fs9.promises.mkdir(opts.dir, { recursive: true }); + opts.dir = await import_fs9.promises.realpath(opts.dir); + return new Extractor(zipPath, opts).extract(); +} +var import_fs9, import_path6, import_stream2, import_util, import_yauzl, debugPkg, getStream, debug2, openZip, pipeline2, Extractor; +var init_extractZip = __esm({ + "packages/utils/third_party/extractZip.ts"() { + "use strict"; + import_fs9 = require("fs"); + import_path6 = __toESM(require("path")); + import_stream2 = __toESM(require("stream")); + import_util = require("util"); + import_yauzl = __toESM(require_yauzl()); + debugPkg = require("./utilsBundle").debug; + getStream = require("./utilsBundle").getStream; + debug2 = debugPkg("extract-zip"); + openZip = (0, import_util.promisify)(import_yauzl.default.open); + pipeline2 = (0, import_util.promisify)(import_stream2.default.pipeline); + Extractor = class { + constructor(zipPath, opts) { + this.canceled = false; + 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 = import_path6.default.dirname(import_path6.default.join(this.opts.dir, entry.fileName)); + try { + await import_fs9.promises.mkdir(destDir, { recursive: true }); + const canonicalDestDir = await import_fs9.promises.realpath(destDir); + const relativeDestDir = import_path6.default.relative(this.opts.dir, canonicalDestDir); + if (relativeDestDir.split(import_path6.default.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 = import_path6.default.join(this.opts.dir, entry.fileName); + const mode = entry.externalFileAttributes >> 16 & 65535; + const IFMT = 61440; + const IFDIR = 16384; + const IFLNK = 40960; + const symlink = (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: symlink }); + const procMode = this.getExtractedMode(mode, isDir) & 511; + const destDir = isDir ? dest : import_path6.default.dirname(dest); + const mkdirOptions = { recursive: true }; + if (isDir) + mkdirOptions.mode = procMode; + debug2("mkdir", { dir: destDir, ...mkdirOptions }); + await import_fs9.promises.mkdir(destDir, mkdirOptions); + if (isDir) + return; + debug2("opening read stream", dest); + const readStream = await (0, import_util.promisify)(this.zipfile.openReadStream.bind(this.zipfile))(entry); + if (symlink) { + const link = await getStream(readStream); + debug2("creating symlink", link, dest); + await import_fs9.promises.symlink(link, dest); + } else { + await pipeline2(readStream, (0, import_fs9.createWriteStream)(dest, { mode: procMode })); + } + } + getExtractedMode(entryMode, isDir) { + let mode = entryMode; + if (mode === 0) { + if (isDir) { + if (this.opts.defaultDirMode) + mode = Number(this.opts.defaultDirMode); + if (!mode) + mode = 493; + } else { + if (this.opts.defaultFileMode) + mode = Number(this.opts.defaultFileMode); + if (!mode) + mode = 420; + } + } + return mode; + } + }; + } +}); + +// packages/utils/third_party/lockfile.ts +function probe(file, fs61, callback) { + const cachedPrecision = fs61[cacheSymbol]; + if (cachedPrecision) { + return fs61.stat(file, (err, stat) => { + if (err) + return callback(err); + callback(null, stat.mtime, cachedPrecision); + }); + } + const mtime = new Date(Math.ceil(Date.now() / 1e3) * 1e3 + 5); + fs61.utimes(file, mtime, mtime, (err) => { + if (err) + return callback(err); + fs61.stat(file, (err2, stat) => { + if (err2) + return callback(err2); + const precision = stat.mtime.getTime() % 1e3 === 0 ? "s" : "ms"; + Object.defineProperty(fs61, cacheSymbol, { value: precision }); + callback(null, stat.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, import_path7.default.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, stat) => { + if (err2) { + if (err2.code === "ENOENT") + return acquireLock(file, { ...options2, stale: 0 }, callback); + return callback(err2); + } + if (!isLockStale(stat, 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(stat, options2) { + return stat.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(null); + }); +} +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, stat) => { + 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() === stat.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 && 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 lockImpl(file, options2, callback) { + const resolvedOptions = { + stale: 1e4, + update: null, + realpath: true, + retries: 0, + fs: gracefulFs, + onCompromised: (err) => { + throw err; + }, + ...options2 + }; + resolvedOptions.retries = resolvedOptions.retries || 0; + resolvedOptions.retries = typeof resolvedOptions.retries === "number" ? { retries: resolvedOptions.retries } : resolvedOptions.retries; + resolvedOptions.stale = Math.max(resolvedOptions.stale || 0, 2e3); + resolvedOptions.update = resolvedOptions.update === null || resolvedOptions.update === void 0 ? resolvedOptions.stale / 2 : resolvedOptions.update || 0; + resolvedOptions.update = Math.max(Math.min(resolvedOptions.update, resolvedOptions.stale / 2), 1e3); + resolveCanonicalPath(file, resolvedOptions, (err, resolvedFile) => { + if (err) + return callback(err); + const canonicalFile = resolvedFile; + const operation = retry.operation(resolvedOptions.retries); + operation.attempt(() => { + acquireLock(canonicalFile, resolvedOptions, (err2, mtime, mtimePrecision) => { + if (operation.retry(err2 || void 0)) + return; + if (err2) + return callback(operation.mainError()); + const lock2 = locks[canonicalFile] = { + lockfilePath: getLockFile(canonicalFile, resolvedOptions), + mtime, + mtimePrecision, + options: resolvedOptions, + lastUpdate: Date.now() + }; + updateLock(canonicalFile, resolvedOptions); + callback(null, (releasedCallback) => { + if (lock2.released) { + return releasedCallback && releasedCallback(Object.assign(new Error("Lock is already released"), { code: "ERELEASED" })); + } + unlock(canonicalFile, { ...resolvedOptions, realpath: false }, releasedCallback || (() => { + })); + }); + }); + }); + }); +} +function unlock(file, options2, callback) { + const resolvedOptions = { + stale: 1e4, + update: null, + realpath: true, + retries: 0, + fs: gracefulFs, + onCompromised: (err) => { + throw err; + }, + ...options2 + }; + resolveCanonicalPath(file, resolvedOptions, (err, resolvedFile) => { + if (err) + return callback(err); + const canonicalFile = resolvedFile; + const lock2 = locks[canonicalFile]; + if (!lock2) + return callback(Object.assign(new Error("Lock is not acquired/owned by you"), { code: "ENOTACQUIRED" })); + if (lock2.updateTimeout) + clearTimeout(lock2.updateTimeout); + lock2.released = true; + delete locks[canonicalFile]; + removeLock(canonicalFile, resolvedOptions, callback); + }); +} +function toPromise(method) { + return (...args) => new Promise((resolve, reject) => { + args.push((err, result2) => { + if (err) + reject(err); + else + resolve(result2); + }); + method(...args); + }); +} +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) { + } + } + }); +} +async function lock(file, options2) { + ensureCleanup(); + const release = await toPromise(lockImpl)(file, options2 || {}); + return toPromise(release); +} +var import_path7, gracefulFs, retry, onExit, locks, cacheSymbol, cleanupInitialized; +var init_lockfile = __esm({ + "packages/utils/third_party/lockfile.ts"() { + "use strict"; + import_path7 = __toESM(require("path")); + gracefulFs = require("./utilsBundle").gracefulFs; + retry = require("./utilsBundle").retry; + onExit = require("./utilsBundle").onExit; + locks = {}; + cacheSymbol = Symbol(); + cleanupInitialized = false; + } +}); + +// packages/utils/index.ts +var utils_exports = {}; +__export(utils_exports, { + FastStats: () => FastStats, + HttpServer: () => HttpServer, + ImageChannel: () => ImageChannel, + NET_DEFAULT_TIMEOUT: () => NET_DEFAULT_TIMEOUT, + RecentLogsCollector: () => RecentLogsCollector, + SerializedFS: () => SerializedFS, + SocksProxy: () => SocksProxy, + SocksProxyHandler: () => SocksProxyHandler, + WSServer: () => WSServer, + ZipFile: () => ZipFile, + Zone: () => Zone, + addSuffixToFilePath: () => addSuffixToFilePath, + blendWithWhite: () => blendWithWhite, + calculateSha1: () => calculateSha1, + canAccessFile: () => canAccessFile, + colorDeltaE94: () => colorDeltaE94, + compare: () => compare, + compareBuffersOrStrings: () => compareBuffersOrStrings, + computeAllowedHosts: () => computeAllowedHosts, + copyFileAndMakeWritable: () => copyFileAndMakeWritable, + createGuid: () => createGuid, + createHttp2Server: () => createHttp2Server, + createHttpServer: () => createHttpServer, + createHttpsServer: () => createHttpsServer, + createProxyAgent: () => createProxyAgent, + currentZone: () => currentZone, + debugLogger: () => debugLogger, + debugMode: () => debugMode, + decorateServer: () => decorateServer, + defaultUserDataDirForChannel: () => defaultUserDataDirForChannel, + emptyZone: () => emptyZone, + envArrayToObject: () => envArrayToObject, + eventsHelper: () => eventsHelper, + existsAsync: () => existsAsync, + extractZip: () => extractZip, + fitToWidth: () => fitToWidth, + generateSelfSignedCertificate: () => generateSelfSignedCertificate, + getAsBooleanFromENV: () => getAsBooleanFromENV, + getComparator: () => getComparator, + getFromENV: () => getFromENV, + getPackageManager: () => getPackageManager, + getPackageManagerExecCommand: () => getPackageManagerExecCommand, + gracefullyCloseAll: () => gracefullyCloseAll, + gracefullyCloseSet: () => gracefullyCloseSet, + gracefullyProcessExitDoNotHang: () => gracefullyProcessExitDoNotHang, + guessClientName: () => guessClientName, + hostPlatform: () => hostPlatform, + hostnameFromHostHeader: () => hostnameFromHostHeader, + httpRequest: () => httpRequest, + isChromiumChannelName: () => isChromiumChannelName, + isCodingAgent: () => isCodingAgent, + isLikelyNpxGlobal: () => isLikelyNpxGlobal, + isOfficiallySupportedPlatform: () => isOfficiallySupportedPlatform, + isPathInside: () => isPathInside, + isSystemDirectory: () => isSystemDirectory, + isURLAvailable: () => isURLAvailable, + isUnderTest: () => isUnderTest, + isWritable: () => isWritable, + jsonStringifyForceASCII: () => jsonStringifyForceASCII, + launchProcess: () => launchProcess, + lock: () => lock, + makeSocketPath: () => makeSocketPath, + makeWaitForNextTask: () => makeWaitForNextTask, + mkdirIfNeeded: () => mkdirIfNeeded, + nodePlatform: () => nodePlatform, + parsePattern: () => parsePattern, + perMessageDeflate: () => perMessageDeflate, + removeFolders: () => removeFolders, + resolveWithinRoot: () => resolveWithinRoot, + rgb2gray: () => rgb2gray, + sanitizeForFilePath: () => sanitizeForFilePath, + serveFolder: () => serveFolder, + setBoxedStackPrefixes: () => setBoxedStackPrefixes, + setPlaywrightTestProcessEnv: () => setPlaywrightTestProcessEnv, + shortPlatform: () => shortPlatform, + spawnAsync: () => spawnAsync, + srgb2xyz: () => srgb2xyz, + ssim: () => ssim, + startHttpServer: () => startHttpServer, + startProfiling: () => startProfiling, + stopProfiling: () => stopProfiling, + stringWidth: () => stringWidth, + toPosixPath: () => toPosixPath, + urlHostFromAddress: () => urlHostFromAddress, + wrapInASCIIBox: () => wrapInASCIIBox, + xyz2lab: () => xyz2lab +}); +var init_utils = __esm({ + "packages/utils/index.ts"() { + "use strict"; + init_ascii(); + init_chromiumChannels(); + init_comparators(); + init_crypto(); + init_debug(); + init_debugLogger(); + init_env(); + init_eventsHelper(); + init_fileUtils(); + init_hostPlatform(); + init_httpServer(); + init_network(); + init_nodePlatform(); + init_processLauncher(); + init_profiler(); + init_serializedFS(); + init_socksProxy(); + init_spawnAsync(); + init_stringWidth(); + init_task(); + init_wsServer(); + init_zipFile(); + init_zones(); + init_extractZip(); + init_lockfile(); + init_colorUtils(); + init_compare(); + init_imageChannel(); + init_stats(); + } +}); + +// packages/playwright-core/src/client/eventEmitter.ts +function checkListener(listener) { + if (typeof listener !== "function") + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); +} +function unwrapListener(l) { + return wrappedListener(l) ?? l; +} +function unwrapListeners(arr) { + return arr.map((l) => wrappedListener(l) ?? l); +} +function wrappedListener(l) { + return l.listener; +} +var EventEmitter3, OnceWrapper; +var init_eventEmitter = __esm({ + "packages/playwright-core/src/client/eventEmitter.ts"() { + "use strict"; + EventEmitter3 = class { + 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(type3, ...args) { + const events = this._events; + if (events === void 0) + return false; + const handler = events?.[type3]; + if (handler === void 0) + return false; + if (typeof handler === "function") { + this._callHandler(type3, handler, args); + } else { + const len = handler.length; + const listeners = handler.slice(); + for (let i = 0; i < len; ++i) + this._callHandler(type3, listeners[i], args); + } + return true; + } + _callHandler(type3, handler, args) { + const promise = Reflect.apply(handler, this, args); + if (!(promise instanceof Promise)) + return; + let set = this._pendingHandlers.get(type3); + if (!set) { + set = /* @__PURE__ */ new Set(); + this._pendingHandlers.set(type3, set); + } + set.add(promise); + promise.catch((e) => { + if (this._rejectionHandler) + this._rejectionHandler(e); + else + throw e; + }).finally(() => set.delete(promise)); + } + addListener(type3, listener) { + return this._addListener(type3, listener, false); + } + on(type3, listener) { + return this._addListener(type3, listener, false); + } + _addListener(type3, listener, prepend) { + checkListener(listener); + let events = this._events; + let existing; + if (events === void 0) { + events = this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } else { + if (events.newListener !== void 0) { + this.emit("newListener", type3, unwrapListener(listener)); + events = this._events; + } + existing = events[type3]; + } + if (existing === void 0) { + existing = events[type3] = listener; + ++this._eventsCount; + } else { + if (typeof existing === "function") { + existing = events[type3] = 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(type3) + " listeners added. Use emitter.setMaxListeners() to increase limit"); + w.name = "MaxListenersExceededWarning"; + w.emitter = this; + w.type = type3; + w.count = existing.length; + if (!this._platform.isUnderTest()) { + console.warn(w); + } + } + } + return this; + } + prependListener(type3, listener) { + return this._addListener(type3, listener, true); + } + once(type3, listener) { + checkListener(listener); + this.on(type3, new OnceWrapper(this, type3, listener).wrapperFunction); + return this; + } + prependOnceListener(type3, listener) { + checkListener(listener); + this.prependListener(type3, new OnceWrapper(this, type3, listener).wrapperFunction); + return this; + } + removeListener(type3, listener) { + checkListener(listener); + const events = this._events; + if (events === void 0) + return this; + const list = events[type3]; + if (list === void 0) + return this; + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) { + this._events = /* @__PURE__ */ Object.create(null); + } else { + delete events[type3]; + if (events.removeListener) + this.emit("removeListener", type3, 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) + events[type3] = list[0]; + if (events.removeListener !== void 0) + this.emit("removeListener", type3, originalListener || listener); + } + return this; + } + off(type3, listener) { + return this.removeListener(type3, listener); + } + removeAllListeners(type3, options2) { + this._removeAllListeners(type3); + if (!options2) + return this; + if (options2.behavior === "wait") { + const errors = []; + this._rejectionHandler = (error) => errors.push(error); + return this._waitFor(type3).then(() => { + if (errors.length) + throw errors[0]; + }); + } + if (options2.behavior === "ignoreErrors") + this._rejectionHandler = () => { + }; + return Promise.resolve(); + } + _removeAllListeners(type3) { + const events = this._events; + if (!events) + return; + if (!events.removeListener) { + if (type3 === void 0) { + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } else if (events[type3] !== void 0) { + if (--this._eventsCount === 0) + this._events = /* @__PURE__ */ Object.create(null); + else + delete events[type3]; + } + return; + } + if (type3 === void 0) { + const keys = Object.keys(events); + let key; + for (let i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === "removeListener") + continue; + this._removeAllListeners(key); + } + this._removeAllListeners("removeListener"); + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + return; + } + const listeners = events[type3]; + if (typeof listeners === "function") { + this.removeListener(type3, listeners); + } else if (listeners !== void 0) { + for (let i = listeners.length - 1; i >= 0; i--) + this.removeListener(type3, listeners[i]); + } + } + listeners(type3) { + return this._listeners(this, type3, true); + } + rawListeners(type3) { + return this._listeners(this, type3, false); + } + listenerCount(type3) { + const events = this._events; + if (events !== void 0) { + const listener = events[type3]; + 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(type3) { + let promises = []; + if (type3) { + promises = [...this._pendingHandlers.get(type3) || []]; + } else { + promises = []; + for (const [, pending] of this._pendingHandlers) + promises.push(...pending); + } + await Promise.all(promises); + } + _listeners(target, type3, unwrap) { + const events = target._events; + if (events === void 0) + return []; + const listener = events[type3]; + if (listener === void 0) + return []; + if (typeof listener === "function") + return unwrap ? [unwrapListener(listener)] : [listener]; + return unwrap ? unwrapListeners(listener) : listener.slice(); + } + }; + OnceWrapper = class { + 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); + } + }; + } +}); + +// packages/playwright-core/src/bootstrap.ts +var init_bootstrap = __esm({ + "packages/playwright-core/src/bootstrap.ts"() { + "use strict"; + if (process.env.PW_INSTRUMENT_MODULES) { + const Module = require("module"); + const originalLoad = Module._load; + const root = { name: "", selfMs: 0, totalMs: 0, childrenMs: 0, children: [] }; + let current = root; + const stack = []; + Module._load = function(request2, _parent, _isMain) { + const node = { name: request2, selfMs: 0, totalMs: 0, childrenMs: 0, children: [] }; + current.children.push(node); + stack.push(current); + current = node; + const start3 = performance.now(); + let result2; + try { + result2 = originalLoad.apply(this, arguments); + } catch (e) { + current = stack.pop(); + current.children.pop(); + throw e; + } + const duration = performance.now() - start3; + node.totalMs = duration; + node.selfMs = Math.max(0, duration - node.childrenMs); + current = stack.pop(); + current.childrenMs += duration; + return result2; + }; + process.on("exit", () => { + function printTree(node, prefix, isLast, lines2, depth) { + if (node.totalMs < 1 && depth > 0) + return; + const connector = depth === 0 ? "" : isLast ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 "; + const time = `${node.totalMs.toFixed(1).padStart(8)}ms`; + const self = node.children.length ? ` (self: ${node.selfMs.toFixed(1)}ms)` : ""; + lines2.push(`${time} ${prefix}${connector}${node.name}${self}`); + const childPrefix = prefix + (depth === 0 ? "" : isLast ? " " : "\u2502 "); + const sorted2 = node.children.slice().sort((a, b) => b.totalMs - a.totalMs); + for (let i = 0; i < sorted2.length; i++) + printTree(sorted2[i], childPrefix, i === sorted2.length - 1, lines2, depth + 1); + } + let totalModules = 0; + function count(n) { + totalModules++; + n.children.forEach(count); + } + root.children.forEach(count); + const lines = []; + const sorted = root.children.slice().sort((a, b) => b.totalMs - a.totalMs); + for (let i = 0; i < sorted.length; i++) + printTree(sorted[i], "", i === sorted.length - 1, lines, 0); + const totalMs = root.children.reduce((s, c) => s + c.totalMs, 0); + process.stderr.write(` +--- Module load tree: ${totalModules} modules, ${totalMs.toFixed(0)}ms total --- +` + lines.join("\n") + "\n"); + const flat = /* @__PURE__ */ new Map(); + function gather(n) { + const existing = flat.get(n.name); + if (existing) { + existing.selfMs += n.selfMs; + existing.totalMs += n.totalMs; + existing.count++; + } else { + flat.set(n.name, { selfMs: n.selfMs, totalMs: n.totalMs, count: 1 }); + } + n.children.forEach(gather); + } + root.children.forEach(gather); + const top50 = [...flat.entries()].sort((a, b) => b[1].selfMs - a[1].selfMs).slice(0, 50); + const flatLines = top50.map( + ([mod, { selfMs, totalMs: totalMs2, count: count2 }]) => `${selfMs.toFixed(1).padStart(8)}ms self ${totalMs2.toFixed(1).padStart(8)}ms total (x${String(count2).padStart(3)}) ${mod}` + ); + process.stderr.write(` +--- Top 50 modules by self time --- +` + flatLines.join("\n") + "\n"); + }); + } + } +}); + +// packages/playwright-core/src/package.ts +function libPath(...parts) { + return import_path8.default.join(packageRoot, "lib", ...parts); +} +var import_path8, packageRoot, packageJSON, binPath; +var init_package = __esm({ + "packages/playwright-core/src/package.ts"() { + "use strict"; + import_path8 = __toESM(require("path")); + packageRoot = import_path8.default.join(__dirname, ".."); + packageJSON = require(import_path8.default.join(packageRoot, "package.json")); + binPath = import_path8.default.join(packageRoot, "bin"); + } +}); + +// packages/playwright-core/src/tools/trace/traceParser.ts +async function extractTrace(traceFile, outDir) { + const zipFile = new ZipFile(traceFile); + try { + const entries = await zipFile.entries(); + for (const entry of entries) { + const outPath = resolveWithinRoot(outDir, entry); + if (!outPath) + throw new Error(`Trace entry '${entry}' escapes output directory`); + await import_fs10.default.promises.mkdir(import_path9.default.dirname(outPath), { recursive: true }); + const buffer = await zipFile.read(entry); + await import_fs10.default.promises.writeFile(outPath, buffer); + } + } finally { + zipFile.close(); + } +} +var import_fs10, import_path9, DirTraceLoaderBackend; +var init_traceParser = __esm({ + "packages/playwright-core/src/tools/trace/traceParser.ts"() { + "use strict"; + import_fs10 = __toESM(require("fs")); + import_path9 = __toESM(require("path")); + init_fileUtils(); + init_zipFile(); + DirTraceLoaderBackend = class { + constructor(dir) { + this._dir = dir; + } + isLive() { + return false; + } + async entryNames() { + const entries = []; + const walk = async (dir, prefix) => { + const items = await import_fs10.default.promises.readdir(dir, { withFileTypes: true }); + for (const item of items) { + if (item.isDirectory()) + await walk(import_path9.default.join(dir, item.name), prefix ? `${prefix}/${item.name}` : item.name); + else + entries.push(prefix ? `${prefix}/${item.name}` : item.name); + } + }; + await walk(this._dir, ""); + return entries; + } + async hasEntry(entryName) { + const resolved = resolveWithinRoot(this._dir, entryName); + if (!resolved) + return false; + try { + await import_fs10.default.promises.access(resolved); + return true; + } catch { + return false; + } + } + async readText(entryName) { + const resolved = resolveWithinRoot(this._dir, entryName); + if (!resolved) + return; + try { + return await import_fs10.default.promises.readFile(resolved, "utf-8"); + } catch { + } + } + async readBlob(entryName) { + const resolved = resolveWithinRoot(this._dir, entryName); + if (!resolved) + return; + try { + const buffer = await import_fs10.default.promises.readFile(resolved); + return new Blob([new Uint8Array(buffer)]); + } catch { + } + } + }; + } +}); + +// packages/playwright-core/src/tools/trace/traceUtils.ts +function ensureTraceOpen() { + if (!import_fs11.default.existsSync(traceDir)) + throw new Error(`No trace opened. Run 'npx playwright trace open ' first.`); + return traceDir; +} +async function closeTrace() { + if (import_fs11.default.existsSync(traceDir)) + await import_fs11.default.promises.rm(traceDir, { recursive: true }); +} +async function openTrace(traceFile) { + const filePath = import_path10.default.resolve(traceFile); + if (!import_fs11.default.existsSync(filePath)) + throw new Error(`Trace file not found: ${filePath}`); + await closeTrace(); + await import_fs11.default.promises.mkdir(traceDir, { recursive: true }); + if (filePath.endsWith(".zip")) + await extractTrace(filePath, traceDir); + else + await import_fs11.default.promises.writeFile(import_path10.default.join(traceDir, ".link"), filePath, "utf-8"); +} +async function loadTrace() { + const dir = ensureTraceOpen(); + const linkFile = import_path10.default.join(dir, ".link"); + let traceDir2; + let traceFile; + if (import_fs11.default.existsSync(linkFile)) { + const tracePath = await import_fs11.default.promises.readFile(linkFile, "utf-8"); + traceDir2 = import_path10.default.dirname(tracePath); + traceFile = import_path10.default.basename(tracePath); + } else { + traceDir2 = dir; + } + const backend = new DirTraceLoaderBackend(traceDir2); + const loader = new TraceLoader(); + await loader.load(backend, traceFile); + const model = new TraceModel(traceDir2, loader.contextEntries); + return new LoadedTrace(model, loader, buildOrdinalMap(model)); +} +function formatTimestamp(ms, base) { + const relative = ms - base; + if (relative < 0) + return "0:00.000"; + const totalMs = Math.floor(relative); + const minutes = Math.floor(totalMs / 6e4); + const seconds = Math.floor(totalMs % 6e4 / 1e3); + const millis = totalMs % 1e3; + return `${minutes}:${seconds.toString().padStart(2, "0")}.${millis.toString().padStart(3, "0")}`; +} +function actionTitle(action) { + return renderTitleForCall({ ...action, type: action.class }) || `${action.class}.${action.method}`; +} +async function saveOutputFile(fileName, content, explicitOutput) { + let outFile; + if (explicitOutput) { + outFile = explicitOutput; + } else { + const resolved = resolveWithinRoot(cliOutputDir, fileName); + if (!resolved) + throw new Error(`Attachment name '${fileName}' escapes output directory`); + await import_fs11.default.promises.mkdir(import_path10.default.dirname(resolved), { recursive: true }); + outFile = resolved; + } + await import_fs11.default.promises.writeFile(outFile, content); + return outFile; +} +function buildOrdinalMap(model) { + const actions = model.actions.filter((a) => a.group !== "configuration"); + const { rootItem } = buildActionTree(actions); + const ordinalToCallId = /* @__PURE__ */ new Map(); + const callIdToOrdinal = /* @__PURE__ */ new Map(); + let ordinal = 1; + const visit = (item) => { + ordinalToCallId.set(ordinal, item.action.callId); + callIdToOrdinal.set(item.action.callId, ordinal); + ordinal++; + for (const child of item.children) + visit(child); + }; + for (const child of rootItem.children) + visit(child); + return { ordinalToCallId, callIdToOrdinal }; +} +var import_fs11, import_path10, traceDir, cliOutputDir, LoadedTrace; +var init_traceUtils2 = __esm({ + "packages/playwright-core/src/tools/trace/traceUtils.ts"() { + "use strict"; + import_fs11 = __toESM(require("fs")); + import_path10 = __toESM(require("path")); + init_traceModel(); + init_traceLoader(); + init_protocolFormatter(); + init_fileUtils(); + init_traceParser(); + traceDir = import_path10.default.join(".playwright-cli", "trace"); + cliOutputDir = ".playwright-cli"; + LoadedTrace = class { + constructor(model, loader, ordinals) { + this.model = model; + this.loader = loader; + this.ordinalToCallId = ordinals.ordinalToCallId; + this.callIdToOrdinal = ordinals.callIdToOrdinal; + } + resolveActionId(actionId) { + const ordinal = parseInt(actionId, 10); + if (!isNaN(ordinal)) { + const callId = this.ordinalToCallId.get(ordinal); + if (callId) + return this.model.actions.find((a) => a.callId === callId); + } + return this.model.actions.find((a) => a.callId === actionId); + } + }; + } +}); + +// packages/playwright-core/src/tools/trace/traceOpen.ts +async function traceOpen(traceFile) { + await openTrace(traceFile); + await traceInfo(); +} +async function traceInfo() { + const trace = await loadTrace(); + const model = trace.model; + const info = { + browser: model.browserName || "unknown", + platform: model.platform || "unknown", + playwrightVersion: model.playwrightVersion || "unknown", + title: model.title || "", + duration: msToString(model.endTime - model.startTime), + durationMs: model.endTime - model.startTime, + startTime: model.wallTime ? new Date(model.wallTime).toISOString() : "unknown", + viewport: model.options.viewport ? `${model.options.viewport.width}x${model.options.viewport.height}` : "default", + actions: model.actions.length, + pages: model.pages.length, + network: model.resources.length, + errors: model.errorDescriptors.length, + attachments: model.attachments.length, + consoleMessages: model.events.filter((e) => e.type === "console").length + }; + console.log(""); + console.log(` Browser: ${info.browser}`); + console.log(` Platform: ${info.platform}`); + console.log(` Playwright: ${info.playwrightVersion}`); + if (info.title) + console.log(` Title: ${info.title}`); + console.log(` Duration: ${info.duration}`); + console.log(` Start time: ${info.startTime}`); + console.log(` Viewport: ${info.viewport}`); + console.log(` Actions: ${info.actions}`); + console.log(` Pages: ${info.pages}`); + console.log(` Network: ${info.network} requests`); + console.log(` Errors: ${info.errors}`); + console.log(` Attachments: ${info.attachments}`); + console.log(` Console: ${info.consoleMessages} messages`); + console.log(""); +} +var init_traceOpen = __esm({ + "packages/playwright-core/src/tools/trace/traceOpen.ts"() { + "use strict"; + init_formatUtils(); + init_traceUtils2(); + } +}); + +// packages/playwright-core/src/tools/trace/traceActions.ts +async function traceActions(options2) { + const trace = await loadTrace(); + const actions = filterActions(trace.model.actions, options2); + const { rootItem } = buildActionTree(actions); + console.log(` ${"#".padStart(4)} ${"Time".padEnd(9)} ${"Action".padEnd(55)} ${"Duration".padStart(8)}`); + console.log(` ${"\u2500".repeat(4)} ${"\u2500".repeat(9)} ${"\u2500".repeat(55)} ${"\u2500".repeat(8)}`); + const visit = (item, indent) => { + const action = item.action; + const ordinal = trace.callIdToOrdinal.get(action.callId) ?? "?"; + const ts = formatTimestamp(action.startTime, trace.model.startTime); + const duration = action.endTime ? msToString(action.endTime - action.startTime) : "running"; + const title = actionTitle(action); + const locator2 = actionLocator(action); + const error = action.error ? " \u2717" : ""; + const prefix = ` ${(ordinal + ".").padStart(4)} ${ts} ${indent}`; + console.log(`${prefix}${title.padEnd(Math.max(1, 55 - indent.length))} ${duration.padStart(8)}${error}`); + if (locator2) + console.log(`${" ".repeat(prefix.length)}${locator2}`); + for (const child of item.children) + visit(child, indent + " "); + }; + for (const child of rootItem.children) + visit(child, ""); +} +function filterActions(actions, options2) { + let result2 = actions.filter((a) => a.group !== "configuration"); + if (options2.grep) { + const pattern = new RegExp(options2.grep, "i"); + result2 = result2.filter((a) => pattern.test(actionTitle(a)) || pattern.test(actionLocator(a) || "")); + } + if (options2.errorsOnly) + result2 = result2.filter((a) => !!a.error); + return result2; +} +function actionLocator(action, sdkLanguage) { + return action.params.selector ? asLocatorDescription(sdkLanguage || "javascript", action.params.selector) : void 0; +} +async function traceAction(actionId) { + const trace = await loadTrace(); + const action = trace.resolveActionId(actionId); + if (!action) { + console.error(`Action '${actionId}' not found. Use 'trace actions' to see available action IDs.`); + process.exitCode = 1; + return; + } + const title = actionTitle(action); + console.log(` + ${title} +`); + console.log(" Time"); + console.log(` start: ${formatTimestamp(action.startTime, trace.model.startTime)}`); + const duration = action.endTime ? msToString(action.endTime - action.startTime) : action.error ? "Timed Out" : "Running"; + console.log(` duration: ${duration}`); + const paramKeys = Object.keys(action.params).filter((name) => name !== "info"); + if (paramKeys.length) { + console.log("\n Parameters"); + for (const key of paramKeys) { + const value2 = formatParamValue(action.params[key]); + console.log(` ${key}: ${value2}`); + } + } + if (action.result) { + console.log("\n Return value"); + for (const [key, value2] of Object.entries(action.result)) + console.log(` ${key}: ${formatParamValue(value2)}`); + } + if (action.error) { + console.log("\n Error"); + console.log(` ${action.error.message}`); + } + if (action.log.length) { + console.log("\n Log"); + for (const entry of action.log) { + const time = entry.time !== -1 ? formatTimestamp(entry.time, trace.model.startTime) : ""; + console.log(` ${time.padEnd(12)} ${entry.message}`); + } + } + if (action.stack?.length) { + console.log("\n Source"); + for (const frame of action.stack.slice(0, 5)) { + const file = frame.file.replace(/.*[/\\](.*)/, "$1"); + console.log(` ${file}:${frame.line}:${frame.column}`); + } + } + const snapshots = []; + if (action.beforeSnapshot) + snapshots.push("before"); + if (action.inputSnapshot) + snapshots.push("input"); + if (action.afterSnapshot) + snapshots.push("after"); + if (snapshots.length) { + console.log("\n Snapshots"); + console.log(` available: ${snapshots.join(", ")}`); + console.log(` usage: npx playwright trace snapshot ${actionId} --name <${snapshots.join("|")}>`); + } + console.log(""); +} +function formatParamValue(value2) { + if (value2 === void 0 || value2 === null) + return String(value2); + if (typeof value2 === "string") + return `"${value2}"`; + if (typeof value2 !== "object") + return String(value2); + if (value2.guid) + return ""; + return JSON.stringify(value2).slice(0, 1e3); +} +var init_traceActions = __esm({ + "packages/playwright-core/src/tools/trace/traceActions.ts"() { + "use strict"; + init_traceModel(); + init_locatorGenerators(); + init_formatUtils(); + init_traceUtils2(); + } +}); + +// packages/playwright-core/src/tools/trace/traceRequests.ts +async function traceRequests(options2) { + const trace = await loadTrace(); + const model = trace.model; + let indexed = model.resources.map((r, i) => ({ resource: r, ordinal: i + 1 })); + if (options2.grep) { + const pattern = new RegExp(options2.grep, "i"); + indexed = indexed.filter(({ resource: r }) => pattern.test(r.request.url)); + } + if (options2.method) + indexed = indexed.filter(({ resource: r }) => r.request.method.toLowerCase() === options2.method.toLowerCase()); + if (options2.status) { + const code = parseInt(options2.status, 10); + indexed = indexed.filter(({ resource: r }) => r.response.status === code); + } + if (options2.failed) + indexed = indexed.filter(({ resource: r }) => r.response.status >= 400 || r.response.status === -1); + if (!indexed.length) { + console.log(" No network requests"); + return; + } + console.log(` ${"#".padStart(4)} ${"Method".padEnd(8)} ${"Status".padEnd(8)} ${"Name".padEnd(45)} ${"Duration".padStart(10)} ${"Size".padStart(8)} ${"Route".padEnd(10)}`); + console.log(` ${"\u2500".repeat(4)} ${"\u2500".repeat(8)} ${"\u2500".repeat(8)} ${"\u2500".repeat(45)} ${"\u2500".repeat(10)} ${"\u2500".repeat(8)} ${"\u2500".repeat(10)}`); + for (const { resource: r, ordinal } of indexed) { + let name; + try { + const url2 = new URL(r.request.url); + name = url2.pathname.substring(url2.pathname.lastIndexOf("/") + 1); + if (!name) + name = url2.host; + if (url2.search) + name += url2.search; + } catch { + name = r.request.url; + } + if (name.length > 45) + name = name.substring(0, 42) + "..."; + const status = r.response.status > 0 ? String(r.response.status) : "ERR"; + const size = r.response._transferSize > 0 ? r.response._transferSize : r.response.bodySize; + const route2 = formatRouteStatus(r); + console.log(` ${(ordinal + ".").padStart(4)} ${r.request.method.padEnd(8)} ${status.padEnd(8)} ${name.padEnd(45)} ${msToString(r.time).padStart(10)} ${bytesToString2(size).padStart(8)} ${route2.padEnd(10)}`); + } +} +async function traceRequest(requestId) { + const trace = await loadTrace(); + const model = trace.model; + const ordinal = parseInt(requestId, 10); + const resource = !isNaN(ordinal) && ordinal >= 1 && ordinal <= model.resources.length ? model.resources[ordinal - 1] : void 0; + if (!resource) { + console.error(`Request '${requestId}' not found. Use 'trace requests' to see available request IDs.`); + process.exitCode = 1; + return; + } + const r = resource; + const status = r.response.status > 0 ? `${r.response.status} ${r.response.statusText}` : "ERR"; + const size = r.response._transferSize > 0 ? r.response._transferSize : r.response.bodySize; + console.log(` + ${r.request.method} ${r.request.url} +`); + console.log(" General"); + console.log(` status: ${status}`); + console.log(` duration: ${msToString(r.time)}`); + console.log(` size: ${bytesToString2(size)}`); + if (r.response.content.mimeType) + console.log(` type: ${r.response.content.mimeType}`); + const route2 = formatRouteStatus(r); + if (route2) + console.log(` route: ${route2}`); + if (r.serverIPAddress) + console.log(` server: ${r.serverIPAddress}${r._serverPort ? ":" + r._serverPort : ""}`); + if (r.response._failureText) + console.log(` error: ${r.response._failureText}`); + if (r.request.headers.length) { + console.log("\n Request headers"); + for (const h of r.request.headers) + console.log(` ${h.name}: ${h.value}`); + } + if (r.request.postData) { + console.log("\n Request body"); + const resource2 = r.request.postData._sha1 ?? r.request.postData._file; + if (resource2) { + console.log(` ${import_path11.default.relative(process.cwd(), import_path11.default.join(trace.model.traceUri, "resources", resource2))}`); + } else { + const text2 = r.request.postData.text.length > 2e3 ? r.request.postData.text.substring(0, 2e3) + "..." : r.request.postData.text; + console.log(` ${text2}`); + } + } + if (r.response.headers.length) { + console.log("\n Response headers"); + for (const h of r.response.headers) + console.log(` ${h.name}: ${h.value}`); + } + if (r.response.bodySize > 0) { + const resource2 = r.response.content._sha1 ?? r.response.content._file; + if (resource2) { + console.log("\n Response body"); + console.log(` ${import_path11.default.relative(process.cwd(), import_path11.default.join(trace.model.traceUri, "resources", resource2))}`); + } else if (r.response.content.text) { + const text2 = r.response.content.text.length > 2e3 ? r.response.content.text.substring(0, 2e3) + "..." : r.response.content.text; + console.log("\n Response body"); + console.log(` ${text2}`); + } + } + if (r._securityDetails) { + console.log("\n Security"); + if (r._securityDetails.protocol) + console.log(` protocol: ${r._securityDetails.protocol}`); + if (r._securityDetails.subjectName) + console.log(` subject: ${r._securityDetails.subjectName}`); + if (r._securityDetails.issuer) + console.log(` issuer: ${r._securityDetails.issuer}`); + } + console.log(""); +} +function bytesToString2(bytes) { + if (bytes < 0 || !isFinite(bytes)) + return "-"; + if (bytes === 0) + return "0"; + if (bytes < 1e3) + return bytes.toFixed(0); + const kb = bytes / 1024; + if (kb < 1e3) + return kb.toFixed(1) + "K"; + const mb = kb / 1024; + if (mb < 1e3) + return mb.toFixed(1) + "M"; + const gb = mb / 1024; + return gb.toFixed(1) + "G"; +} +function formatRouteStatus(r) { + if (r._wasAborted) + return "aborted"; + if (r._wasContinued) + return "continued"; + if (r._wasFulfilled) + return "fulfilled"; + if (r._apiRequest) + return "api"; + return ""; +} +var import_path11; +var init_traceRequests = __esm({ + "packages/playwright-core/src/tools/trace/traceRequests.ts"() { + "use strict"; + import_path11 = __toESM(require("path")); + init_formatUtils(); + init_traceUtils2(); + } +}); + +// packages/playwright-core/src/tools/trace/traceConsole.ts +async function traceConsole(options2) { + const trace = await loadTrace(); + const model = trace.model; + const items = []; + for (const event of model.events) { + if (event.type === "console") { + if (options2.stdio) + continue; + const level = event.messageType; + if (options2.errorsOnly && level !== "error") + continue; + if (options2.warnings && level !== "error" && level !== "warning") + continue; + const url2 = event.location.url; + const filename = url2 ? url2.substring(url2.lastIndexOf("/") + 1) : ""; + items.push({ + type: "browser", + level, + text: event.text, + location: `${filename}:${event.location.lineNumber}`, + timestamp: event.time + }); + } + if (event.type === "event" && event.method === "pageError") { + if (options2.stdio) + continue; + const error = event.params.error; + items.push({ + type: "browser", + level: "error", + text: error?.error?.message || String(error?.value || ""), + timestamp: event.time + }); + } + } + for (const event of model.stdio) { + if (options2.browser) + continue; + if (options2.errorsOnly && event.type !== "stderr") + continue; + if (options2.warnings && event.type !== "stderr") + continue; + let text2 = ""; + if (event.text) + text2 = event.text.trim(); + if (event.base64) + text2 = Buffer.from(event.base64, "base64").toString("utf-8").trim(); + if (!text2) + continue; + items.push({ + type: event.type, + level: event.type === "stderr" ? "error" : "info", + text: text2, + timestamp: event.timestamp + }); + } + items.sort((a, b) => a.timestamp - b.timestamp); + if (!items.length) { + console.log(" No console entries"); + return; + } + for (const item of items) { + const ts = formatTimestamp(item.timestamp, model.startTime); + const source8 = item.type === "browser" ? "[browser]" : `[${item.type}]`; + const level = item.level.padEnd(8); + const location2 = item.location ? ` ${item.location}` : ""; + console.log(` ${ts} ${source8.padEnd(10)} ${level} ${item.text}${location2}`); + } +} +var init_traceConsole = __esm({ + "packages/playwright-core/src/tools/trace/traceConsole.ts"() { + "use strict"; + init_traceUtils2(); + } +}); + +// packages/playwright-core/src/tools/trace/traceErrors.ts +async function traceErrors() { + const trace = await loadTrace(); + const model = trace.model; + if (!model.errorDescriptors.length) { + console.log(" No errors"); + return; + } + for (const error of model.errorDescriptors) { + if (error.action) { + const title = actionTitle(error.action); + console.log(` + \u2717 ${title}`); + } else { + console.log(` + \u2717 Error`); + } + if (error.stack?.length) { + const frame = error.stack[0]; + const file = frame.file.replace(/.*[/\\](.*)/, "$1"); + console.log(` at ${file}:${frame.line}:${frame.column}`); + } + console.log(""); + const indented = error.message.split("\n").map((l) => ` ${l}`).join("\n"); + console.log(indented); + } + console.log(""); +} +var init_traceErrors = __esm({ + "packages/playwright-core/src/tools/trace/traceErrors.ts"() { + "use strict"; + init_traceUtils2(); + } +}); + +// packages/isomorphic/disposable.ts +async function disposeAll(disposables) { + const copy = [...disposables]; + disposables.length = 0; + await Promise.all(copy.map((d) => d.dispose())); +} +var init_disposable = __esm({ + "packages/isomorphic/disposable.ts"() { + "use strict"; + } +}); + +// packages/playwright-core/src/server/userAgent.ts +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 version3 = import_os4.default.release().split("."); + osIdentifier = "windows"; + osVersion = `${version3[0]}.${version3[1]}`; + } else if (process.platform === "darwin") { + const version3 = (0, import_child_process2.execSync)("sw_vers -productVersion", { stdio: ["ignore", "pipe", "ignore"] }).toString().trim().split("."); + osIdentifier = "macOS"; + osVersion = `${version3[0]}.${version3[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 (process.env.CI) + additionalTokens.push("CI/1"); + const serializedTokens = additionalTokens.length ? " " + additionalTokens.join(" ") : ""; + const { embedderName, embedderVersion } = getEmbedderName(); + return `Playwright/${getPlaywrightVersion()} (${import_os4.default.arch()}; ${osIdentifier} ${osVersion}) ${embedderName}/${embedderVersion}${serializedTokens}`; +} +function getEmbedderName() { + let embedderName = "unknown"; + let embedderVersion = "unknown"; + if (!process.env.PW_LANG_NAME) { + embedderName = "node"; + embedderVersion = process.version.substring(1).split(".").slice(0, 2).join("."); + } else if (["node", "python", "java", "csharp"].includes(process.env.PW_LANG_NAME)) { + embedderName = process.env.PW_LANG_NAME; + embedderVersion = process.env.PW_LANG_NAME_VERSION ?? "unknown"; + } + return { embedderName, embedderVersion }; +} +function getPlaywrightVersion(majorMinorOnly = false) { + const version3 = process.env.PW_VERSION_OVERRIDE || packageJSON.version; + return majorMinorOnly ? version3.split(".").slice(0, 2).join(".") : version3; +} +var import_child_process2, import_os4, cachedUserAgent; +var init_userAgent = __esm({ + "packages/playwright-core/src/server/userAgent.ts"() { + "use strict"; + import_child_process2 = require("child_process"); + import_os4 = __toESM(require("os")); + init_linuxUtils(); + init_package(); + } +}); + +// packages/playwright-core/src/generated/clockSource.ts +var source; +var init_clockSource = __esm({ + "packages/playwright-core/src/generated/clockSource.ts"() { + "use strict"; + source = '\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._innerInstall(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 _innerInstall(time) {\n if (this._now.origin < 0)\n this._now.ticks = 0;\n this._innerSetTime(time);\n }\n _innerSetFixedTime(time) {\n this._innerSetTime(time);\n this._now.isFixedTime = true;\n }\n _advanceNow(to) {\n if (this._now.ticks > to) {\n return;\n }\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._runWithDisabledRealTimeSync(async () => {\n await this._runTo(shiftTicks(this._now.ticks, ticks));\n });\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 await this._innerPause();\n const toConsume = time - this._now.time;\n await this._innerFastForwardTo(shiftTicks(this._now.ticks, toConsume));\n return toConsume;\n }\n async _innerPause() {\n var _a;\n this._realTime = void 0;\n await ((_a = this._currentRealTimeTimer) == null ? void 0 : _a.dispose());\n this._currentRealTimeTimer = void 0;\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 ((_a = this._currentRealTimeTimer) == null ? void 0 : _a.promise) {\n return;\n }\n const firstTimer = this._firstTimer();\n const nextTick = Math.min(firstTimer ? firstTimer.callAt : this._now.ticks + maxTimeout, this._now.ticks + 100);\n const callAt = this._currentRealTimeTimer ? Math.min(this._currentRealTimeTimer.callAt, nextTick) : nextTick;\n if (this._currentRealTimeTimer) {\n this._currentRealTimeTimer.cancel();\n this._currentRealTimeTimer = void 0;\n }\n const realTimeTimer = {\n callAt,\n promise: void 0,\n cancel: this._embedder.setTimeout(() => {\n this._syncRealTime();\n realTimeTimer.promise = this._runTo(this._now.ticks).catch((e) => console.error(e));\n void realTimeTimer.promise.then(() => {\n this._currentRealTimeTimer = void 0;\n if (this._realTime)\n this._updateRealTimeTimer();\n });\n }, callAt - this._now.ticks),\n dispose: async () => {\n realTimeTimer.cancel();\n await realTimeTimer.promise;\n }\n };\n this._currentRealTimeTimer = realTimeTimer;\n }\n async _runWithDisabledRealTimeSync(fn) {\n if (!this._realTime) {\n await fn();\n return;\n }\n await this._innerPause();\n try {\n await fn();\n } finally {\n this._innerResume();\n }\n }\n async fastForward(ticks) {\n this._replayLogOnce();\n await this._runWithDisabledRealTimeSync(async () => {\n await this._innerFastForwardTo(shiftTicks(this._now.ticks, ticks | 0));\n });\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 this._replayLogOnce();\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._innerInstall(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._innerSetTime(asWallTime(param));\n } else if (type === "resume") {\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) {\n if (lastLogTime > 0)\n this._advanceNow(shiftTicks(this._now.ticks, this._embedder.dateNow() - lastLogTime));\n this._innerResume();\n } else {\n this._realTime = void 0;\n }\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 AbortSignal: globalObject.AbortSignal\n };\n const bound = { ...raw };\n for (const key of Object.keys(bound)) {\n if (key !== "Date" && key !== "AbortSignal" && 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, browserName) {\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 AbortSignal: originals.AbortSignal ? fakeAbortSignal(clock, originals.AbortSignal, browserName) : void 0\n };\n}\nfunction getClearHandler(type) {\n if (type === "IdleCallback" || type === "AnimationFrame")\n return `cancel${type}`;\n return `clear${type}`;\n}\nvar FakePerformanceEntry = class {\n constructor(name, entryType, startTime, duration) {\n this.name = name;\n this.entryType = entryType;\n this.startTime = startTime;\n this.duration = duration;\n }\n toJSON() {\n return JSON.stringify({ ...this });\n }\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 if (key === "mark")\n result[key] = (name) => new FakePerformanceEntry(name, "mark", 0, 0);\n else if (key === "measure")\n result[key] = (name) => new FakePerformanceEntry(name, "measure", 0, 50);\n else\n result[key] = () => {\n };\n }\n return result;\n}\nfunction fakeAbortSignal(clock, abortSignal, browserName) {\n Object.defineProperty(abortSignal, "timeout", {\n value(ms) {\n const controller = new AbortController();\n clock.addTimer({\n delay: ms,\n type: "Timeout" /* Timeout */,\n func: () => controller.abort(\n new DOMException(\n browserName === "chromium" ? "signal timed out" : "The operation timed out.",\n "TimeoutError"\n )\n )\n });\n return controller.signal;\n }\n });\n return abortSignal;\n}\nfunction createClock(globalObject, config = {}) {\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, config.browserName);\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, config);\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 === "AbortSignal") {\n globalObject.AbortSignal = 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, browserName) {\n const builtins = platformOriginals(globalObject).bound;\n const { clock: controller } = install(globalObject, { browserName });\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'; + } +}); + +// packages/playwright-core/src/protocol/serializers.ts +function parseSerializedValue(value2, handles) { + return innerParseSerializedValue(value2, handles, /* @__PURE__ */ new Map(), []); +} +function innerParseSerializedValue(value2, handles, refs, accessChain) { + if (value2.ref !== void 0) + return refs.get(value2.ref); + if (value2.n !== void 0) + return value2.n; + if (value2.s !== void 0) + return value2.s; + if (value2.b !== void 0) + return value2.b; + if (value2.v !== void 0) { + if (value2.v === "undefined") + return void 0; + if (value2.v === "null") + return null; + if (value2.v === "NaN") + return NaN; + if (value2.v === "Infinity") + return Infinity; + if (value2.v === "-Infinity") + return -Infinity; + if (value2.v === "-0") + return -0; + } + if (value2.d !== void 0) + return new Date(value2.d); + if (value2.u !== void 0) + return new URL(value2.u); + if (value2.bi !== void 0) + return BigInt(value2.bi); + if (value2.e !== void 0) { + const error = new Error(value2.e.m); + error.name = value2.e.n; + error.stack = value2.e.s; + return error; + } + if (value2.r !== void 0) + return new RegExp(value2.r.p, value2.r.f); + if (value2.ta !== void 0) { + const ctor = typedArrayKindToConstructor[value2.ta.k]; + return new ctor(value2.ta.b.buffer, value2.ta.b.byteOffset, value2.ta.b.length / ctor.BYTES_PER_ELEMENT); + } + if (value2.a !== void 0) { + const result2 = []; + refs.set(value2.id, result2); + for (let i = 0; i < value2.a.length; i++) + result2.push(innerParseSerializedValue(value2.a[i], handles, refs, [...accessChain, i])); + return result2; + } + if (value2.o !== void 0) { + const result2 = {}; + refs.set(value2.id, result2); + for (const { k, v } of value2.o) + result2[k] = innerParseSerializedValue(v, handles, refs, [...accessChain, k]); + return result2; + } + if (value2.h !== void 0) { + if (handles === void 0) + throw new Error("Unexpected handle"); + return handles[value2.h]; + } + throw new Error(`Attempting to deserialize unexpected value${accessChainToDisplayString(accessChain)}: ${value2}`); +} +function serializeValue(value2, handleSerializer) { + return innerSerializeValue(value2, handleSerializer, { lastId: 0, visited: /* @__PURE__ */ new Map() }, []); +} +function innerSerializeValue(value2, handleSerializer, visitorInfo, accessChain) { + const handle = handleSerializer(value2); + if ("fallThrough" in handle) + value2 = handle.fallThrough; + else + return handle; + if (typeof value2 === "symbol") + return { v: "undefined" }; + if (Object.is(value2, void 0)) + return { v: "undefined" }; + if (Object.is(value2, null)) + return { v: "null" }; + if (Object.is(value2, NaN)) + return { v: "NaN" }; + if (Object.is(value2, Infinity)) + return { v: "Infinity" }; + if (Object.is(value2, -Infinity)) + return { v: "-Infinity" }; + if (Object.is(value2, -0)) + return { v: "-0" }; + if (typeof value2 === "boolean") + return { b: value2 }; + if (typeof value2 === "number") + return { n: value2 }; + if (typeof value2 === "string") + return { s: value2 }; + if (typeof value2 === "bigint") + return { bi: value2.toString() }; + if (isError2(value2)) + return { e: { n: value2.name, m: value2.message, s: value2.stack || "" } }; + if (isDate(value2)) + return { d: value2.toJSON() }; + if (isURL(value2)) + return { u: value2.toJSON() }; + if (isRegExp4(value2)) + return { r: { p: value2.source, f: value2.flags } }; + const typedArrayKind = constructorToTypedArrayKind.get(value2.constructor); + if (typedArrayKind) + return { ta: { b: Buffer.from(value2.buffer, value2.byteOffset, value2.byteLength), k: typedArrayKind } }; + const id = visitorInfo.visited.get(value2); + if (id) + return { ref: id }; + if (Array.isArray(value2)) { + const a = []; + const id2 = ++visitorInfo.lastId; + visitorInfo.visited.set(value2, id2); + for (let i = 0; i < value2.length; ++i) + a.push(innerSerializeValue(value2[i], handleSerializer, visitorInfo, [...accessChain, i])); + return { a, id: id2 }; + } + if (typeof value2 === "object") { + const o = []; + const id2 = ++visitorInfo.lastId; + visitorInfo.visited.set(value2, id2); + for (const name of Object.keys(value2)) + o.push({ k: name, v: innerSerializeValue(value2[name], handleSerializer, visitorInfo, [...accessChain, name]) }); + return { o, id: id2 }; + } + throw new Error(`Attempting to serialize unexpected value${accessChainToDisplayString(accessChain)}: ${value2}`); +} +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 isRegExp4(obj) { + return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]"; +} +function isDate(obj) { + return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]"; +} +function isURL(obj) { + return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]"; +} +function isError2(obj) { + const proto = obj ? Object.getPrototypeOf(obj) : null; + return obj instanceof Error || proto?.name === "Error" || proto && isError2(proto); +} +var typedArrayKindToConstructor, constructorToTypedArrayKind; +var init_serializers = __esm({ + "packages/playwright-core/src/protocol/serializers.ts"() { + "use strict"; + typedArrayKindToConstructor = { + i8: Int8Array, + ui8: Uint8Array, + ui8c: Uint8ClampedArray, + i16: Int16Array, + ui16: Uint16Array, + i32: Int32Array, + ui32: Uint32Array, + f32: Float32Array, + f64: Float64Array, + bi64: BigInt64Array, + bui64: BigUint64Array + }; + constructorToTypedArrayKind = new Map(Object.entries(typedArrayKindToConstructor).map(([k, v]) => [v, k])); + } +}); + +// packages/playwright-core/src/server/errors.ts +function isTargetClosedError(error) { + return error instanceof TargetClosedError || error.name === "TargetClosedError"; +} +function serializeError(e) { + if (isError(e)) + return { error: { message: e.message, stack: e.stack, name: e.name } }; + return { value: serializeValue(e, (value2) => ({ fallThrough: value2 })) }; +} +function parseError(error) { + if (!error.error) { + if (error.value === void 0) + throw new Error("Serialized error must have either an error or a value"); + return parseSerializedValue(error.value, void 0); + } + const e = new Error(error.error.message); + e.stack = error.error.stack || ""; + e.name = error.error.name; + return e; +} +var CustomError, TimeoutError, TargetClosedError; +var init_errors = __esm({ + "packages/playwright-core/src/server/errors.ts"() { + "use strict"; + init_rtti(); + init_serializers(); + CustomError = class extends Error { + constructor(message) { + super(message); + this.name = this.constructor.name; + } + }; + TimeoutError = class extends CustomError { + }; + TargetClosedError = class extends CustomError { + constructor(cause, logs) { + super((cause || "Target page, context or browser has been closed") + (logs || "")); + } + }; + } +}); + +// packages/playwright-core/src/server/progress.ts +function isAbortError(error) { + return error instanceof TimeoutError || !!error[kAbortErrorSymbol]; +} +async function raceUncancellableOperationWithCleanup(progress2, run, cleanup) { + let aborted = false; + try { + return await progress2.race(run().then(async (t) => { + if (aborted) + await cleanup(t); + return t; + })); + } catch (error) { + aborted = true; + throw error; + } +} +var ProgressController, kAbortErrorSymbol, nullProgress; +var init_progress = __esm({ + "packages/playwright-core/src/server/progress.ts"() { + "use strict"; + init_manualPromise(); + init_assert(); + init_time(); + init_debugLogger(); + init_errors(); + ProgressController = class _ProgressController { + constructor(metadata, onCallLog) { + this._forceAbortPromise = new ManualPromise(); + this._donePromise = new ManualPromise(); + this._state = "before"; + this.metadata = metadata || { id: "", startTime: 0, endTime: 0, type: "Internal", method: "", params: {}, log: [], internal: true }; + this._onCallLog = onCallLog; + this._forceAbortPromise.catch((e) => null); + this._controller = new AbortController(); + } + static createForSdkObject(sdkObject, callMetadata) { + const logName = sdkObject.logName || "api"; + return new _ProgressController(callMetadata, (message) => { + if (logName === "api" && sdkObject.attribution.playwright?.options.isInternalPlaywright) + return; + debugLogger.log(logName, message); + sdkObject.instrumentation.onCallLog(sdkObject, callMetadata, logName, message); + }); + } + async abort(error) { + if (this._state === "running") { + error[kAbortErrorSymbol] = true; + this._state = { error }; + this._forceAbortPromise.reject(error); + this._controller.abort(error); + } + await this._donePromise; + } + async run(task, timeout) { + const deadline = timeout ? monotonicTime() + timeout : 0; + assert(this._state === "before"); + this._state = "running"; + let timer; + let outerProgress; + let allowConcurrent = false; + const progress2 = { + timeout: timeout ?? 0, + deadline, + disableTimeout: () => { + clearTimeout(timer); + }, + log: (message) => { + if (this._state === "running") + this.metadata.log.push(message); + this._onCallLog?.(message); + }, + metadata: this.metadata, + setAllowConcurrentOrNestedRaces: (allow) => { + allowConcurrent = allow; + }, + race: (promise) => { + if (process.env.PW_DETECT_NESTED_PROGRESS) { + const innerProgress = new Error().stack; + if (outerProgress && !allowConcurrent && outerProgress !== innerProgress) { + console.error("Cannot call race() inside another race()"); + console.error("<<<<>>>>:", outerProgress); + console.error("<<<<>>>>:", innerProgress); + } + outerProgress = innerProgress; + } + const promises = Array.isArray(promise) ? promise : [promise]; + if (!promises.length) + return Promise.resolve(); + return Promise.race([...promises, this._forceAbortPromise]).finally(() => outerProgress = void 0); + }, + wait: async (timeout2) => { + let timer2; + const promise = new Promise((f) => timer2 = setTimeout(f, timeout2)); + return progress2.race(promise).finally(() => clearTimeout(timer2)); + }, + signal: this._controller.signal + }; + if (deadline) { + const timeoutError = new TimeoutError(`Timeout ${timeout}ms exceeded.`); + timer = setTimeout(() => { + if (this.metadata.pauseStartTime && !this.metadata.pauseEndTime) + return; + if (this._state === "running") { + this._state = { error: timeoutError }; + this._forceAbortPromise.reject(timeoutError); + this._controller.abort(timeoutError); + } + }, deadline - monotonicTime()); + } + try { + const result2 = await task(progress2); + this._state = "finished"; + return result2; + } catch (error) { + this._state = { error }; + throw error; + } finally { + clearTimeout(timer); + this._donePromise.resolve(); + } + } + }; + kAbortErrorSymbol = Symbol("kAbortError"); + nullProgress = { + timeout: 0, + deadline: 0, + disableTimeout() { + }, + log() { + }, + race(promise) { + const promises = Array.isArray(promise) ? promise : [promise]; + return Promise.race(promises); + }, + wait: async (timeout) => await new Promise((f) => setTimeout(f, timeout)), + signal: new AbortController().signal, + metadata: { + id: "", + startTime: 0, + endTime: 0, + type: "", + method: "", + params: {}, + log: [], + internal: true + }, + setAllowConcurrentOrNestedRaces() { + } + }; + } +}); + +// packages/playwright-core/src/server/clock.ts +function parseTicks(value2) { + if (typeof value2 === "number") + return value2; + if (!value2) + return 0; + const str = value2; + const strings = str.split(":"); + const l = strings.length; + let i = l; + let ms = 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}`); + ms += parsed * Math.pow(60, l - i - 1); + } + return ms * 1e3; +} +function parseTime(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(); +} +var Clock; +var init_clock = __esm({ + "packages/playwright-core/src/server/clock.ts"() { + "use strict"; + init_clockSource(); + init_progress(); + Clock = class { + constructor(browserContext) { + this._initScripts = []; + this._browserContext = browserContext; + } + async uninstall(progress2) { + await progress2.race(Promise.all(this._initScripts.map((script) => script.dispose()))); + this._initScripts = []; + } + async fastForward(ticks) { + await this._installIfNeeded(); + const ticksMillis = parseTicks(ticks); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `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(time) : Date.now(); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `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(ticks); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('pauseAt', ${Date.now()}, ${timeMillis})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.pauseAt(${timeMillis})`); + } + resumeNoReply() { + if (!this._initScripts.length) + return; + const doResume = async () => { + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('resume', ${Date.now()})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.resume()`); + }; + doResume().catch(() => { + }); + } + async resume(progress2) { + await progress2.race(this._installIfNeeded()); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('resume', ${Date.now()})`)); + await progress2.race(this._evaluateInFrames(`globalThis.__pwClock.controller.resume()`)); + } + async setFixedTime(time) { + await this._installIfNeeded(); + const timeMillis = parseTime(time); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `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(time); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `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(ticks); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `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} + if (!globalThis.__pwClock) + globalThis.__pwClock = (module.exports.inject())(globalThis, ${JSON.stringify(this._browserContext._browser.options.name)}); + })();`; + const initScript = await this._browserContext.addInitScript(nullProgress, script); + await this._evaluateInFrames(script); + this._initScripts.push(initScript); + } + async _evaluateInFrames(script) { + await this._browserContext.safeNonStallingEvaluateInAllFrames(script, "main", { throwOnJSErrors: true }); + } + }; + } +}); + +// packages/playwright-core/src/server/instrumentation.ts +function createRootSdkObject() { + const fakeParent = { attribution: {}, instrumentation: createInstrumentation() }; + const root = new SdkObject(fakeParent); + root.guid = ""; + return root; +} +function createInstrumentation() { + const listeners = /* @__PURE__ */ new Map(); + return new Proxy({}, { + get: (obj, prop) => { + if (typeof prop !== "string") + return obj[prop]; + if (prop === "addListener") + return (listener, context2) => listeners.set(listener, context2); + if (prop === "removeListener") + return (listener) => listeners.delete(listener); + if (!prop.startsWith("on")) + return obj[prop]; + return async (sdkObject, ...params2) => { + for (const [listener, context2] of listeners) { + if (!context2 || sdkObject.attribution.context === context2) + await listener[prop]?.(sdkObject, ...params2); + } + }; + } + }); +} +var import_events3, SdkObject; +var init_instrumentation = __esm({ + "packages/playwright-core/src/server/instrumentation.ts"() { + "use strict"; + import_events3 = require("events"); + init_crypto(); + init_debugLogger(); + SdkObject = class extends import_events3.EventEmitter { + constructor(parent, guidPrefix, guid) { + super(); + this.guid = guid || `${guidPrefix || ""}@${createGuid()}`; + this.setMaxListeners(0); + this.attribution = { ...parent.attribution }; + this.instrumentation = parent.instrumentation; + } + apiLog(message) { + if (!this.attribution.playwright.options.isInternalPlaywright) + debugLogger.log("api", message); + } + closeReason() { + return this.attribution.worker?._closeReason || this.attribution.page?._closeReason || this.attribution.context?._closeReason || this.attribution.browser?._closeReason; + } + }; + } +}); + +// packages/playwright-core/src/server/debugger.ts +function matchesLocation(metadata, location2) { + return !!metadata.location?.file.includes(location2.file) && (location2.line === void 0 || metadata.location.line === location2.line) && (location2.column === void 0 || metadata.location.column === location2.column); +} +var symbol, Debugger; +var init_debugger = __esm({ + "packages/playwright-core/src/server/debugger.ts"() { + "use strict"; + init_protocolMetainfo(); + init_time(); + init_instrumentation(); + init_browserContext(); + symbol = Symbol("Debugger"); + Debugger = class _Debugger extends SdkObject { + constructor(context2) { + super(context2, "debugger"); + this._pauseAt = {}; + this._enabled = false; + this._pauseBeforeWaitingActions = false; + this._muted = false; + this._context = context2; + this._context[symbol] = this; + context2.instrumentation.addListener(this, context2); + this._context.once(BrowserContext.Events.Close, () => { + this._context.instrumentation.removeListener(this); + }); + } + static { + this.Events = { + PausedStateChanged: "pausedstatechanged" + }; + } + requestPause(progress2) { + if (this.isPaused()) + throw new Error("Debugger is already paused"); + this.setPauseBeforeWaitingActions(); + this.setPauseAt({ next: true }); + } + doResume(progress2) { + if (!this.isPaused()) + throw new Error("Debugger is not paused"); + this.resume(); + } + next(progress2) { + if (!this.isPaused()) + throw new Error("Debugger is not paused"); + this.setPauseBeforeWaitingActions(); + this.setPauseAt({ next: true }); + this.resume(); + } + runTo(progress2, location2) { + if (!this.isPaused()) + throw new Error("Debugger is not paused"); + this.setPauseBeforeWaitingActions(); + this.setPauseAt({ location: location2 }); + this.resume(); + } + async setMuted(muted) { + this._muted = muted; + } + async onBeforeCall(sdkObject, metadata) { + if (this._muted || metadata.internal) + return; + const metainfo = getMetainfo(metadata); + const pauseOnPauseCall = this._enabled && metadata.type === "BrowserContext" && metadata.method === "pause"; + const pauseBeforeAction = !!this._pauseAt.next && !!metainfo?.pause && (this._pauseBeforeWaitingActions || !metainfo?.isAutoWaiting); + const pauseOnLocation = !!this._pauseAt.location && matchesLocation(metadata, this._pauseAt.location); + if (pauseOnPauseCall || pauseBeforeAction || pauseOnLocation) + await this._pause(sdkObject, metadata); + } + async onBeforeInputAction(sdkObject, metadata) { + if (this._muted || metadata.internal) + return; + const metainfo = getMetainfo(metadata); + const pauseBeforeInput = !!this._pauseAt.next && !!metainfo?.pause && !!metainfo?.isAutoWaiting && !this._pauseBeforeWaitingActions; + if (pauseBeforeInput) + await this._pause(sdkObject, metadata); + } + async _pause(sdkObject, metadata) { + if (this._muted || metadata.internal) + return; + if (this._pausedCall) + return; + this._pauseAt = {}; + metadata.pauseStartTime = monotonicTime(); + const result2 = new Promise((resolve) => { + this._pausedCall = { metadata, sdkObject, resolve }; + }); + this.emit(_Debugger.Events.PausedStateChanged); + return result2; + } + resume() { + if (!this._pausedCall) + return; + this._pausedCall.metadata.pauseEndTime = monotonicTime(); + this._pausedCall.resolve(); + this._pausedCall = void 0; + this.emit(_Debugger.Events.PausedStateChanged); + } + setPauseBeforeWaitingActions() { + this._pauseBeforeWaitingActions = true; + } + setPauseAt(at = {}) { + this._enabled = true; + this._pauseAt = at; + } + isPaused(metadata) { + if (metadata) + return this._pausedCall?.metadata === metadata; + return !!this._pausedCall; + } + pausedDetails() { + return this._pausedCall; + } + }; + } +}); + +// packages/playwright-core/src/server/dialog.ts +var Dialog, DialogManager; +var init_dialog = __esm({ + "packages/playwright-core/src/server/dialog.ts"() { + "use strict"; + init_assert(); + init_instrumentation(); + Dialog = class extends SdkObject { + constructor(page, type3, message, onHandle, defaultValue) { + super(page, "dialog"); + this._handled = false; + this._page = page; + this._type = type3; + this._message = message; + this._onHandle = onHandle; + this._defaultValue = defaultValue || ""; + } + async accept(progress2, promptText) { + await progress2.race(this._accept(promptText)); + } + async dismiss(progress2) { + await progress2.race(this._dismiss()); + } + 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(); + } + }; + DialogManager = class { + 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(); + })); + } + }; + } +}); + +// packages/playwright-core/src/server/network.ts +function filterCookies(cookies, urls) { + const parsedURLs = urls.map((s) => new URL(s)); + return cookies.filter((c) => { + if (!parsedURLs.length) + return true; + for (const parsedURL of parsedURLs) { + let domain = c.domain; + if (!domain.startsWith(".")) + domain = "." + domain; + if (!("." + parsedURL.hostname).endsWith(domain)) + continue; + if (!parsedURL.pathname.startsWith(c.path)) + continue; + if (parsedURL.protocol !== "https:" && !isLocalHostname(parsedURL.hostname) && c.secure) + continue; + return true; + } + return false; + }); +} +function isLocalHostname(hostname) { + return hostname === "localhost" || hostname.endsWith(".localhost"); +} +function isForbiddenHeader(name, value2) { + const lowerName = name.toLowerCase(); + if (FORBIDDEN_HEADER_NAMES.has(lowerName)) + return true; + if (lowerName.startsWith("proxy-")) + return true; + if (lowerName.startsWith("sec-")) + return true; + if (lowerName === "x-http-method" || lowerName === "x-http-method-override" || lowerName === "x-method-override") { + if (value2 && FORBIDDEN_METHODS.has(value2.toUpperCase())) + return true; + } + return false; +} +function applyHeadersOverrides(original, overrides) { + const forbiddenHeaders = original.filter((header) => isForbiddenHeader(header.name, header.value)); + const allowedHeaders = overrides.filter((header) => !isForbiddenHeader(header.name, header.value)); + return mergeHeaders([allowedHeaders, forbiddenHeaders]); +} +function rewriteCookies(cookies) { + return cookies.map((c) => { + assert(c.url || c.domain && c.path, "Cookie should have a url or a domain/path pair"); + assert(!(c.url && c.domain), "Cookie should have either url or domain"); + assert(!(c.url && c.path), "Cookie should have either url or path"); + assert(!(c.expires && c.expires < 0 && c.expires !== -1), "Cookie should have a valid expires, only -1 or a positive number for the unix timestamp in seconds is allowed"); + assert(!(c.expires && c.expires > 0 && c.expires > kMaxCookieExpiresDateInSeconds), "Cookie should have a valid expires, only -1 or a positive number for the unix timestamp in seconds is allowed"); + const copy = { ...c }; + if (copy.url) { + assert(copy.url !== "about:blank", `Blank page can not have cookie "${c.name}"`); + assert(!copy.url.startsWith("data:"), `Data URL page can not have cookie "${c.name}"`); + const url2 = new URL(copy.url); + copy.domain = url2.hostname; + copy.path = url2.pathname.substring(0, url2.pathname.lastIndexOf("/") + 1); + copy.secure = url2.protocol === "https:"; + } + return copy; + }); +} +function parseURL2(url2) { + try { + return new URL(url2); + } catch (e) { + return null; + } +} +function stripFragmentFromUrl(url2) { + if (!url2.includes("#")) + return url2; + return url2.substring(0, url2.indexOf("#")); +} +function statusText(status) { + return STATUS_TEXTS[String(status)] || "Unknown"; +} +function singleHeader(name, value2) { + return [{ name, value: value2 }]; +} +function mergeHeaders(headers) { + const lowerCaseToValue = /* @__PURE__ */ new Map(); + const lowerCaseToOriginalCase = /* @__PURE__ */ new Map(); + for (const h of headers) { + if (!h) + continue; + for (const { name, value: value2 } of h) { + const lower = name.toLowerCase(); + lowerCaseToOriginalCase.set(lower, name); + lowerCaseToValue.set(lower, value2); + } + } + const result2 = []; + for (const [lower, value2] of lowerCaseToValue) + result2.push({ name: lowerCaseToOriginalCase.get(lower), value: value2 }); + return result2; +} +var FORBIDDEN_HEADER_NAMES, FORBIDDEN_METHODS, kMaxCookieExpiresDateInSeconds, Request, Route, Response2, WebSocket, STATUS_TEXTS; +var init_network2 = __esm({ + "packages/playwright-core/src/server/network.ts"() { + "use strict"; + init_manualPromise(); + init_assert(); + init_browserContext(); + init_fetch(); + init_instrumentation(); + FORBIDDEN_HEADER_NAMES = /* @__PURE__ */ new Set([ + "accept-charset", + "accept-encoding", + "access-control-request-headers", + "access-control-request-method", + "connection", + "content-length", + "cookie", + "date", + "dnt", + "expect", + "host", + "keep-alive", + "origin", + "referer", + "set-cookie", + "te", + "trailer", + "transfer-encoding", + "upgrade", + "via" + ]); + FORBIDDEN_METHODS = /* @__PURE__ */ new Set(["CONNECT", "TRACE", "TRACK"]); + kMaxCookieExpiresDateInSeconds = 253402300799; + Request = class _Request extends SdkObject { + constructor(context2, frame, serviceWorker, redirectedFrom, documentId, url2, resourceType, method, postData, headers) { + super(frame || context2, "request"); + this._response = null; + this._redirectedTo = null; + this._failureText = null; + this._frame = null; + this._serviceWorker = null; + this._rawRequestHeadersPromise = new ManualPromise(); + this._waitForResponsePromise = new ManualPromise(); + this._responseEndTiming = -1; + assert(!url2.startsWith("data:"), "Data urls should not fire requests"); + this._context = context2; + this._frame = frame; + this._serviceWorker = serviceWorker; + this._redirectedFrom = redirectedFrom; + if (redirectedFrom) + redirectedFrom._redirectedTo = this; + this._documentId = documentId; + this._url = stripFragmentFromUrl(url2); + this._resourceType = resourceType; + this._method = method; + this._postData = postData; + this._headers = headers; + this._isFavicon = url2.endsWith("/favicon.ico") || !!redirectedFrom?._isFavicon; + } + static { + this.Events = { + Response: "response" + }; + } + async rawRequestHeaders(progress2) { + return await progress2.race(this._rawRequestHeaders()); + } + async response(progress2) { + return await progress2.race(this._waitForResponse()); + } + _setFailureText(failureText) { + this._failureText = failureText; + this._waitForResponsePromise.resolve(null); + } + _applyOverrides(overrides) { + this._overrides = { ...this._overrides, ...overrides }; + return this._overrides; + } + overrides() { + return this._overrides; + } + url() { + return this._overrides?.url || this._url; + } + resourceType() { + return this._resourceType; + } + method() { + return this._overrides?.method || this._method; + } + postDataBuffer() { + return this._overrides?.postData || this._postData; + } + headers() { + return this._overrides?.headers || this._headers; + } + headerValue(name) { + const lowerCaseName = name.toLowerCase(); + return this.headers().find((h) => h.name.toLowerCase() === lowerCaseName)?.value; + } + // "null" means no raw headers available - we'll use provisional headers as raw headers. + setRawRequestHeaders(headers) { + if (!this._rawRequestHeadersPromise.isDone()) + this._rawRequestHeadersPromise.resolve(headers || this._headers); + } + async _rawRequestHeaders() { + return this._overrides?.headers || this._rawRequestHeadersPromise; + } + _waitForResponse() { + return this._waitForResponsePromise; + } + _existingResponse() { + return this._response; + } + _setResponse(response2) { + this._response = response2; + this._waitForResponsePromise.resolve(response2); + this.emit(_Request.Events.Response, response2); + } + _finalRequest() { + return this._redirectedTo ? this._redirectedTo._finalRequest() : this; + } + frame() { + return this._frame; + } + serviceWorker() { + return this._serviceWorker; + } + isNavigationRequest() { + return !!this._documentId; + } + redirectedFrom() { + return this._redirectedFrom; + } + failure() { + if (this._failureText === null) + return null; + return { + errorText: this._failureText + }; + } + // TODO(bidi): remove once post body is available. + _setBodySize(size) { + this._bodySize = size; + } + bodySize() { + return this._bodySize || this.postDataBuffer()?.length || 0; + } + async _requestHeadersSize() { + let headersSize = 4; + headersSize += this.method().length; + headersSize += new URL(this.url()).pathname.length; + headersSize += 8; + const headers = await this._rawRequestHeaders(); + for (const header of headers) + headersSize += header.name.length + header.value.length + 4; + return headersSize; + } + }; + Route = class extends SdkObject { + constructor(request2, delegate) { + super(request2._frame || request2._context, "route"); + this._handled = false; + this._futureHandlers = []; + this._request = request2; + this._delegate = delegate; + this._request._context.addRouteInFlight(this); + } + handle(handlers) { + this._futureHandlers = [...handlers]; + this.continue({ isFallback: true }).catch(() => { + }); + } + async removeHandler(handler) { + this._futureHandlers = this._futureHandlers.filter((h) => h !== handler); + if (handler === this._currentHandler) { + await this.continue({ isFallback: true }).catch(() => { + }); + return; + } + } + request() { + return this._request; + } + async abort(errorCode = "failed") { + this._startHandling(); + this._request._context.emit(BrowserContext.Events.RequestAborted, this._request); + await this._delegate.abort(errorCode); + this._endHandling(); + } + redirectNavigationRequest(url2) { + this._startHandling(); + assert(this._request.isNavigationRequest()); + this._request.frame().redirectNavigation(url2, this._request._documentId, this._request.headerValue("referer")); + this._endHandling(); + } + async fulfill(overrides) { + this._startHandling(); + let body = overrides.body; + let isBase64 = overrides.isBase64 || false; + if (body === void 0) { + if (overrides.fetchResponseUid) { + const buffer = this._request._context.fetchRequest.fetchResponses.get(overrides.fetchResponseUid) || APIRequestContext.findResponseBody(overrides.fetchResponseUid); + assert(buffer, "Fetch response has been disposed"); + body = buffer.toString("base64"); + isBase64 = true; + } else { + body = ""; + isBase64 = false; + } + } else if (!overrides.status || overrides.status < 200 || overrides.status >= 400) { + this._request._responseBodyOverride = { body, isBase64 }; + } + const headers = [...overrides.headers || []]; + this._maybeAddCorsHeaders(headers); + this._request._context.emit(BrowserContext.Events.RequestFulfilled, this._request); + await this._delegate.fulfill({ + status: overrides.status || 200, + headers, + body, + isBase64 + }); + this._endHandling(); + } + // See https://github.com/microsoft/playwright/issues/12929 + _maybeAddCorsHeaders(headers) { + const origin = this._request.headerValue("origin"); + if (!origin) + return; + const requestUrl = new URL(this._request.url()); + if (!requestUrl.protocol.startsWith("http")) + return; + if (requestUrl.origin === origin.trim()) + return; + const corsHeader = headers.find(({ name }) => name === "access-control-allow-origin"); + if (corsHeader) + return; + headers.push({ name: "access-control-allow-origin", value: origin }); + headers.push({ name: "access-control-allow-credentials", value: "true" }); + headers.push({ name: "vary", value: "Origin" }); + } + async continue(overrides) { + if (overrides.url) { + const newUrl = new URL(overrides.url); + const oldUrl = new URL(this._request.url()); + if (oldUrl.protocol !== newUrl.protocol) + throw new Error("New URL must have same protocol as overridden URL"); + } + if (overrides.headers) { + overrides.headers = applyHeadersOverrides(this._request._headers, overrides.headers); + } + overrides = this._request._applyOverrides(overrides); + const nextHandler = this._futureHandlers.shift(); + if (nextHandler) { + this._currentHandler = nextHandler; + nextHandler(this, this._request); + return; + } + if (!overrides.isFallback) + this._request._context.emit(BrowserContext.Events.RequestContinued, this._request); + this._startHandling(); + await this._delegate.continue(overrides); + this._endHandling(); + } + _startHandling() { + assert(!this._handled, "Route is already handled!"); + this._handled = true; + this._currentHandler = void 0; + } + _endHandling() { + this._futureHandlers = []; + this._currentHandler = void 0; + this._request._context.removeRouteInFlight(this); + } + }; + Response2 = class extends SdkObject { + constructor(request2, status, statusText2, headers, timing, getResponseBodyCallback, fromServiceWorker) { + super(request2.frame() || request2._context, "response"); + this._contentPromise = null; + this._finishedPromise = new ManualPromise(); + this._headersMap = /* @__PURE__ */ new Map(); + this._serverAddrPromise = new ManualPromise(); + this._securityDetailsPromise = new ManualPromise(); + this._rawResponseHeadersPromise = new ManualPromise(); + this._httpVersionPromise = new ManualPromise(); + this._encodedBodySizePromise = new ManualPromise(); + this._transferSizePromise = new ManualPromise(); + this._responseHeadersSizePromise = new ManualPromise(); + this._request = request2; + this._timing = timing; + this._status = status; + this._statusText = statusText2; + this._url = request2.url(); + this._headers = headers; + for (const { name, value: value2 } of this._headers) + this._headersMap.set(name.toLowerCase(), value2); + this._getResponseBodyCallback = getResponseBodyCallback; + this._request._setResponse(this); + this._fromServiceWorker = fromServiceWorker; + } + async body(progress2) { + return await progress2.race(this.internalBody()); + } + async securityDetails(progress2) { + return await progress2.race(this.internalSecurityDetails()); + } + async serverAddr(progress2) { + return await progress2.race(this._serverAddrPromise) || null; + } + async rawResponseHeaders(progress2) { + return await progress2.race(this._rawResponseHeadersPromise); + } + async httpVersion(progress2) { + return await progress2.race(this._httpVersion()); + } + async sizes(progress2) { + return await progress2.race(this._sizes()); + } + _serverAddrFinished(addr) { + this._serverAddrPromise.resolve(addr); + } + _securityDetailsFinished(securityDetails) { + this._securityDetailsPromise.resolve(securityDetails); + } + _requestFinished(responseEndTiming) { + this._request._responseEndTiming = Math.max(responseEndTiming, this._timing.responseStart); + if (this._timing.requestStart === -1) + this._timing.requestStart = this._request._responseEndTiming; + this._finishedPromise.resolve(); + } + _setHttpVersion(httpVersion) { + this._httpVersionPromise.resolve(httpVersion); + } + url() { + return this._url; + } + status() { + return this._status; + } + statusText() { + return this._statusText; + } + headers() { + return this._headers; + } + headerValue(name) { + return this._headersMap.get(name); + } + // "null" means no raw headers available - we'll use provisional headers as raw headers. + setRawResponseHeaders(headers) { + if (!this._rawResponseHeadersPromise.isDone()) + this._rawResponseHeadersPromise.resolve(headers || this._headers); + } + setTransferSize(size) { + this._transferSizePromise.resolve(size); + } + setEncodedBodySize(size) { + this._encodedBodySizePromise.resolve(size); + } + setResponseHeadersSize(size) { + this._responseHeadersSizePromise.resolve(size); + } + timing() { + return this._timing; + } + async internalSecurityDetails() { + return await this._securityDetailsPromise || null; + } + internalBody() { + if (!this._contentPromise) { + this._contentPromise = this._finishedPromise.then(async () => { + if (this._status >= 300 && this._status <= 399) + throw new Error("Response body is unavailable for redirect responses"); + if (this._request._responseBodyOverride) { + const { body, isBase64 } = this._request._responseBodyOverride; + return Buffer.from(body, isBase64 ? "base64" : "utf-8"); + } + return this._getResponseBodyCallback(); + }); + } + return this._contentPromise; + } + request() { + return this._request; + } + finished() { + return this._finishedPromise; + } + frame() { + return this._request.frame(); + } + async _httpVersion() { + const httpVersion = await this._httpVersionPromise || null; + if (!httpVersion) + return "HTTP/1.1"; + if (httpVersion === "http/1.1") + return "HTTP/1.1"; + if (httpVersion === "h2") + return "HTTP/2.0"; + return httpVersion; + } + fromServiceWorker() { + return this._fromServiceWorker; + } + async responseHeadersSize() { + const availableSize = await this._responseHeadersSizePromise; + if (availableSize !== null) + return availableSize; + let headersSize = 4; + headersSize += 8; + headersSize += 3; + headersSize += this.statusText().length; + const headers = await this._rawResponseHeadersPromise; + for (const header of headers) + headersSize += header.name.length + header.value.length + 4; + headersSize += 2; + return headersSize; + } + async _sizes() { + const requestHeadersSize = await this._request._requestHeadersSize(); + const responseHeadersSize = await this.responseHeadersSize(); + let encodedBodySize = await this._encodedBodySizePromise; + if (encodedBodySize === null) { + const headers = await this._rawResponseHeadersPromise; + const contentLength = headers.find((h) => h.name.toLowerCase() === "content-length")?.value; + encodedBodySize = contentLength ? +contentLength : 0; + } + let transferSize = await this._transferSizePromise; + if (transferSize === null) { + transferSize = responseHeadersSize + encodedBodySize; + } + return { + requestBodySize: this._request.bodySize(), + requestHeadersSize, + responseBodySize: encodedBodySize, + responseHeadersSize, + transferSize + }; + } + }; + WebSocket = class _WebSocket extends SdkObject { + constructor(parent, url2) { + super(parent, "ws"); + this._notified = false; + this._url = url2; + } + static { + this.Events = { + Close: "close", + SocketError: "socketerror", + FrameReceived: "framereceived", + FrameSent: "framesent" + }; + } + markAsNotified() { + if (this._notified) + return false; + this._notified = true; + return true; + } + url() { + return this._url; + } + frameSent(opcode, data) { + this.emit(_WebSocket.Events.FrameSent, { opcode, data }); + } + frameReceived(opcode, data) { + this.emit(_WebSocket.Events.FrameReceived, { opcode, data }); + } + error(errorMessage) { + this.emit(_WebSocket.Events.SocketError, errorMessage); + } + closed() { + this.emit(_WebSocket.Events.Close); + } + }; + STATUS_TEXTS = { + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "103": "Early Hints", + "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", + "306": "Switch 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": "Too Early", + "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", + "510": "Not Extended", + "511": "Network Authentication Required" + }; + } +}); + +// packages/playwright-core/src/server/cookieStore.ts +function parseRawCookie(header) { + const pairs = header.split(";").filter((s) => s.trim().length > 0).map((p) => { + let key = ""; + let value3 = ""; + const separatorPos = p.indexOf("="); + if (separatorPos === -1) { + key = p.trim(); + } else { + key = p.slice(0, separatorPos).trim(); + value3 = p.slice(separatorPos + 1).trim(); + } + return [key, value3]; + }); + if (!pairs.length) + return null; + const [name, value2] = pairs[0]; + const cookie = { + name, + value: value2 + }; + for (let i = 1; i < pairs.length; i++) { + const [name2, value3] = pairs[i]; + switch (name2.toLowerCase()) { + case "expires": + const expiresMs = +new Date(value3); + if (isFinite(expiresMs)) { + if (expiresMs <= 0) + cookie.expires = 0; + else + cookie.expires = Math.min(expiresMs / 1e3, kMaxCookieExpiresDateInSeconds); + } + break; + case "max-age": + const maxAgeSec = parseInt(value3, 10); + if (isFinite(maxAgeSec)) { + if (maxAgeSec <= 0) + cookie.expires = 0; + else + cookie.expires = Math.min(Date.now() / 1e3 + maxAgeSec, kMaxCookieExpiresDateInSeconds); + } + break; + case "domain": + cookie.domain = value3.toLocaleLowerCase() || ""; + if (cookie.domain && !cookie.domain.startsWith(".") && cookie.domain.includes(".")) + cookie.domain = "." + cookie.domain; + break; + case "path": + cookie.path = value3 || ""; + break; + case "secure": + cookie.secure = true; + break; + case "httponly": + cookie.httpOnly = true; + break; + case "samesite": + switch (value3.toLowerCase()) { + case "none": + cookie.sameSite = "None"; + break; + case "lax": + cookie.sameSite = "Lax"; + break; + case "strict": + cookie.sameSite = "Strict"; + break; + } + break; + } + } + return cookie; +} +function domainMatches(value2, domain) { + if (value2 === domain) + return true; + if (!domain.startsWith(".")) + return false; + value2 = "." + value2; + return value2.endsWith(domain); +} +function pathMatches(value2, path59) { + if (value2 === path59) + return true; + if (!value2.endsWith("/")) + value2 = value2 + "/"; + if (!path59.endsWith("/")) + path59 = path59 + "/"; + return value2.startsWith(path59); +} +var Cookie, CookieStore; +var init_cookieStore = __esm({ + "packages/playwright-core/src/server/cookieStore.ts"() { + "use strict"; + init_network2(); + Cookie = class { + constructor(data) { + this._raw = data; + } + _name() { + return this._raw.name; + } + // https://datatracker.ietf.org/doc/html/rfc6265#section-5.4 + matches(url2) { + if (this._raw.secure && (url2.protocol !== "https:" && !isLocalHostname(url2.hostname))) + return false; + if (!domainMatches(url2.hostname, this._raw.domain)) + return false; + if (!pathMatches(url2.pathname, this._raw.path)) + return false; + return true; + } + _equals(other) { + return this._raw.name === other._raw.name && this._raw.domain === other._raw.domain && this._raw.path === other._raw.path; + } + _networkCookie() { + return this._raw; + } + _updateExpiresFrom(other) { + this._raw.expires = other._raw.expires; + } + _expired() { + if (this._raw.expires === -1) + return false; + return this._raw.expires * 1e3 < Date.now(); + } + }; + CookieStore = class _CookieStore { + constructor() { + this._nameToCookies = /* @__PURE__ */ new Map(); + } + addCookies(cookies) { + for (const cookie of cookies) + this._addCookie(new Cookie(cookie)); + } + cookies(url2) { + const result2 = []; + for (const cookie of this._cookiesIterator()) { + if (cookie.matches(url2)) + result2.push(cookie._networkCookie()); + } + return result2; + } + allCookies() { + const result2 = []; + for (const cookie of this._cookiesIterator()) + result2.push(cookie._networkCookie()); + return result2; + } + _addCookie(cookie) { + let set = this._nameToCookies.get(cookie._name()); + if (!set) { + set = /* @__PURE__ */ new Set(); + this._nameToCookies.set(cookie._name(), set); + } + for (const other of set) { + if (other._equals(cookie)) + set.delete(other); + } + set.add(cookie); + _CookieStore.pruneExpired(set); + } + *_cookiesIterator() { + for (const [name, cookies] of this._nameToCookies) { + _CookieStore.pruneExpired(cookies); + for (const cookie of cookies) + yield cookie; + if (cookies.size === 0) + this._nameToCookies.delete(name); + } + } + static pruneExpired(cookies) { + for (const cookie of cookies) { + if (cookie._expired()) + cookies.delete(cookie); + } + } + }; + } +}); + +// packages/playwright-core/src/server/formData.ts +function generateUniqueBoundaryString() { + const charCodes = []; + for (let i = 0; i < 16; i++) + charCodes.push(alphaNumericEncodingMap[Math.floor(Math.random() * alphaNumericEncodingMap.length)]); + return "----WebKitFormBoundary" + String.fromCharCode(...charCodes); +} +var mime2, MultipartFormData, alphaNumericEncodingMap; +var init_formData = __esm({ + "packages/playwright-core/src/server/formData.ts"() { + "use strict"; + mime2 = require("./utilsBundle").mime; + MultipartFormData = class { + constructor() { + this._chunks = []; + this._boundary = generateUniqueBoundaryString(); + } + contentTypeHeader() { + return `multipart/form-data; boundary=${this._boundary}`; + } + addField(name, value2) { + this._beginMultiPartHeader(name); + this._finishMultiPartHeader(); + this._chunks.push(Buffer.from(value2)); + this._finishMultiPartField(); + } + addFileField(name, value2) { + this._beginMultiPartHeader(name); + this._chunks.push(Buffer.from(`; filename="${value2.name}"`)); + this._chunks.push(Buffer.from(`\r +content-type: ${value2.mimeType || mime2.getType(value2.name) || "application/octet-stream"}`)); + this._finishMultiPartHeader(); + this._chunks.push(value2.buffer); + this._finishMultiPartField(); + } + finish() { + this._addBoundary(true); + return Buffer.concat(this._chunks); + } + _beginMultiPartHeader(name) { + this._addBoundary(); + this._chunks.push(Buffer.from(`content-disposition: form-data; name="${name}"`)); + } + _finishMultiPartHeader() { + this._chunks.push(Buffer.from(`\r +\r +`)); + } + _finishMultiPartField() { + this._chunks.push(Buffer.from(`\r +`)); + } + _addBoundary(isLastBoundary) { + this._chunks.push(Buffer.from("--" + this._boundary)); + if (isLastBoundary) + this._chunks.push(Buffer.from("--")); + this._chunks.push(Buffer.from("\r\n")); + } + }; + alphaNumericEncodingMap = [ + 65, + 66, + 67, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 97, + 98, + 99, + 100, + 101, + 102, + 103, + 104, + 105, + 106, + 107, + 108, + 109, + 110, + 111, + 112, + 113, + 114, + 115, + 116, + 117, + 118, + 119, + 120, + 121, + 122, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 65, + 66 + ]; + } +}); + +// packages/playwright-core/src/server/socksClientCertificatesInterceptor.ts +function loadDummyServerCertsIfNeeded() { + if (dummyServerTlsOptions) + return; + const { cert, key } = generateSelfSignedCertificate(); + dummyServerTlsOptions = { key, cert }; +} +function normalizeOrigin(origin) { + try { + return new URL(origin).origin; + } catch (error) { + 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?.filter( + (c) => normalizeOrigin(c.origin) === origin + ); + return convertClientCertificatesToTLSOptions(matchingCerts); +} +function rewriteToLocalhostIfNeeded(host) { + return host === "local.playwright" ? "localhost" : host; +} +function rewriteOpenSSLErrorIfNeeded(error) { + if (error.message !== "unsupported" && error.code !== "ERR_CRYPTO_UNSUPPORTED_OPERATION") + return error; + return rewriteErrorMessage(error, [ + "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")); +} +function parseALPNFromClientHello(buffer) { + if (buffer.length < 6) + return null; + if (buffer[0] !== 22) + return null; + let offset = 5; + if (buffer[offset] !== 1) + return null; + offset += 4; + offset += 2; + offset += 32; + if (offset >= buffer.length) + return null; + const sessionIdLength = buffer[offset]; + offset += 1 + sessionIdLength; + if (offset + 2 > buffer.length) + return null; + const cipherSuitesLength = buffer.readUInt16BE(offset); + offset += 2 + cipherSuitesLength; + if (offset >= buffer.length) + return null; + const compressionMethodsLength = buffer[offset]; + offset += 1 + compressionMethodsLength; + if (offset + 2 > buffer.length) + return null; + const extensionsLength = buffer.readUInt16BE(offset); + offset += 2; + const extensionsEnd = offset + extensionsLength; + if (extensionsEnd > buffer.length) + return null; + while (offset + 4 <= extensionsEnd) { + const extensionType = buffer.readUInt16BE(offset); + offset += 2; + const extensionLength = buffer.readUInt16BE(offset); + offset += 2; + if (offset + extensionLength > extensionsEnd) + return null; + if (extensionType === 16) + return parseALPNExtension(buffer.subarray(offset, offset + extensionLength)); + offset += extensionLength; + } + return null; +} +function parseALPNExtension(buffer) { + if (buffer.length < 2) + return null; + const listLength = buffer.readUInt16BE(0); + if (listLength !== buffer.length - 2) + return null; + const protocols = []; + let offset = 2; + while (offset < buffer.length) { + const protocolLength = buffer[offset]; + offset += 1; + if (offset + protocolLength > buffer.length) + break; + const protocol = buffer.subarray(offset, offset + protocolLength).toString("utf8"); + protocols.push(protocol); + offset += protocolLength; + } + return protocols.length > 0 ? protocols : null; +} +var import_events4, import_http23, import_net3, import_stream3, import_tls2, getProxyForUrl2, dummyServerTlsOptions, SocksProxyConnection, ClientCertificatesProxy; +var init_socksClientCertificatesInterceptor = __esm({ + "packages/playwright-core/src/server/socksClientCertificatesInterceptor.ts"() { + "use strict"; + import_events4 = require("events"); + import_http23 = __toESM(require("http2")); + import_net3 = __toESM(require("net")); + import_stream3 = __toESM(require("stream")); + import_tls2 = __toESM(require("tls")); + init_socksProxy(); + init_debugLogger(); + init_happyEyeballs(); + init_stringUtils(); + init_crypto(); + init_stackTrace(); + init_network(); + init_browserContext(); + ({ getProxyForUrl: getProxyForUrl2 } = require("./utilsBundle")); + dummyServerTlsOptions = void 0; + SocksProxyConnection = class { + constructor(socksProxy, uid, host, port) { + this._firstPackageReceived = false; + this._closed = false; + this.socksProxy = socksProxy; + this.uid = uid; + this.host = host; + this.port = port; + this._serverCloseEventListener = () => { + this._browserEncrypted.destroy(); + }; + this._browserEncrypted = new import_stream3.default.Duplex({ + read: () => { + }, + write: (data, encoding, callback) => { + this.socksProxy._socksProxy.sendSocketData({ uid: this.uid, data }); + callback(); + }, + destroy: (error, callback) => { + if (error) + socksProxy._socksProxy.sendSocketError({ uid: this.uid, error: error.message }); + else + socksProxy._socksProxy.sendSocketEnd({ uid: this.uid }); + callback(); + } + }); + } + async connect() { + const proxyAgent = this.socksProxy._getProxyAgent(this.host, this.port); + if (proxyAgent) + this._serverEncrypted = await proxyAgent.connect(new import_events4.EventEmitter(), { host: rewriteToLocalhostIfNeeded(this.host), port: this.port, secureEndpoint: false }); + else + this._serverEncrypted = await createSocket(rewriteToLocalhostIfNeeded(this.host), this.port); + this._serverEncrypted.once("close", this._serverCloseEventListener); + this._serverEncrypted.once("error", (error) => this._browserEncrypted.destroy(error)); + if (this._closed) { + this._serverEncrypted.destroy(); + return; + } + this.socksProxy._socksProxy.socketConnected({ + uid: this.uid, + host: this._serverEncrypted.localAddress, + port: this._serverEncrypted.localPort + }); + } + onClose() { + this._serverEncrypted.destroy(); + this._browserEncrypted.destroy(); + this._closed = true; + } + onData(data) { + if (!this._firstPackageReceived) { + this._firstPackageReceived = true; + if (data[0] === 22) + this._establishTlsTunnel(this._browserEncrypted, data); + else + this._establishPlaintextTunnel(this._browserEncrypted); + } + this._browserEncrypted.push(data); + } + _establishPlaintextTunnel(browserEncrypted) { + browserEncrypted.pipe(this._serverEncrypted); + this._serverEncrypted.pipe(browserEncrypted); + } + _establishTlsTunnel(browserEncrypted, clientHello) { + const browserALPNProtocols = parseALPNFromClientHello(clientHello) || ["http/1.1"]; + debugLogger.log("client-certificates", `Browser->Proxy ${this.host}:${this.port} offers ALPN ${browserALPNProtocols}`); + const serverDecrypted = import_tls2.default.connect({ + socket: this._serverEncrypted, + host: this.host, + port: this.port, + rejectUnauthorized: !this.socksProxy.ignoreHTTPSErrors, + ALPNProtocols: browserALPNProtocols, + servername: !import_net3.default.isIP(this.host) ? this.host : void 0, + secureContext: this.socksProxy.secureContextMap.get(new URL(`https://${this.host}:${this.port}`).origin) + }, async () => { + const browserDecrypted = await this._upgradeToTLSIfNeeded(browserEncrypted, serverDecrypted.alpnProtocol); + debugLogger.log("client-certificates", `Proxy->Server ${this.host}:${this.port} chooses ALPN ${browserDecrypted.alpnProtocol}`); + browserDecrypted.pipe(serverDecrypted); + serverDecrypted.pipe(browserDecrypted); + const cleanup = (error) => this._serverEncrypted.destroy(error); + browserDecrypted.once("error", cleanup); + serverDecrypted.once("error", cleanup); + browserDecrypted.once("close", cleanup); + serverDecrypted.once("close", cleanup); + if (this._closed) + serverDecrypted.destroy(); + }); + serverDecrypted.once("error", async (error) => { + debugLogger.log("client-certificates", `error when connecting to server: ${error.message.replaceAll("\n", " ")}`); + this._serverEncrypted.removeListener("close", this._serverCloseEventListener); + this._serverEncrypted.destroy(); + const browserDecrypted = await this._upgradeToTLSIfNeeded(this._browserEncrypted, serverDecrypted.alpnProtocol); + const responseBody = escapeHTML("Playwright client-certificate error: " + error.message).replaceAll("\n", "
"); + if (browserDecrypted.alpnProtocol === "h2") { + if ("performServerHandshake" in import_http23.default) { + const session2 = import_http23.default.performServerHandshake(browserDecrypted); + session2.on("error", (error2) => { + this._browserEncrypted.destroy(error2); + }); + session2.once("stream", (stream3) => { + const cleanup = (error2) => { + session2.close(); + this._browserEncrypted.destroy(error2); + }; + stream3.once("end", cleanup); + stream3.once("error", cleanup); + stream3.respond({ + [import_http23.default.constants.HTTP2_HEADER_CONTENT_TYPE]: "text/html", + [import_http23.default.constants.HTTP2_HEADER_STATUS]: 503 + }); + stream3.end(responseBody); + }); + } else { + this._browserEncrypted.destroy(error); + } + } else { + browserDecrypted.end([ + "HTTP/1.1 503 Internal Server Error", + "Content-Type: text/html; charset=utf-8", + "Content-Length: " + Buffer.byteLength(responseBody), + "", + responseBody + ].join("\r\n")); + } + }); + } + async _upgradeToTLSIfNeeded(socket, alpnProtocol) { + this._brorwserDecrypted ??= new Promise((resolve, reject) => { + const dummyServer = import_tls2.default.createServer({ + ...dummyServerTlsOptions, + ALPNProtocols: [alpnProtocol || "http/1.1"] + }); + dummyServer.emit("connection", socket); + dummyServer.once("secureConnection", (tlsSocket) => { + dummyServer.close(); + resolve(tlsSocket); + }); + dummyServer.once("error", (error) => { + dummyServer.close(); + reject(error); + }); + }); + return this._brorwserDecrypted; + } + }; + ClientCertificatesProxy = class _ClientCertificatesProxy { + constructor(contextOptions) { + this._connections = /* @__PURE__ */ new Map(); + this.secureContextMap = /* @__PURE__ */ new Map(); + verifyClientCertificates(contextOptions.clientCertificates); + this.ignoreHTTPSErrors = contextOptions.ignoreHTTPSErrors; + this._proxy = 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 (error) { + debugLogger.log("client-certificates", `Failed to connect to ${payload.host}:${payload.port}: ${error.message}`); + this._socksProxy.socketFailed({ uid: payload.uid, errorCode: error.code }); + } + }); + this._socksProxy.addListener(SocksProxy.Events.SocksData, (payload) => { + this._connections.get(payload.uid)?.onData(payload.data); + }); + this._socksProxy.addListener(SocksProxy.Events.SocksClosed, (payload) => { + this._connections.get(payload.uid)?.onClose(); + this._connections.delete(payload.uid); + }); + loadDummyServerCertsIfNeeded(); + } + _getProxyAgent(host, port) { + const proxyFromOptions = createProxyAgent(this._proxy); + if (proxyFromOptions) + return proxyFromOptions; + const proxyFromEnv = getProxyForUrl2(`https://${host}:${port}`); + if (proxyFromEnv) + return createProxyAgent({ server: proxyFromEnv }); + } + _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, import_tls2.default.createSecureContext(convertClientCertificatesToTLSOptions(certs))); + } catch (error) { + error = rewriteOpenSSLErrorIfNeeded(error); + throw rewriteErrorMessage(error, `Failed to load client certificate: ${error.message}`); + } + } + } + static async create(progress2, contextOptions) { + const proxy = new _ClientCertificatesProxy(contextOptions); + try { + await progress2.race(proxy._socksProxy.listen(0, "127.0.0.1")); + return proxy; + } catch (error) { + await progress2.race(proxy.close()); + throw error; + } + } + proxySettings() { + return { server: `socks5://127.0.0.1:${this._socksProxy.port()}` }; + } + async close() { + await this._socksProxy.close(); + } + }; + } +}); + +// packages/playwright-core/src/server/trace/recorder/snapshotterInjected.ts +function frameSnapshotStreamer(snapshotStreamer, removeNoScript) { + if (window[snapshotStreamer]) + return; + const kShadowAttribute = "__playwright_shadow_root_"; + const kValueAttribute = "__playwright_value_"; + const kCheckedAttribute = "__playwright_checked_"; + const kSelectedAttribute = "__playwright_selected_"; + const kScrollTopAttribute = "__playwright_scroll_top_"; + const kScrollLeftAttribute = "__playwright_scroll_left_"; + const kStyleSheetAttribute = "__playwright_style_sheet_"; + const kTargetAttribute = "__playwright_target__"; + const kCustomElementsAttribute = "__playwright_custom_elements__"; + const kCurrentSrcAttribute = "__playwright_current_src__"; + const kBoundingRectAttribute = "__playwright_bounding_rect__"; + const kPopoverOpenAttribute = "__playwright_popover_open_"; + const kDialogOpenAttribute = "__playwright_dialog_open_"; + const kSnapshotFrameId = Symbol("__playwright_snapshot_frameid_"); + const kCachedData = Symbol("__playwright_snapshot_cache_"); + const kEndOfList = Symbol("__playwright_end_of_list_"); + function resetCachedData(obj) { + delete obj[kCachedData]; + } + function ensureCachedData(obj) { + if (!obj[kCachedData]) + obj[kCachedData] = {}; + return obj[kCachedData]; + } + function removeHash2(url2) { + try { + const u = new URL(url2); + u.hash = ""; + return u.toString(); + } catch (e) { + return url2; + } + } + class Streamer { + constructor() { + this._lastSnapshotNumber = 0; + this._staleStyleSheets = /* @__PURE__ */ new Set(); + this._modifiedStyleSheets = /* @__PURE__ */ new Set(); + this._readingStyleSheet = false; + const invalidateCSSGroupingRule = (rule) => { + if (rule.parentStyleSheet) + this._invalidateStyleSheet(rule.parentStyleSheet); + }; + this._interceptNativeMethod(window.CSSStyleSheet.prototype, "insertRule", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeMethod(window.CSSStyleSheet.prototype, "deleteRule", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeMethod(window.CSSStyleSheet.prototype, "addRule", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeMethod(window.CSSStyleSheet.prototype, "removeRule", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeGetter(window.CSSStyleSheet.prototype, "rules", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeGetter(window.CSSStyleSheet.prototype, "cssRules", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeMethod(window.CSSStyleSheet.prototype, "replaceSync", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeMethod(window.CSSGroupingRule.prototype, "insertRule", invalidateCSSGroupingRule); + this._interceptNativeMethod(window.CSSGroupingRule.prototype, "deleteRule", invalidateCSSGroupingRule); + this._interceptNativeGetter(window.CSSGroupingRule.prototype, "cssRules", invalidateCSSGroupingRule); + this._interceptNativeSetter(window.StyleSheet.prototype, "disabled", (sheet) => { + if (sheet instanceof CSSStyleSheet) + this._invalidateStyleSheet(sheet); + }); + this._interceptNativeAsyncMethod(window.CSSStyleSheet.prototype, "replace", (sheet) => this._invalidateStyleSheet(sheet)); + this._fakeBase = document.createElement("base"); + this._observer = new MutationObserver((list) => this._handleMutations(list)); + const observerConfig = { attributes: true, subtree: true }; + this._observer.observe(document, observerConfig); + this._refreshListenersWhenNeeded(); + } + _refreshListenersWhenNeeded() { + this._refreshListeners(); + const customEventName = "__playwright_snapshotter_global_listeners_check__"; + let seenEvent = false; + const handleCustomEvent = () => seenEvent = true; + window.addEventListener(customEventName, handleCustomEvent); + const observer = new MutationObserver((entries) => { + const newDocumentElement = entries.some((entry) => Array.from(entry.addedNodes).includes(document.documentElement)); + if (newDocumentElement) { + seenEvent = false; + window.dispatchEvent(new CustomEvent(customEventName)); + if (!seenEvent) { + window.addEventListener(customEventName, handleCustomEvent); + this._refreshListeners(); + } + } + }); + observer.observe(document, { childList: true }); + } + _refreshListeners() { + document.addEventListener("__playwright_mark_target__", (event) => { + if (!event.detail) + return; + const callId = event.detail; + event.composedPath()[0].__playwright_target__ = callId; + }); + document.addEventListener("__playwright_unmark_target__", (event) => { + if (!event.detail) + return; + const callId = event.detail; + if (event.composedPath()[0].__playwright_target__ === callId) + delete event.composedPath()[0].__playwright_target__; + }); + } + _interceptNativeMethod(obj, method, cb) { + const native = obj[method]; + if (!native) + return; + obj[method] = function(...args) { + const result2 = native.call(this, ...args); + cb(this, result2); + return result2; + }; + } + _interceptNativeAsyncMethod(obj, method, cb) { + const native = obj[method]; + if (!native) + return; + obj[method] = async function(...args) { + const result2 = await native.call(this, ...args); + cb(this, result2); + return result2; + }; + } + _interceptNativeGetter(obj, prop, cb) { + const descriptor = Object.getOwnPropertyDescriptor(obj, prop); + Object.defineProperty(obj, prop, { + ...descriptor, + get: function() { + const result2 = descriptor.get.call(this); + cb(this, result2); + return result2; + } + }); + } + _interceptNativeSetter(obj, prop, cb) { + const descriptor = Object.getOwnPropertyDescriptor(obj, prop); + Object.defineProperty(obj, prop, { + ...descriptor, + set: function(value2) { + const result2 = descriptor.set.call(this, value2); + cb(this, value2); + return result2; + } + }); + } + _handleMutations(list) { + for (const mutation of list) + ensureCachedData(mutation.target).attributesCached = void 0; + } + _invalidateStyleSheet(sheet) { + if (this._readingStyleSheet) + return; + this._staleStyleSheets.add(sheet); + if (sheet.href !== null) + this._modifiedStyleSheets.add(sheet); + } + _updateStyleElementStyleSheetTextIfNeeded(sheet, forceText) { + const data = ensureCachedData(sheet); + if (this._staleStyleSheets.has(sheet) || forceText && data.cssText === void 0) { + this._staleStyleSheets.delete(sheet); + try { + data.cssText = this._getSheetText(sheet); + } catch (e) { + data.cssText = ""; + } + } + return data.cssText; + } + // Returns either content, ref, or no override. + _updateLinkStyleSheetTextIfNeeded(sheet, snapshotNumber) { + const data = ensureCachedData(sheet); + if (this._staleStyleSheets.has(sheet)) { + this._staleStyleSheets.delete(sheet); + try { + data.cssText = this._getSheetText(sheet); + data.cssRef = snapshotNumber; + return data.cssText; + } catch (e) { + } + } + return data.cssRef === void 0 ? void 0 : snapshotNumber - data.cssRef; + } + markIframe(iframeElement, frameId) { + iframeElement[kSnapshotFrameId] = frameId; + } + reset() { + this._staleStyleSheets.clear(); + const visitNode = (node) => { + resetCachedData(node); + if (node.nodeType === Node.ELEMENT_NODE) { + const element2 = node; + if (element2.shadowRoot) + visitNode(element2.shadowRoot); + } + for (let child = node.firstChild; child; child = child.nextSibling) + visitNode(child); + }; + visitNode(document.documentElement); + visitNode(this._fakeBase); + } + __sanitizeMetaAttribute(name, value2, httpEquiv) { + if (name === "charset") + return "utf-8"; + if (httpEquiv.toLowerCase() !== "content-type" || name !== "content") + return value2; + const [type3, ...params2] = value2.split(";"); + if (type3 !== "text/html" || params2.length <= 0) + return value2; + const charsetParamIdx = params2.findIndex((param) => param.trim().startsWith("charset=")); + if (charsetParamIdx > -1) + params2[charsetParamIdx] = "charset=utf-8"; + return `${type3}; ${params2.join("; ")}`; + } + _sanitizeUrl(url2) { + if (url2.startsWith("javascript:") || url2.startsWith("vbscript:")) + return ""; + return url2; + } + _sanitizeSrcSet(srcset) { + return srcset.split(",").map((src) => { + src = src.trim(); + const spaceIndex = src.lastIndexOf(" "); + if (spaceIndex === -1) + return this._sanitizeUrl(src); + return this._sanitizeUrl(src.substring(0, spaceIndex).trim()) + src.substring(spaceIndex); + }).join(", "); + } + _resolveUrl(base, url2) { + if (url2 === "") + return ""; + try { + return new URL(url2, base).href; + } catch (e) { + return url2; + } + } + _getSheetBase(sheet) { + let rootSheet = sheet; + while (rootSheet.parentStyleSheet) + rootSheet = rootSheet.parentStyleSheet; + if (rootSheet.ownerNode) + return rootSheet.ownerNode.baseURI; + return document.baseURI; + } + _getSheetText(sheet) { + this._readingStyleSheet = true; + try { + if (sheet.disabled) + return ""; + const rules = []; + for (const rule of sheet.cssRules) + rules.push(rule.cssText); + return rules.join("\n"); + } finally { + this._readingStyleSheet = false; + } + } + captureSnapshot(needsReset) { + const timestamp = performance.now(); + const snapshotNumber = ++this._lastSnapshotNumber; + if (needsReset) + this.reset(); + let nodeCounter = 0; + let shadowDomNesting = 0; + let headNesting = 0; + this._handleMutations(this._observer.takeRecords()); + const definedCustomElements = /* @__PURE__ */ new Set(); + const visitNode = (node) => { + const nodeType = node.nodeType; + const nodeName = nodeType === Node.DOCUMENT_FRAGMENT_NODE ? "template" : node.nodeName; + if (nodeType !== Node.ELEMENT_NODE && nodeType !== Node.DOCUMENT_FRAGMENT_NODE && nodeType !== Node.TEXT_NODE) + return; + if (nodeName === "SCRIPT") + return; + if (nodeName === "LINK" && nodeType === Node.ELEMENT_NODE) { + const rel = node.getAttribute("rel")?.toLowerCase(); + if (rel === "preload" || rel === "prefetch") + return; + } + if (removeNoScript && nodeName === "NOSCRIPT") + return; + if (nodeName === "META") { + const httpEquiv = node.httpEquiv.toLowerCase(); + if (httpEquiv === "content-security-policy" || httpEquiv === "refresh" || httpEquiv === "set-cookie") + return; + } + if ((nodeName === "IFRAME" || nodeName === "FRAME") && headNesting) + return; + const data = ensureCachedData(node); + const values = []; + let equals = !!data.cached; + let extraNodes = 0; + const expectValue = (value2) => { + equals = equals && data.cached[values.length] === value2; + values.push(value2); + }; + const checkAndReturn = (n) => { + data.attributesCached = true; + if (equals) + return { equals: true, n: [[snapshotNumber - data.ref[0], data.ref[1]]] }; + nodeCounter += extraNodes; + data.ref = [snapshotNumber, nodeCounter++]; + data.cached = values; + return { equals: false, n }; + }; + if (nodeType === Node.TEXT_NODE) { + const value2 = node.nodeValue || ""; + expectValue(value2); + return checkAndReturn(value2); + } + if (nodeName === "STYLE") { + const sheet = node.sheet; + let cssText; + if (sheet) + cssText = this._updateStyleElementStyleSheetTextIfNeeded(sheet); + cssText = cssText || node.textContent || ""; + expectValue(cssText); + extraNodes++; + return checkAndReturn([nodeName, {}, cssText]); + } + const attrs = {}; + const result3 = [nodeName, attrs]; + const visitChild = (child) => { + const snapshot3 = visitNode(child); + if (snapshot3) { + result3.push(snapshot3.n); + expectValue(child); + equals = equals && snapshot3.equals; + } + }; + const visitChildStyleSheet = (child) => { + const snapshot3 = visitStyleSheet(child); + if (snapshot3) { + result3.push(snapshot3.n); + expectValue(child); + equals = equals && snapshot3.equals; + } + }; + if (nodeType === Node.DOCUMENT_FRAGMENT_NODE) + attrs[kShadowAttribute] = "open"; + if (nodeType === Node.ELEMENT_NODE) { + const element2 = node; + if (element2.localName.includes("-") && window.customElements?.get(element2.localName)) + definedCustomElements.add(element2.localName); + if (nodeName === "INPUT" || nodeName === "TEXTAREA") { + const value2 = element2.value; + expectValue(kValueAttribute); + expectValue(value2); + attrs[kValueAttribute] = value2; + } + if (nodeName === "INPUT" && ["checkbox", "radio"].includes(element2.type)) { + const value2 = element2.checked ? "true" : "false"; + expectValue(kCheckedAttribute); + expectValue(value2); + attrs[kCheckedAttribute] = value2; + } + if (nodeName === "OPTION") { + const value2 = element2.selected ? "true" : "false"; + expectValue(kSelectedAttribute); + expectValue(value2); + attrs[kSelectedAttribute] = value2; + } + if (nodeName === "CANVAS" || nodeName === "IFRAME" || nodeName === "FRAME") { + const boundingRect = element2.getBoundingClientRect(); + const value2 = JSON.stringify({ + left: boundingRect.left, + top: boundingRect.top, + right: boundingRect.right, + bottom: boundingRect.bottom + }); + expectValue(kBoundingRectAttribute); + expectValue(value2); + attrs[kBoundingRectAttribute] = value2; + } + if (element2.popover && element2.matches && element2.matches(":popover-open")) { + const value2 = "true"; + expectValue(kPopoverOpenAttribute); + expectValue(value2); + attrs[kPopoverOpenAttribute] = value2; + } + if (nodeName === "DIALOG" && element2.open) { + const value2 = element2.matches(":modal") ? "modal" : "true"; + expectValue(kDialogOpenAttribute); + expectValue(value2); + attrs[kDialogOpenAttribute] = value2; + } + if (element2.scrollTop) { + expectValue(kScrollTopAttribute); + expectValue(element2.scrollTop); + attrs[kScrollTopAttribute] = "" + element2.scrollTop; + } + if (element2.scrollLeft) { + expectValue(kScrollLeftAttribute); + expectValue(element2.scrollLeft); + attrs[kScrollLeftAttribute] = "" + element2.scrollLeft; + } + if (element2.shadowRoot) { + ++shadowDomNesting; + visitChild(element2.shadowRoot); + --shadowDomNesting; + } + if ("__playwright_target__" in element2) { + expectValue(kTargetAttribute); + expectValue(element2["__playwright_target__"]); + attrs[kTargetAttribute] = element2["__playwright_target__"]; + } + } + if (nodeName === "HEAD") { + ++headNesting; + this._fakeBase.setAttribute("href", document.baseURI); + visitChild(this._fakeBase); + } + for (let child = node.firstChild; child; child = child.nextSibling) + visitChild(child); + if (nodeName === "HEAD") + --headNesting; + expectValue(kEndOfList); + let documentOrShadowRoot = null; + if (node.ownerDocument.documentElement === node) + documentOrShadowRoot = node.ownerDocument; + else if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) + documentOrShadowRoot = node; + if (documentOrShadowRoot) { + for (const sheet of documentOrShadowRoot.adoptedStyleSheets || []) + visitChildStyleSheet(sheet); + expectValue(kEndOfList); + } + if (nodeName === "IFRAME" || nodeName === "FRAME") { + const element2 = node; + const frameId = element2[kSnapshotFrameId]; + const name = "src"; + const value2 = frameId ? `/snapshot/${frameId}` : ""; + expectValue(name); + expectValue(value2); + attrs[name] = value2; + } + if (nodeName === "BODY" && definedCustomElements.size) { + const value2 = [...definedCustomElements].join(","); + expectValue(kCustomElementsAttribute); + expectValue(value2); + attrs[kCustomElementsAttribute] = value2; + } + if (nodeName === "IMG" || nodeName === "PICTURE") { + const value2 = nodeName === "PICTURE" ? "" : this._sanitizeUrl(node.currentSrc); + expectValue(kCurrentSrcAttribute); + expectValue(value2); + attrs[kCurrentSrcAttribute] = value2; + } + if (equals && data.attributesCached && !shadowDomNesting) + return checkAndReturn(result3); + if (nodeType === Node.ELEMENT_NODE) { + const element2 = node; + for (let i = 0; i < element2.attributes.length; i++) { + const name = element2.attributes[i].name; + if (nodeName === "LINK" && name === "integrity") + continue; + if (nodeName === "IFRAME" && (name === "src" || name === "srcdoc" || name === "sandbox")) + continue; + if (nodeName === "FRAME" && name === "src") + continue; + if (nodeName === "DIALOG" && name === "open") + continue; + let value2 = element2.attributes[i].value; + if (nodeName === "META") + value2 = this.__sanitizeMetaAttribute(name, value2, node.httpEquiv); + else if (name === "src" && nodeName === "IMG") + value2 = this._sanitizeUrl(value2); + else if (name === "srcset" && nodeName === "IMG") + value2 = this._sanitizeSrcSet(value2); + else if (name === "srcset" && nodeName === "SOURCE") + value2 = this._sanitizeSrcSet(value2); + else if (name === "href" && nodeName === "LINK") + value2 = this._sanitizeUrl(value2); + else if (name.startsWith("on")) + value2 = ""; + expectValue(name); + expectValue(value2); + attrs[name] = value2; + } + expectValue(kEndOfList); + } + if (result3.length === 2 && !Object.keys(attrs).length) + result3.pop(); + return checkAndReturn(result3); + }; + const visitStyleSheet = (sheet) => { + const data = ensureCachedData(sheet); + const oldCSSText = data.cssText; + const cssText = this._updateStyleElementStyleSheetTextIfNeeded( + sheet, + true + /* forceText */ + ); + if (cssText === oldCSSText) + return { equals: true, n: [[snapshotNumber - data.ref[0], data.ref[1]]] }; + data.ref = [snapshotNumber, nodeCounter++]; + return { + equals: false, + n: ["template", { + [kStyleSheetAttribute]: cssText + }] + }; + }; + let html; + if (document.documentElement) { + const { n } = visitNode(document.documentElement); + html = n; + } else { + html = ["html"]; + } + const result2 = { + html, + doctype: document.doctype ? document.doctype.name : void 0, + resourceOverrides: [], + viewport: { + width: window.innerWidth, + height: window.innerHeight + }, + url: location.href, + wallTime: Date.now(), + collectionTime: 0 + }; + for (const sheet of this._modifiedStyleSheets) { + if (sheet.href === null) + continue; + const content = this._updateLinkStyleSheetTextIfNeeded(sheet, snapshotNumber); + if (content === void 0) { + continue; + } + const base = this._getSheetBase(sheet); + const url2 = removeHash2(this._resolveUrl(base, sheet.href)); + result2.resourceOverrides.push({ url: url2, content, contentType: "text/css" }); + } + result2.collectionTime = performance.now() - timestamp; + return result2; + } + } + window[snapshotStreamer] = new Streamer(); +} +var init_snapshotterInjected = __esm({ + "packages/playwright-core/src/server/trace/recorder/snapshotterInjected.ts"() { + "use strict"; + } +}); + +// packages/isomorphic/utilityScriptSerializers.ts +function isRegExp5(obj) { + try { + return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]"; + } catch (error) { + return false; + } +} +function isDate2(obj) { + try { + return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]"; + } catch (error) { + return false; + } +} +function isURL2(obj) { + try { + return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]"; + } catch (error) { + return false; + } +} +function isError3(obj) { + try { + return obj instanceof Error || obj && Object.getPrototypeOf(obj)?.name === "Error"; + } catch (error) { + return false; + } +} +function isTypedArray(obj, constructor) { + try { + return obj instanceof constructor || Object.prototype.toString.call(obj) === `[object ${constructor.name}]`; + } catch (error) { + return false; + } +} +function isArrayBuffer(obj) { + try { + return obj instanceof ArrayBuffer || Object.prototype.toString.call(obj) === "[object ArrayBuffer]"; + } catch (error) { + return false; + } +} +function typedArrayToBase64(array) { + if ("toBase64" in array) + return array.toBase64(); + const binary = Array.from(new Uint8Array(array.buffer, array.byteOffset, array.byteLength)).map((b) => String.fromCharCode(b)).join(""); + return btoa(binary); +} +function base64ToTypedArray(base64, TypedArrayConstructor) { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) + bytes[i] = binary.charCodeAt(i); + return new TypedArrayConstructor(bytes.buffer); +} +function parseEvaluationResultValue(value2, handles = [], refs = /* @__PURE__ */ new Map()) { + if (Object.is(value2, void 0)) + return void 0; + if (typeof value2 === "object" && value2) { + if ("ref" in value2) + return refs.get(value2.ref); + if ("v" in value2) { + if (value2.v === "undefined") + return void 0; + if (value2.v === "null") + return null; + if (value2.v === "NaN") + return NaN; + if (value2.v === "Infinity") + return Infinity; + if (value2.v === "-Infinity") + return -Infinity; + if (value2.v === "-0") + return -0; + return void 0; + } + if ("d" in value2) { + return new Date(value2.d); + } + if ("u" in value2) + return new URL(value2.u); + if ("bi" in value2) + return BigInt(value2.bi); + if ("e" in value2) { + const error = new Error(value2.e.m); + error.name = value2.e.n; + error.stack = value2.e.s; + return error; + } + if ("r" in value2) + return new RegExp(value2.r.p, value2.r.f); + if ("a" in value2) { + const result2 = []; + refs.set(value2.id, result2); + for (const a of value2.a) + result2.push(parseEvaluationResultValue(a, handles, refs)); + return result2; + } + if ("o" in value2) { + const result2 = {}; + refs.set(value2.id, result2); + for (const { k, v } of value2.o) { + if (k === "__proto__") + continue; + result2[k] = parseEvaluationResultValue(v, handles, refs); + } + return result2; + } + if ("h" in value2) + return handles[value2.h]; + if ("ta" in value2) + return base64ToTypedArray(value2.ta.b, typedArrayConstructors[value2.ta.k]); + if ("ab" in value2) + return base64ToTypedArray(value2.ab.b, Uint8Array).buffer; + } + return value2; +} +function serializeAsCallArgument(value2, handleSerializer) { + return serialize(value2, handleSerializer, { visited: /* @__PURE__ */ new Map(), lastId: 0 }); +} +function serialize(value2, handleSerializer, visitorInfo) { + if (value2 && typeof value2 === "object") { + if (typeof globalThis.Window === "function" && value2 instanceof globalThis.Window) + return "ref: "; + if (typeof globalThis.Document === "function" && value2 instanceof globalThis.Document) + return "ref: "; + if (typeof globalThis.Node === "function" && value2 instanceof globalThis.Node) + return "ref: "; + } + return innerSerialize(value2, handleSerializer, visitorInfo); +} +function innerSerialize(value2, handleSerializer, visitorInfo) { + const result2 = handleSerializer(value2); + if ("fallThrough" in result2) + value2 = result2.fallThrough; + else + return result2; + if (typeof value2 === "symbol") + return { v: "undefined" }; + if (Object.is(value2, void 0)) + return { v: "undefined" }; + if (Object.is(value2, null)) + return { v: "null" }; + if (Object.is(value2, NaN)) + return { v: "NaN" }; + if (Object.is(value2, Infinity)) + return { v: "Infinity" }; + if (Object.is(value2, -Infinity)) + return { v: "-Infinity" }; + if (Object.is(value2, -0)) + return { v: "-0" }; + if (typeof value2 === "boolean") + return value2; + if (typeof value2 === "number") + return value2; + if (typeof value2 === "string") + return value2; + if (typeof value2 === "bigint") + return { bi: value2.toString() }; + if (isError3(value2)) { + let stack; + if (value2.stack?.startsWith(value2.name + ": " + value2.message)) { + stack = value2.stack; + } else { + stack = `${value2.name}: ${value2.message} +${value2.stack}`; + } + return { e: { n: value2.name, m: value2.message, s: stack } }; + } + if (isDate2(value2)) + return { d: value2.toJSON() }; + if (isURL2(value2)) + return { u: value2.toJSON() }; + if (isRegExp5(value2)) + return { r: { p: value2.source, f: value2.flags } }; + for (const [k, ctor] of Object.entries(typedArrayConstructors)) { + if (isTypedArray(value2, ctor)) + return { ta: { b: typedArrayToBase64(value2), k } }; + } + if (isArrayBuffer(value2)) + return { ab: { b: typedArrayToBase64(new Uint8Array(value2)) } }; + const id = visitorInfo.visited.get(value2); + if (id) + return { ref: id }; + if (Array.isArray(value2)) { + const a = []; + const id2 = ++visitorInfo.lastId; + visitorInfo.visited.set(value2, id2); + for (let i = 0; i < value2.length; ++i) + a.push(serialize(value2[i], handleSerializer, visitorInfo)); + return { a, id: id2 }; + } + if (typeof value2 === "object") { + const o = []; + const id2 = ++visitorInfo.lastId; + visitorInfo.visited.set(value2, id2); + for (const name of Object.keys(value2)) { + let item; + try { + item = value2[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 && value2.toJSON && typeof value2.toJSON === "function") + jsonWrapper = { value: value2.toJSON() }; + } catch (e) { + } + if (jsonWrapper) + return innerSerialize(jsonWrapper.value, handleSerializer, visitorInfo); + return { o, id: id2 }; + } +} +var typedArrayConstructors; +var init_utilityScriptSerializers = __esm({ + "packages/isomorphic/utilityScriptSerializers.ts"() { + "use strict"; + 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 + }; + } +}); + +// packages/playwright-core/src/server/disposable.ts +async function disposeAll2(disposables) { + const copy = [...disposables]; + disposables.length = 0; + await Promise.all(copy.map((d) => d.dispose())); +} +var DisposableObject; +var init_disposable2 = __esm({ + "packages/playwright-core/src/server/disposable.ts"() { + "use strict"; + init_instrumentation(); + DisposableObject = class extends SdkObject { + constructor(parent) { + super(parent, "disposable"); + this.parent = parent; + } + }; + } +}); + +// packages/playwright-core/src/server/console.ts +var ConsoleMessage; +var init_console = __esm({ + "packages/playwright-core/src/server/console.ts"() { + "use strict"; + ConsoleMessage = class { + constructor(page, worker, type3, text2, args, location2, timestamp) { + this._page = page; + this._worker = worker; + this._type = type3; + this._text = text2; + this._args = args; + this._location = location2 || { url: "", lineNumber: 0, columnNumber: 0 }; + this._timestamp = timestamp; + } + page() { + return this._page; + } + worker() { + return this._worker; + } + type() { + return this._type; + } + text() { + if (this._text === void 0) + this._text = this._args.map((arg) => arg.preview()).join(" "); + return this._text; + } + args() { + return this._args; + } + location() { + return this._location; + } + timestamp() { + return this._timestamp; + } + }; + } +}); + +// packages/playwright-core/src/server/fileChooser.ts +var FileChooser; +var init_fileChooser = __esm({ + "packages/playwright-core/src/server/fileChooser.ts"() { + "use strict"; + FileChooser = class { + constructor(elementHandle, isMultiple) { + this._elementHandle = elementHandle; + this._isMultiple = isMultiple; + } + element() { + return this._elementHandle; + } + isMultiple() { + return this._isMultiple; + } + }; + } +}); + +// packages/playwright-core/src/generated/utilityScriptSource.ts +var source2; +var init_utilityScriptSource = __esm({ + "packages/playwright-core/src/generated/utilityScriptSource.ts"() { + "use strict"; + source2 = '\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/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}\nfunction isArrayBuffer(obj) {\n try {\n return obj instanceof ArrayBuffer || Object.prototype.toString.call(obj) === "[object ArrayBuffer]";\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 if ("ab" in value)\n return base64ToTypedArray(value.ab.b, Uint8Array).buffer;\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 if (isArrayBuffer(value))\n return { ab: { b: typedArrayToBase64(new Uint8Array(value)) } };\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 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 AbortSignal: global.AbortSignal\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'; + } +}); + +// packages/playwright-core/src/server/javascript.ts +async function evaluate(context2, returnByValue, pageFunction, ...args) { + return evaluateExpression(context2, String(pageFunction), { returnByValue, isFunction: typeof pageFunction === "function" }, ...args); +} +async function evaluateExpression(context2, expression2, options2, ...args) { + expression2 = normalizeEvaluationExpression(expression2, 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) { + if (!handle._objectId) + return { fallThrough: handle._value }; + if (handle._disposed) + throw new JavaScriptErrorInEvaluate("JSHandle is disposed!"); + const adopted = context2.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 !== context2) + throw new JavaScriptErrorInEvaluate("JSHandles can be evaluated only in the context they were created!"); + utilityScriptObjects.push(handle); + } + const utilityScriptValues = [options2.isFunction, options2.returnByValue, expression2, args.length, ...args]; + const script = `(utilityScript, ...args) => utilityScript.evaluate(...args)`; + try { + return await context2._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(expression2, isFunction2) { + expression2 = expression2.trim(); + if (isFunction2) { + try { + new Function("(" + expression2 + ")"); + } catch (e1) { + if (expression2.startsWith("async ")) + expression2 = "async function " + expression2.substring("async ".length); + else + expression2 = "function " + expression2; + try { + new Function("(" + expression2 + ")"); + } catch (e2) { + throw new Error("Passed function is not well-serializable!"); + } + } + } + if (/^(async)?\s*function(\s|\()/.test(expression2)) + expression2 = "(" + expression2 + ")"; + return expression2; +} +function isJavaScriptErrorInEvaluate(error) { + return error instanceof JavaScriptErrorInEvaluate; +} +function sparseArrayToString(entries) { + const arrayEntries = []; + for (const { name, value: value2 } of entries) { + const index = +name; + if (isNaN(index) || index < 0) + continue; + arrayEntries.push({ index, value: value2 }); + } + arrayEntries.sort((a, b) => a.index - b.index); + let lastIndex = -1; + const tokens = []; + for (const { index, value: value2 } of arrayEntries) { + const emptyItems = index - lastIndex - 1; + if (emptyItems === 1) + tokens.push(`empty`); + else if (emptyItems > 1) + tokens.push(`empty x ${emptyItems}`); + tokens.push(String(value2)); + lastIndex = index; + } + return "[" + tokens.join(", ") + "]"; +} +var ExecutionContext, JSHandle, JavaScriptErrorInEvaluate; +var init_javascript = __esm({ + "packages/playwright-core/src/server/javascript.ts"() { + "use strict"; + init_utilityScriptSerializers(); + init_manualPromise(); + init_debug(); + init_instrumentation(); + init_utilityScriptSource(); + ExecutionContext = class 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(expression2) { + return this.raceAgainstContextDestroyed(this.delegate.rawEvaluateJSON(expression2)); + } + rawEvaluateHandle(expression2) { + return this.raceAgainstContextDestroyed(this.delegate.rawEvaluateHandle(this, expression2)); + } + async _evaluateWithArguments(expression2, returnByValue, values, handles) { + const utilityScript = await this._utilityScript(); + return this.raceAgainstContextDestroyed(this.delegate.evaluateWithArguments(expression2, 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 source8 = ` + (() => { + const module = {}; + ${source2} + return new (module.exports.UtilityScript())(globalThis, ${isUnderTest()}); + })();`; + this._utilityScriptPromise = this.raceAgainstContextDestroyed(this.delegate.rawEvaluateHandle(this, source8)).then((handle) => { + handle._setPreview("UtilityScript"); + return handle; + }); + } + return this._utilityScriptPromise; + } + }; + JSHandle = class extends SdkObject { + constructor(context2, type3, preview, objectId, value2) { + super(context2, "handle"); + this.__jshandle = true; + this._disposed = false; + this._context = context2; + this._objectId = objectId; + this._value = value2; + this._objectType = type3; + this._preview = this._objectId ? preview || `JSHandle@${this._objectType}` : String(value2); + if (this._objectId && globalThis.leakedJSHandles) + globalThis.leakedJSHandles.set(this, new Error("Leaked JSHandle")); + } + async evaluateExpression(progress2, expression2, options2, arg) { + return await progress2.race(this.internalEvaluateExpression(expression2, options2, arg)); + } + async evaluateExpressionHandle(progress2, expression2, options2, arg) { + return await progress2.race(this._evaluateExpressionHandle(expression2, options2, arg)); + } + async getProperty(progress2, propertyName) { + return await progress2.race(this._getProperty(propertyName)); + } + async getProperties(progress2) { + return await progress2.race(this.internalGetProperties()); + } + async jsonValue(progress2) { + return await progress2.race(this._jsonValue()); + } + 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 internalEvaluateExpression(expression2, options2, arg) { + return await evaluateExpression(this._context, expression2, { ...options2, returnByValue: true }, this, arg); + } + async _evaluateExpressionHandle(expression2, options2, arg) { + return await evaluateExpression(this._context, expression2, { ...options2, returnByValue: false }, this, arg); + } + async _getProperty(propertyName) { + const objectHandle = await this.evaluateHandle((object, propertyName2) => { + const result3 = { __proto__: null }; + result3[propertyName2] = object[propertyName2]; + return result3; + }, propertyName); + const properties = await objectHandle.internalGetProperties(); + const result2 = properties.get(propertyName); + objectHandle.dispose(); + return result2; + } + async internalGetProperties() { + 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); + } + }; + JavaScriptErrorInEvaluate = class extends Error { + }; + } +}); + +// packages/playwright-core/src/server/fileUploadUtils.ts +async function filesExceedUploadLimit(files) { + const sizes = await Promise.all(files.map(async (file) => (await import_fs12.default.promises.stat(file)).size)); + return sizes.reduce((total, size) => total + size, 0) >= fileUploadSizeLimit; +} +async function prepareFilesForUpload(frame, params2) { + const { payloads, streams, directoryStream } = params2; + let { localPaths, localDirectory } = params2; + 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(import_path12.default.isAbsolute(p) && import_path12.default.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: import_path12.default.basename(item), + buffer: await import_fs12.default.promises.readFile(item), + lastModifiedMs: (await import_fs12.default.promises.stat(item)).mtimeMs + }; + })); + localPaths = void 0; + } + } + const filePayloads = fileBuffers?.map((payload) => ({ + name: payload.name, + mimeType: payload.mimeType || mime3.getType(payload.name) || "application/octet-stream", + buffer: payload.buffer.toString("base64"), + lastModifiedMs: payload.lastModifiedMs + })); + return { localPaths, localDirectory, filePayloads }; +} +var import_fs12, import_path12, mime3, fileUploadSizeLimit; +var init_fileUploadUtils = __esm({ + "packages/playwright-core/src/server/fileUploadUtils.ts"() { + "use strict"; + import_fs12 = __toESM(require("fs")); + import_path12 = __toESM(require("path")); + init_assert(); + mime3 = require("./utilsBundle").mime; + fileUploadSizeLimit = 50 * 1024 * 1024; + } +}); + +// packages/playwright-core/src/generated/injectedScriptSource.ts +var source3; +var init_injectedScriptSource = __esm({ + "packages/playwright-core/src/generated/injectedScriptSource.ts"() { + "use strict"; + source3 = '\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/isomorphic/ariaSnapshot.ts\nfunction ariaNodesEqual(a, b) {\n if (a.role !== b.role || a.name !== b.name)\n return false;\n if (!ariaPropsEqual(a, b) || hasPointerCursor(a) !== hasPointerCursor(b))\n return false;\n const aKeys = Object.keys(a.props);\n const bKeys = Object.keys(b.props);\n return aKeys.length === bKeys.length && aKeys.every((k) => a.props[k] === b.props[k]);\n}\nfunction hasPointerCursor(ariaNode) {\n return ariaNode.box.cursor === "pointer";\n}\nfunction ariaPropsEqual(a, b) {\n return a.active === b.active && a.checked === b.checked && a.disabled === b.disabled && a.expanded === b.expanded && a.selected === b.selected && a.level === b.level && a.pressed === b.pressed;\n}\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: textValue(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)] = textValue(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: textValue(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 && (!fragment.containerMode || fragment.containerMode === "contain"))\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 textValue(value) {\n return {\n raw: value,\n normalized: normalizeWhitespace(value)\n };\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 === "active") {\n this._assert(value === "true" || value === "false", \'Value of "active" attribute must be a boolean\', errorPos);\n node.active = 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};\nfunction findNewNode(from, to) {\n var _a, _b;\n function fillMap(root, map, position) {\n let size = 1;\n let childPosition = position + size;\n for (const child of root.children || []) {\n if (typeof child === "string") {\n size++;\n childPosition++;\n } else {\n size += fillMap(child, map, childPosition);\n childPosition += size;\n }\n }\n if (!["none", "presentation", "fragment", "iframe", "generic"].includes(root.role) && root.name) {\n let byRole = map.get(root.role);\n if (!byRole) {\n byRole = /* @__PURE__ */ new Map();\n map.set(root.role, byRole);\n }\n const existing = byRole.get(root.name);\n const sizeAndPosition = size * 100 - position;\n if (!existing || existing.sizeAndPosition < sizeAndPosition)\n byRole.set(root.name, { node: root, sizeAndPosition });\n }\n return size;\n }\n const fromMap = /* @__PURE__ */ new Map();\n if (from)\n fillMap(from, fromMap, 0);\n const toMap = /* @__PURE__ */ new Map();\n fillMap(to, toMap, 0);\n const result = [];\n for (const [role, byRole] of toMap) {\n for (const [name, byName] of byRole) {\n const inFrom = (_a = fromMap.get(role)) == null ? void 0 : _a.get(name);\n if (!inFrom)\n result.push(byName);\n }\n }\n result.sort((a, b) => b.sizeAndPosition - a.sizeAndPosition);\n return (_b = result[0]) == null ? void 0 : _b.node;\n}\n\n// packages/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);\n const c2 = next(2);\n const 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/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/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/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}\nvar ansiRegex = new RegExp("([\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:[a-zA-Z\\\\d]*(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)|(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TZcf-ntqry=><~])))", "g");\n\n// packages/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 if (attr.name === "description") {\n options.exact = attr.caseSensitive;\n options.description = 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 (isRegExp(options.description))\n attrs.push(`description: ${this.regexToSourceString(options.description)}`);\n else if (typeof options.description === "string")\n attrs.push(`description: ${this.quote(options.description)}`);\n if (options.exact && (typeof options.name === "string" || typeof options.description === "string"))\n attrs.push(`exact: true`);\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 (isRegExp(options.description))\n attrs.push(`description=${this.regexToString(options.description)}`);\n else if (typeof options.description === "string")\n attrs.push(`description=${this.quote(options.description)}`);\n if (options.exact && (typeof options.name === "string" || typeof options.description === "string"))\n attrs.push(`exact=True`);\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 (isRegExp(options.description))\n attrs.push(`.setDescription(${this.regexToString(options.description)})`);\n else if (typeof options.description === "string")\n attrs.push(`.setDescription(${this.quote(options.description)})`);\n if (options.exact && (typeof options.name === "string" || typeof options.description === "string"))\n attrs.push(`.setExact(true)`);\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 (isRegExp(options.description))\n attrs.push(`DescriptionRegex = ${this.regexToString(options.description)}`);\n else if (typeof options.description === "string")\n attrs.push(`Description = ${this.quote(options.description)}`);\n if (options.exact && (typeof options.name === "string" || typeof options.description === "string"))\n attrs.push(`Exact = true`);\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/isomorphic/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/domUtils.ts\nvar globalOptions = {};\nfunction setGlobalOptions(options) {\n globalOptions = options;\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 const cache = pseudo === "::before" ? cacheStyleBefore : pseudo === "::after" ? cacheStyleAfter : cacheStyle;\n if (cache && cache.has(element))\n return cache.get(element);\n const style = element.ownerDocument && element.ownerDocument.defaultView ? element.ownerDocument.defaultView.getComputedStyle(element, pseudo) : void 0;\n cache == null ? void 0 : cache.set(element, style);\n return style;\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 computeBox(element) {\n const style = getElementComputedStyle(element);\n if (!style)\n return { visible: true, inline: false };\n const cursor = style.cursor;\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, inline: false, cursor };\n if (child.nodeType === 3 && isVisibleTextNode(child))\n return { visible: true, inline: true, cursor };\n }\n return { visible: false, inline: false, cursor };\n }\n if (!isElementStyleVisibilityVisible(element, style))\n return { cursor, visible: false, inline: false };\n const rect = element.getBoundingClientRect();\n return { cursor, visible: rect.width > 0 && rect.height > 0, inline: style.display === "inline" };\n}\nfunction isElementVisible(element) {\n return computeBox(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 const tagName = element.tagName;\n if (typeof tagName === "string")\n return tagName.toUpperCase();\n if (element instanceof HTMLFormElement)\n return "FORM";\n return element.tagName.toUpperCase();\n}\nvar cacheStyle;\nvar cacheStyleBefore;\nvar cacheStyleAfter;\nvar cachesCounter = 0;\nfunction beginDOMCaches() {\n ++cachesCounter;\n cacheStyle != null ? cacheStyle : cacheStyle = /* @__PURE__ */ new Map();\n cacheStyleBefore != null ? cacheStyleBefore : cacheStyleBefore = /* @__PURE__ */ new Map();\n cacheStyleAfter != null ? cacheStyleAfter : cacheStyleAfter = /* @__PURE__ */ new Map();\n}\nfunction endDOMCaches() {\n if (!--cachesCounter) {\n cacheStyle = void 0;\n cacheStyleBefore = void 0;\n cacheStyleAfter = void 0;\n }\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")\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 "SEARCH": () => "search",\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 const scope = e.getAttribute("scope");\n if (scope === "col" || scope === "colgroup")\n return "columnheader";\n if (scope === "row" || scope === "rowgroup")\n return "rowheader";\n const nextSibling = e.nextElementSibling;\n const prevSibling = e.previousElementSibling;\n const row = !!e.parentElement && elementSafeTagName(e.parentElement) === "TR" ? e.parentElement : void 0;\n if (!nextSibling && !prevSibling) {\n if (row) {\n const table = closestCrossShadow(row, "table");\n if (table && table.rows.length <= 1)\n return null;\n }\n return "columnheader";\n }\n if (isHeaderCell(nextSibling) && isHeaderCell(prevSibling))\n return "columnheader";\n if (isNonEmptyDataCell(nextSibling) || isNonEmptyDataCell(prevSibling))\n return "rowheader";\n return "columnheader";\n },\n "THEAD": () => "rowgroup",\n "TIME": () => "time",\n "TR": () => "row",\n "UL": () => "list"\n};\nfunction isHeaderCell(element) {\n return !!element && elementSafeTagName(element) === "TH";\n}\nfunction isNonEmptyDataCell(element) {\n var _a;\n if (!element || elementSafeTagName(element) !== "TD")\n return false;\n return !!(((_a = element.textContent) == null ? void 0 : _a.trim()) || element.children.length > 0);\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) {\n const contentValue = style.content;\n if (contentValue && contentValue !== "none" && contentValue !== "normal") {\n if (style.display !== "none" && style.visibility !== "hidden") {\n content = parseCSSContentPropertyAsString(element, contentValue, !!pseudo);\n }\n }\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 (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(elementSafeTagName(element));\n return isNativeFormControl && (element.hasAttribute("disabled") || belongsToDisabledOptGroup(element) || belongsToDisabledFieldSet(element));\n}\nfunction belongsToDisabledOptGroup(element) {\n return elementSafeTagName(element) === "OPTION" && !!element.closest("OPTGROUP[DISABLED]");\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 cachesCounter2 = 0;\nfunction beginAriaCaches() {\n beginDOMCaches();\n ++cachesCounter2;\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 (!--cachesCounter2) {\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 endDOMCaches();\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/ariaSnapshot.ts\nvar lastRef = 0;\nfunction toInternalOptions(options) {\n const renderBoxes = options.boxes;\n if (options.mode === "ai") {\n return {\n visibility: "ariaOrVisible",\n refs: "interactable",\n refPrefix: options.refPrefix,\n includeGenericRole: true,\n renderActive: !options.doNotRenderActive,\n renderCursorPointer: true,\n renderBoxes\n };\n }\n if (options.mode === "autoexpect") {\n return { visibility: "ariaAndVisible", refs: "none", renderBoxes };\n }\n if (options.mode === "codegen") {\n return { visibility: "aria", refs: "none", renderStringsAsRegex: true, renderBoxes };\n }\n return { visibility: "aria", refs: "none", renderBoxes };\n}\nfunction generateAriaTree(rootElement, publicOptions) {\n const options = toInternalOptions(publicOptions);\n const visited = /* @__PURE__ */ new Set();\n const snapshot = {\n root: { role: "fragment", name: "", children: [], props: {}, box: computeBox(rootElement), receivesPointerEvents: true },\n elements: /* @__PURE__ */ new Map(),\n refs: /* @__PURE__ */ new Map(),\n iframeRefs: []\n };\n setAriaNodeElement(snapshot.root, rootElement);\n const visit = (ariaNode, node, parentElementVisible) => {\n if (visited.has(node))\n return;\n visited.add(node);\n if (node.nodeType === Node.TEXT_NODE && node.nodeValue) {\n if (!parentElementVisible)\n return;\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 const isElementVisibleForAria = !isElementHiddenForAria(element);\n let visible = isElementVisibleForAria;\n if (options.visibility === "ariaOrVisible")\n visible = isElementVisibleForAria || isElementVisible(element);\n if (options.visibility === "ariaAndVisible")\n visible = isElementVisibleForAria && isElementVisible(element);\n if (options.visibility === "aria" && !visible)\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 = visible ? toAriaNode(element, options) : null;\n if (childAriaNode) {\n if (childAriaNode.ref) {\n snapshot.elements.set(childAriaNode.ref, element);\n snapshot.refs.set(element, childAriaNode.ref);\n if (childAriaNode.role === "iframe")\n snapshot.iframeRefs.push(childAriaNode.ref);\n }\n ariaNode.children.push(childAriaNode);\n }\n processElement(childAriaNode || ariaNode, element, ariaChildren, visible);\n };\n function processElement(ariaNode, element, ariaChildren, parentElementVisible) {\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, parentElementVisible);\n } else {\n for (let child = element.firstChild; child; child = child.nextSibling) {\n if (!child.assignedSlot)\n visit(ariaNode, child, parentElementVisible);\n }\n if (element.shadowRoot) {\n for (let child = element.shadowRoot.firstChild; child; child = child.nextSibling)\n visit(ariaNode, child, parentElementVisible);\n }\n }\n for (const child of ariaChildren)\n visit(ariaNode, child, parentElementVisible);\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 if (ariaNode.role === "textbox" && element.hasAttribute("placeholder") && element.getAttribute("placeholder") !== ariaNode.name) {\n const placeholder = element.getAttribute("placeholder");\n ariaNode.props["placeholder"] = placeholder;\n }\n }\n beginAriaCaches();\n try {\n visit(snapshot.root, rootElement, true);\n } finally {\n endAriaCaches();\n }\n normalizeStringChildren(snapshot.root);\n normalizeGenericRoles(snapshot.root);\n return snapshot;\n}\nfunction computeAriaRef(ariaNode, options) {\n var _a;\n if (options.refs === "none")\n return;\n if (options.refs === "interactable" && (!ariaNode.box.visible || !ariaNode.receivesPointerEvents))\n return;\n const element = ariaNodeElement(ariaNode);\n let ariaRef = element._ariaRef;\n if (!ariaRef || ariaRef.role !== ariaNode.role || ariaRef.name !== ariaNode.name) {\n ariaRef = { role: ariaNode.role, name: ariaNode.name, ref: ((_a = options.refPrefix) != null ? _a : "") + "e" + ++lastRef };\n element._ariaRef = ariaRef;\n }\n ariaNode.ref = ariaRef.ref;\n}\nfunction toAriaNode(element, options) {\n var _a;\n const active = element.ownerDocument.activeElement === element;\n if (element.nodeName === "IFRAME") {\n const ariaNode = {\n role: "iframe",\n name: "",\n children: [],\n props: {},\n box: computeBox(element),\n receivesPointerEvents: true,\n active\n };\n setAriaNodeElement(ariaNode, element);\n computeAriaRef(ariaNode, options);\n return ariaNode;\n }\n const defaultRole = options.includeGenericRole ? "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 receivesPointerEvents2 = receivesPointerEvents(element);\n const box = computeBox(element);\n if (role === "generic" && box.inline && element.childNodes.length === 1 && element.childNodes[0].nodeType === Node.TEXT_NODE)\n return null;\n const result = {\n role,\n name,\n children: [],\n props: {},\n box,\n receivesPointerEvents: receivesPointerEvents2,\n active\n };\n setAriaNodeElement(result, element);\n computeAriaRef(result, options);\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")\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" && !node2.name && result.length <= 1 && result.every((c) => typeof c !== "string" && !!c.ref);\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 matchesStringOrRegex(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 matchesTextValue(text, template) {\n if (!(template == null ? void 0 : template.normalized))\n return true;\n if (!text)\n return false;\n if (text === template.normalized)\n return true;\n if (text === template.raw)\n return true;\n const regex = cachedRegex(template);\n if (regex)\n return !!text.match(regex);\n return false;\n}\nvar cachedRegexSymbol = Symbol("cachedRegex");\nfunction cachedRegex(template) {\n if (template[cachedRegexSymbol] !== void 0)\n return template[cachedRegexSymbol];\n const { raw } = template;\n const canBeRegex = raw.startsWith("/") && raw.endsWith("/") && raw.length > 1;\n let regex;\n try {\n regex = canBeRegex ? new RegExp(raw.slice(1, -1)) : null;\n } catch (e) {\n regex = null;\n }\n template[cachedRegexSymbol] = regex;\n return regex;\n}\nfunction matchesExpectAriaTemplate(rootElement, template) {\n const snapshot = generateAriaTree(rootElement, { mode: "default" });\n const matches = matchesNodeDeep(snapshot.root, template, false, false);\n return {\n matches,\n received: {\n raw: renderAriaTree(snapshot, { mode: "default" }).text,\n regex: renderAriaTree(snapshot, { mode: "codegen" }).text\n }\n };\n}\nfunction getAllElementsMatchingExpectAriaTemplate(rootElement, template) {\n const root = generateAriaTree(rootElement, { mode: "default" }).root;\n const matches = matchesNodeDeep(root, template, true, false);\n return matches.map((n) => ariaNodeElement(n));\n}\nfunction matchesNode(node, template, isDeepEqual) {\n var _a;\n if (typeof node === "string" && template.kind === "text")\n return matchesTextValue(node, template.text);\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 (!matchesStringOrRegex(node.name, template.name))\n return false;\n if (!matchesTextValue(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 buildByRefMap(root, map = /* @__PURE__ */ new Map()) {\n if (root == null ? void 0 : root.ref)\n map.set(root.ref, root);\n for (const child of (root == null ? void 0 : root.children) || []) {\n if (typeof child !== "string")\n buildByRefMap(child, map);\n }\n return map;\n}\nfunction compareSnapshots(ariaSnapshot, previousSnapshot) {\n var _a;\n const previousByRef = buildByRefMap(previousSnapshot == null ? void 0 : previousSnapshot.root);\n const result = /* @__PURE__ */ new Map();\n const visit = (ariaNode, previousNode) => {\n let same = ariaNode.children.length === (previousNode == null ? void 0 : previousNode.children.length) && ariaNodesEqual(ariaNode, previousNode);\n let canBeSkipped = same;\n for (let childIndex = 0; childIndex < ariaNode.children.length; childIndex++) {\n const child = ariaNode.children[childIndex];\n const previousChild = previousNode == null ? void 0 : previousNode.children[childIndex];\n if (typeof child === "string") {\n same && (same = child === previousChild);\n canBeSkipped && (canBeSkipped = child === previousChild);\n } else {\n let previous = typeof previousChild !== "string" ? previousChild : void 0;\n if (child.ref)\n previous = previousByRef.get(child.ref);\n const sameChild = visit(child, previous);\n if (!previous || !sameChild && !child.ref || previous !== previousChild)\n canBeSkipped = false;\n same && (same = sameChild && previous === previousChild);\n }\n }\n result.set(ariaNode, same ? "same" : canBeSkipped ? "skip" : "changed");\n return same;\n };\n visit(ariaSnapshot.root, previousByRef.get((_a = previousSnapshot == null ? void 0 : previousSnapshot.root) == null ? void 0 : _a.ref));\n return result;\n}\nfunction filterSnapshotDiff(nodes, statusMap) {\n const result = [];\n const visit = (ariaNode) => {\n const status = statusMap.get(ariaNode);\n if (status === "same") {\n } else if (status === "skip") {\n for (const child of ariaNode.children) {\n if (typeof child !== "string")\n visit(child);\n }\n } else {\n result.push(ariaNode);\n }\n };\n for (const node of nodes) {\n if (typeof node === "string")\n result.push(node);\n else\n visit(node);\n }\n return result;\n}\nfunction indent(depth) {\n return " ".repeat(depth);\n}\nfunction renderAriaTree(ariaSnapshot, publicOptions, previousSnapshot) {\n const options = toInternalOptions(publicOptions);\n const lines = [];\n const iframeDepths = {};\n const includeText = options.renderStringsAsRegex ? textContributesInfo : () => true;\n const renderString = options.renderStringsAsRegex ? convertToBestGuessRegex : (str) => str;\n let nodesToRender = ariaSnapshot.root.role === "fragment" ? ariaSnapshot.root.children : [ariaSnapshot.root];\n const statusMap = compareSnapshots(ariaSnapshot, previousSnapshot);\n if (previousSnapshot)\n nodesToRender = filterSnapshotDiff(nodesToRender, statusMap);\n const visitText = (text, depth) => {\n if (publicOptions.depth && depth > publicOptions.depth)\n return;\n const escaped = yamlEscapeValueIfNeeded(renderString(text));\n if (escaped)\n lines.push(indent(depth) + "- text: " + escaped);\n };\n const createKey = (ariaNode, renderCursorPointer) => {\n let key = ariaNode.role;\n if (ariaNode.name && ariaNode.name.length <= 900) {\n const name = renderString(ariaNode.name);\n if (name) {\n const stringifiedName = name.startsWith("/") && name.endsWith("/") ? name : JSON.stringify(name);\n key += " " + stringifiedName;\n }\n }\n if (ariaNode.checked === "mixed")\n key += ` [checked=mixed]`;\n if (ariaNode.checked === true)\n key += ` [checked]`;\n if (ariaNode.disabled)\n key += ` [disabled]`;\n if (ariaNode.expanded)\n key += ` [expanded]`;\n if (ariaNode.active && options.renderActive)\n key += ` [active]`;\n if (ariaNode.level)\n key += ` [level=${ariaNode.level}]`;\n if (ariaNode.pressed === "mixed")\n key += ` [pressed=mixed]`;\n if (ariaNode.pressed === true)\n key += ` [pressed]`;\n if (ariaNode.selected === true)\n key += ` [selected]`;\n if (ariaNode.ref) {\n key += ` [ref=${ariaNode.ref}]`;\n if (renderCursorPointer && hasPointerCursor(ariaNode))\n key += " [cursor=pointer]";\n }\n if (options.renderBoxes) {\n const element = ariaNodeElement(ariaNode);\n if (element) {\n const r = element.getBoundingClientRect();\n key += ` [box=${Math.round(r.x)},${Math.round(r.y)},${Math.round(r.width)},${Math.round(r.height)}]`;\n }\n }\n return key;\n };\n const getSingleInlinedTextChild = (ariaNode) => {\n return (ariaNode == null ? void 0 : ariaNode.children.length) === 1 && typeof ariaNode.children[0] === "string" && !Object.keys(ariaNode.props).length ? ariaNode.children[0] : void 0;\n };\n const visit = (ariaNode, depth, renderCursorPointer) => {\n if (publicOptions.depth && depth > publicOptions.depth)\n return;\n if (ariaNode.role === "iframe" && ariaNode.ref)\n iframeDepths[ariaNode.ref] = depth;\n if (statusMap.get(ariaNode) === "same" && ariaNode.ref) {\n lines.push(indent(depth) + `- ref=${ariaNode.ref} [unchanged]`);\n return;\n }\n const isDiffRoot = !!previousSnapshot && !depth;\n const escapedKey = indent(depth) + "- " + (isDiffRoot ? " " : "") + yamlEscapeKeyIfNeeded(createKey(ariaNode, renderCursorPointer));\n const singleInlinedTextChild = getSingleInlinedTextChild(ariaNode);\n const isAtDepthLimit = !!publicOptions.depth && depth === publicOptions.depth;\n const hasNoChildren = !singleInlinedTextChild && (!ariaNode.children.length || isAtDepthLimit);\n if (hasNoChildren && !Object.keys(ariaNode.props).length) {\n lines.push(escapedKey);\n } else if (singleInlinedTextChild !== void 0) {\n const shouldInclude = includeText(ariaNode, singleInlinedTextChild);\n if (shouldInclude)\n lines.push(escapedKey + ": " + yamlEscapeValueIfNeeded(renderString(singleInlinedTextChild)));\n else\n lines.push(escapedKey);\n } else {\n lines.push(escapedKey + ":");\n for (const [name, value] of Object.entries(ariaNode.props))\n lines.push(indent(depth + 1) + "- /" + name + ": " + yamlEscapeValueIfNeeded(value));\n const inCursorPointer = !!ariaNode.ref && renderCursorPointer && hasPointerCursor(ariaNode);\n for (const child of ariaNode.children) {\n if (typeof child === "string")\n visitText(includeText(ariaNode, child) ? child : "", depth + 1);\n else\n visit(child, depth + 1, renderCursorPointer && !inCursorPointer);\n }\n }\n };\n for (const nodeToRender of nodesToRender) {\n if (typeof nodeToRender === "string")\n visitText(nodeToRender, 0);\n else\n visit(nodeToRender, 0, !!options.renderCursorPointer);\n }\n return { text: lines.join("\\n"), iframeDepths };\n}\nfunction convertToBestGuessRegex(text) {\n const dynamicContent = [\n // 550e8400-e29b-41d4-a716-446655440000\n { regex: /\\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\b/, replacement: "[0-9a-fA-F-]+" },\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 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}\nvar elementSymbol = Symbol("element");\nfunction ariaNodeElement(ariaNode) {\n return ariaNode[elementSymbol];\n}\nfunction setAriaNodeElement(ariaNode, element) {\n ariaNode[elementSymbol] = element;\n}\nfunction findNewElement(from, to) {\n const node = findNewNode(from, to);\n return node ? ariaNodeElement(node) : void 0;\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-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;z-index:10;font-size:13px}x-pw-dialog:not(.autosize){width:400px;height:150px}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-title{position:absolute;backdrop-filter:blur(5px);background-color:#00000080;color:#fff;border-radius:6px;padding:6px;font-size:24px;line-height:1.4;white-space:nowrap;user-select:none;z-index:3}x-pw-user-overlays,x-pw-user-overlay{position:absolute;inset:0}@keyframes pw-fade-out{0%{opacity:1}to{opacity:0}}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.record.toggled>x-div{clip-path:url(#icon-stop-circle)}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}x-pw-action-list{flex:auto;display:flex;flex-direction:column;user-select:none}x-pw-action-item{padding:6px 10px;cursor:pointer;overflow:hidden}x-pw-action-item:hover{background-color:#f2f2f2}x-pw-action-item:last-child{border-bottom-left-radius:6px;border-bottom-right-radius:6px}\\n";\n\n// packages/injected/src/highlight.ts\nvar Highlight = class {\n constructor(injectedScript) {\n this._renderedEntries = [];\n this._userOverlays = /* @__PURE__ */ new Map();\n this._userOverlayHidden = false;\n this._language = "javascript";\n this._elementHighlightSelectors = /* @__PURE__ */ new Map();\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.setAttribute("popover", "manual");\n this._glassPaneElement.style.inset = "0";\n this._glassPaneElement.style.width = "100%";\n this._glassPaneElement.style.height = "100%";\n this._glassPaneElement.style.maxWidth = "none";\n this._glassPaneElement.style.maxHeight = "none";\n this._glassPaneElement.style.padding = "0";\n this._glassPaneElement.style.margin = "0";\n this._glassPaneElement.style.border = "none";\n this._glassPaneElement.style.overflow = "visible";\n this._glassPaneElement.style.pointerEvents = "none";\n this._glassPaneElement.style.display = "flex";\n this._glassPaneElement.style.backgroundColor = "transparent";\n this._actionPointElement = document.createElement("x-pw-action-point");\n this._actionPointElement.setAttribute("hidden", "true");\n this._titleElement = document.createElement("x-pw-title");\n this._titleElement.setAttribute("hidden", "true");\n this._userOverlayContainer = document.createElement("x-pw-user-overlays");\n this._userOverlayContainer.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 this._glassPaneShadow.appendChild(this._titleElement);\n this._glassPaneShadow.appendChild(this._userOverlayContainer);\n }\n install() {\n if (!this._injectedScript.document.documentElement)\n return;\n if (!this._injectedScript.document.documentElement.contains(this._glassPaneElement) || this._glassPaneElement.nextElementSibling)\n this._injectedScript.document.documentElement.appendChild(this._glassPaneElement);\n this._bringToFront();\n }\n _bringToFront() {\n this._glassPaneElement.hidePopover();\n this._glassPaneElement.showPopover();\n }\n setLanguage(language) {\n this._language = language;\n }\n addElementHighlight(selector, cssStyle) {\n const key = stringifySelector(selector);\n this._elementHighlightSelectors.set(key, { selector, cssStyle });\n this._ensureElementHighlightRaf();\n }\n removeElementHighlight(selector) {\n const key = stringifySelector(selector);\n if (!this._elementHighlightSelectors.delete(key))\n return;\n if (this._elementHighlightSelectors.size === 0) {\n if (this._rafRequest) {\n this._injectedScript.utils.builtins.cancelAnimationFrame(this._rafRequest);\n this._rafRequest = void 0;\n }\n this.clearHighlight();\n }\n }\n _ensureElementHighlightRaf() {\n if (this._rafRequest)\n return;\n const tick = () => {\n const entries = [];\n for (const { selector, cssStyle } of this._elementHighlightSelectors.values()) {\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 for (let i = 0; i < elements.length; ++i) {\n const suffix = elements.length > 1 ? ` [${i + 1} of ${elements.length}]` : "";\n entries.push({ element: elements[i], color, tooltipText: locator + suffix, cssStyle });\n }\n }\n this.updateHighlight(entries);\n this._rafRequest = this._injectedScript.utils.builtins.requestAnimationFrame(tick);\n };\n this._rafRequest = this._injectedScript.utils.builtins.requestAnimationFrame(tick);\n }\n uninstall() {\n if (this._rafRequest) {\n this._injectedScript.utils.builtins.cancelAnimationFrame(this._rafRequest);\n this._rafRequest = void 0;\n }\n this._elementHighlightSelectors.clear();\n this._glassPaneElement.remove();\n }\n showActionPoint(x, y, fadeDuration) {\n this._actionPointElement.style.top = y + "px";\n this._actionPointElement.style.left = x + "px";\n this._actionPointElement.hidden = false;\n if (fadeDuration)\n this._actionPointElement.style.animation = `pw-fade-out ${fadeDuration}ms ease-out forwards`;\n else\n this._actionPointElement.style.animation = "";\n }\n hideActionPoint() {\n this._actionPointElement.hidden = true;\n }\n showActionTitle(text, fadeDuration, position, fontSize) {\n this._titleElement.textContent = text;\n this._titleElement.hidden = false;\n if (fadeDuration) {\n const fadeTime = fadeDuration / 4;\n this._titleElement.style.animation = `pw-fade-out ${fadeTime}ms ease-out ${fadeDuration - fadeTime}ms forwards`;\n } else {\n this._titleElement.style.animation = "";\n }\n this._titleElement.style.top = "";\n this._titleElement.style.bottom = "";\n this._titleElement.style.left = "";\n this._titleElement.style.right = "";\n this._titleElement.style.transform = "";\n switch (position) {\n case "top-left":\n this._titleElement.style.top = "6px";\n this._titleElement.style.left = "6px";\n break;\n case "top":\n this._titleElement.style.top = "6px";\n this._titleElement.style.left = "50%";\n this._titleElement.style.transform = "translateX(-50%)";\n break;\n case "bottom-left":\n this._titleElement.style.bottom = "6px";\n this._titleElement.style.left = "6px";\n break;\n case "bottom":\n this._titleElement.style.bottom = "6px";\n this._titleElement.style.left = "50%";\n this._titleElement.style.transform = "translateX(-50%)";\n break;\n case "bottom-right":\n this._titleElement.style.bottom = "6px";\n this._titleElement.style.right = "6px";\n break;\n case "top-right":\n default:\n this._titleElement.style.top = "6px";\n this._titleElement.style.right = "6px";\n break;\n }\n if (fontSize)\n this._titleElement.style.fontSize = fontSize + "px";\n }\n hideActionTitle() {\n this._titleElement.hidden = true;\n }\n addUserOverlay(id, html) {\n const element = this._injectedScript.document.createElement("div");\n element.className = "x-pw-user-overlay";\n element.innerHTML = html;\n for (const script of element.querySelectorAll("script"))\n script.remove();\n for (const el of element.querySelectorAll("*")) {\n for (const attr of [...el.attributes]) {\n if (attr.name.startsWith("on"))\n el.removeAttribute(attr.name);\n }\n }\n this._userOverlays.set(id, element);\n this._userOverlayContainer.appendChild(element);\n this._userOverlayContainer.hidden = this._userOverlayHidden;\n return id;\n }\n getUserOverlay(id) {\n return this._userOverlays.get(id);\n }\n removeUserOverlay(id) {\n const element = this._userOverlays.get(id);\n if (element) {\n element.remove();\n this._userOverlays.delete(id);\n }\n if (this._userOverlays.size === 0)\n this._userOverlayContainer.hidden = true;\n }\n setUserOverlaysVisible(visible) {\n this._userOverlayHidden = !visible;\n this._userOverlayContainer.hidden = !visible || this._userOverlays.size === 0;\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, box: toDOMRect(entry.box), color: entry.color, borderColor: entry.borderColor, fadeDuration: entry.fadeDuration, cssStyle: entry.cssStyle, tooltipElement, highlightElement });\n }\n for (const entry of this._renderedEntries) {\n if (!entry.box && !entry.targetElement)\n continue;\n entry.box = 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 box = entry.box;\n entry.highlightElement.style.backgroundColor = entry.color;\n entry.highlightElement.style.left = box.x + "px";\n entry.highlightElement.style.top = box.y + "px";\n entry.highlightElement.style.width = box.width + "px";\n entry.highlightElement.style.height = box.height + "px";\n entry.highlightElement.style.display = "block";\n if (entry.borderColor)\n entry.highlightElement.style.border = "2px solid " + entry.borderColor;\n if (entry.fadeDuration)\n entry.highlightElement.style.animation = `pw-fade-out ${entry.fadeDuration}ms ease-out forwards`;\n if (entry.cssStyle)\n entry.highlightElement.style.cssText += ";" + entry.cssStyle;\n if (this._isUnderTest)\n console.error("Highlight box for test: " + JSON.stringify({ x: box.x, y: box.y, width: box.width, height: box.height }));\n }\n }\n firstBox() {\n var _a;\n return (_a = this._renderedEntries[0]) == null ? void 0 : _a.box;\n }\n firstTooltipBox() {\n const entry = this._renderedEntries[0];\n if (!entry || !entry.tooltipElement || entry.tooltipLeft === void 0 || entry.tooltipTop === void 0)\n return;\n return {\n x: entry.tooltipLeft,\n y: entry.tooltipTop,\n left: entry.tooltipLeft,\n top: entry.tooltipTop,\n width: entry.tooltipElement.offsetWidth,\n height: entry.tooltipElement.offsetHeight,\n bottom: entry.tooltipTop + entry.tooltipElement.offsetHeight,\n right: entry.tooltipLeft + entry.tooltipElement.offsetWidth,\n toJSON: () => {\n }\n };\n }\n // Note: there is a copy of this method in dialog.tsx. Please fix bugs in both places.\n tooltipPosition(box, 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 = Math.max(5, box.left);\n if (anchorLeft + tooltipWidth > totalWidth - 5)\n anchorLeft = totalWidth - tooltipWidth - 5;\n let anchorTop = Math.max(0, box.bottom) + 5;\n if (anchorTop + tooltipHeight > totalHeight - 5) {\n if (Math.max(0, box.top) > tooltipHeight + 5) {\n anchorTop = Math.max(0, box.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 if (entries[i].cssStyle !== this._renderedEntries[i].cssStyle)\n return false;\n const oldBox = this._renderedEntries[i].box;\n if (!oldBox)\n return false;\n const box = entries[i].box ? toDOMRect(entries[i].box) : entries[i].element.getBoundingClientRect();\n if (box.top !== oldBox.top || box.right !== oldBox.right || box.bottom !== oldBox.bottom || box.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 onGlassPaneClick(handler) {\n this._glassPaneElement.style.pointerEvents = "auto";\n this._glassPaneElement.style.backgroundColor = "rgba(0, 0, 0, 0.3)";\n this._glassPaneElement.addEventListener("click", handler);\n }\n offGlassPaneClick(handler) {\n this._glassPaneElement.style.pointerEvents = "none";\n this._glassPaneElement.style.backgroundColor = "transparent";\n this._glassPaneElement.removeEventListener("click", handler);\n }\n};\nfunction toDOMRect(box) {\n if (!box)\n return void 0;\n return new DOMRect(box.x, box.y, box.width, box.height);\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 box = 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(box, 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 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/roleSelectorEngine.ts\nvar kSupportedAttributes = ["selected", "checked", "pressed", "expanded", "level", "disabled", "name", "description", "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.nameExact = attr.caseSensitive;\n break;\n }\n case "description": {\n if (attr.op === "")\n throw new Error(`"description" attribute must have a value`);\n if (typeof attr.value !== "string" && !(attr.value instanceof RegExp))\n throw new Error(`"description" attribute must be a string or a regular expression`);\n options.description = attr.value;\n options.descriptionOp = attr.op;\n options.descriptionExact = 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.nameExact && options.nameOp === "=")\n options.nameOp = "*=";\n if (!matchesAttributePart(accessibleName, { name: "", jsonPath: [], op: options.nameOp || "=", value: options.name, caseSensitive: !!options.nameExact }))\n return;\n }\n if (options.description !== void 0) {\n const accessibleDescription = normalizeWhiteSpace(getElementAccessibleDescription(element, !!options.includeHidden));\n if (typeof options.description === "string")\n options.description = normalizeWhiteSpace(options.description);\n if (internal && !options.descriptionExact && options.descriptionOp === "=")\n options.descriptionOp = "*=";\n if (!matchesAttributePart(accessibleDescription, { name: "", jsonPath: [], op: options.descriptionOp || "=", value: options.description, caseSensitive: !!options.descriptionExact }))\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 beginDOMCaches();\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 endDOMCaches();\n endAriaCaches();\n injectedScript._evaluator.end();\n }\n}\nfunction generateSelectorFor(cache, injectedScript, targetElement, options) {\n var _a;\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 let result = null;\n const updateResult = (candidate) => {\n if (!result || combineScores(candidate) < combineScores(result))\n result = candidate;\n };\n const candidates = [];\n if (!options.noText) {\n for (const candidate of buildTextCandidates(injectedScript, targetElement, !options.isRecursive))\n candidates.push({ candidate, isTextCandidate: true });\n }\n for (const token of buildNoTextCandidates(injectedScript, targetElement, options)) {\n if (options.omitInternalEngines && token.engine.startsWith("internal:"))\n continue;\n candidates.push({ candidate: [token], isTextCandidate: false });\n }\n candidates.sort((a, b) => combineScores(a.candidate) - combineScores(b.candidate));\n for (const { candidate, isTextCandidate } of candidates) {\n const elements = injectedScript.querySelectorAll(injectedScript.parseSelector(joinTokens(candidate)), (_a = options.root) != null ? _a : targetElement.ownerDocument);\n if (!elements.includes(targetElement)) {\n continue;\n }\n if (elements.length === 1) {\n updateResult(candidate);\n break;\n }\n const index = elements.indexOf(targetElement);\n if (index > 5) {\n continue;\n }\n updateResult([...candidate, { engine: "nth", selector: String(index), score: kNthScore }]);\n if (options.isRecursive) {\n continue;\n }\n for (let parent = parentElementOrShadowHost(targetElement); parent && parent !== options.root; parent = parentElementOrShadowHost(parent)) {\n const filtered = elements.filter((e) => isInsideScope(parent, e) && e !== parent);\n const newIndex = filtered.indexOf(targetElement);\n if (filtered.length > 5 || newIndex === -1 || newIndex === index && filtered.length > 1) {\n continue;\n }\n const inParent = filtered.length === 1 ? candidate : [...candidate, { engine: "nth", selector: String(newIndex), score: kNthScore }];\n const idealSelectorForParent = { engine: "", selector: "", score: 1 };\n if (result && combineScores([idealSelectorForParent, ...inParent]) >= combineScores(result)) {\n continue;\n }\n const noText = !!options.noText || isTextCandidate;\n const cacheMap = noText ? cache.disallowText : cache.allowText;\n let parentTokens = cacheMap.get(parent);\n if (parentTokens === void 0) {\n parentTokens = generateSelectorFor(cache, injectedScript, parent, { ...options, isRecursive: true, noText }) || cssFallback(injectedScript, parent, options);\n cacheMap.set(parent, parentTokens);\n }\n if (!parentTokens)\n continue;\n updateResult([...parentTokens, ...inParent]);\n }\n }\n return result;\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 (isTargetNode && 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 && !ariaName.match(/^\\p{Co}+$/u)) {\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 const ariaDescription = getElementAccessibleDescription(element, false);\n if (ariaDescription) {\n candidates.push([{ engine: "internal:role", selector: `${ariaRole}[name=${escapeForAttributeSelector(ariaName, true)}][description=${escapeForAttributeSelector(ariaDescription, true)}]`, score: kRoleWithNameScoreExact + 1 }]);\n for (const alternative of suitableTextAlternatives(ariaName))\n candidates.push([{ engine: "internal:role", selector: `${ariaRole}[name=${escapeForAttributeSelector(alternative.text, false)}][description=${escapeForAttributeSelector(ariaDescription, true)}]`, score: kRoleWithNameScore - alternative.scoreBonus + 1 }]);\n }\n } else {\n const roleToken = { engine: "internal:role", selector: `${ariaRole}`, score: kRoleWithoutNameScore };\n const ariaDescription = getElementAccessibleDescription(element, false);\n if (ariaDescription)\n candidates.push([{ engine: "internal:role", selector: `${ariaRole}[description=${escapeForAttributeSelector(ariaDescription, true)}]`, score: kRoleWithoutNameScore + 1 }]);\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 (isTargetNode && 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 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/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/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.description !== void 0)\n props.push(["description", escapeForAttributeSelector(options.description, !!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 || { mode: "default" });\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 if (!this._injectedScript.window.__pw_resume)\n return false;\n this._injectedScript.window.__pw_resume().catch(() => {\n });\n }\n};\n\n// packages/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}\nfunction isArrayBuffer(obj) {\n try {\n return obj instanceof ArrayBuffer || Object.prototype.toString.call(obj) === "[object ArrayBuffer]";\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 if ("ab" in value)\n return base64ToTypedArray(value.ab.b, Uint8Array).buffer;\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 if (isArrayBuffer(value))\n return { ab: { b: typedArrayToBase64(new Uint8Array(value)) } };\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 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 AbortSignal: global.AbortSignal\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 constructor(window, options) {\n this._testIdAttributeNameForStrictErrorAndConsoleCodegen = "data-testid";\n this._lastAriaSnapshotForTrack = /* @__PURE__ */ new Map();\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 generateAriaTree,\n findNewElement,\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("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 this._shouldPrependErrorPrefix = !!options.shouldPrependErrorPrefix;\n this._isUtilityWorld = !!options.isUtilityWorld;\n setGlobalOptions({ browserNameForWorkarounds: options.browserName });\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 this.checkDeprecatedSelectorUsage(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 return this.incrementalAriaSnapshot(node, options).full;\n }\n incrementalAriaSnapshot(node, options) {\n if (node.nodeType !== Node.ELEMENT_NODE)\n throw this.createStacklessError("Can only capture aria snapshot of Element nodes.");\n const ariaSnapshot = generateAriaTree(node, options);\n const rendered = renderAriaTree(ariaSnapshot, options);\n let incremental;\n if (options.track) {\n const previousSnapshot = this._lastAriaSnapshotForTrack.get(options.track);\n if (previousSnapshot)\n incremental = renderAriaTree(ariaSnapshot, options, previousSnapshot).text;\n this._lastAriaSnapshotForTrack.set(options.track, ariaSnapshot);\n }\n this._lastAriaSnapshotForQuery = ariaSnapshot;\n return { full: rendered.text, incremental, iframeRefs: ariaSnapshot.iframeRefs, iframeDepths: rendered.iframeDepths };\n }\n ariaSnapshotForRecorder() {\n const tree = generateAriaTree(this.document.body, { mode: "ai" });\n const { text: ariaSnapshot } = renderAriaTree(tree, { mode: "ai" });\n return { ariaSnapshot, refs: tree.refs };\n }\n getAllElementsMatchingExpectAriaTemplate(document, template) {\n return getAllElementsMatchingExpectAriaTemplate(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._lastAriaSnapshotForQuery) == 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
${escapeHTML(options2.description)}
` : ""; + const styleSheet = ` + @keyframes pw-chapter-fade-in { + from { opacity: 0; } + to { opacity: 1; } + } + @keyframes pw-chapter-fade-out { + from { opacity: 1; } + to { opacity: 0; } + } + #background { + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + backdrop-filter: blur(2px); + animation: pw-chapter-fade-in ${fadeDuration}ms ease-out forwards; + } + #background.fade-out { + animation: pw-chapter-fade-out ${fadeDuration}ms ease-in forwards; + } + #content { + background: rgba(0, 0, 0, 0.7); + border: 1px solid rgba(255, 255, 255, 0.15); + border-radius: 16px; + padding: 40px 56px; + max-width: 560px; + box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4); + } + #title { + color: white; + font-family: system-ui, -apple-system, sans-serif; + font-size: 28px; + font-weight: 600; + line-height: 1.3; + text-align: center; + letter-spacing: -0.01em; + } + #description { + color: rgba(255, 255, 255, 0.7); + font-family: system-ui, -apple-system, sans-serif; + font-size: 15px; + line-height: 1.5; + margin-top: 12px; + text-align: center; + } + `; + const duration = options2.duration ?? 2e3; + const html = `
${escapeHTML(options2.title)}
${descriptionHtml}
`; + const id = await this.show(html); + await new Promise((f) => setTimeout(f, duration)); + const utility = await this._page.mainFrame().utilityContext(); + await utility.evaluate(({ injected, id: id2, fadeDuration: fadeDuration2 }) => { + const overlay = injected.getUserOverlay(id2); + const bg = overlay?.querySelector("#background"); + if (bg) + bg.classList.add("fade-out"); + return new Promise((f) => injected.utils.builtins.setTimeout(f, fadeDuration2)); + }, { injected: await utility.injectedScript(), id, fadeDuration }).catch((e) => debugLogger.log("error", e)); + await this.remove(id); + } + async setVisible(visible) { + if (!this._overlays.size) + return; + const utility = await this._page.mainFrame().utilityContext(); + await utility.evaluate(({ injected, visible: visible2 }) => { + injected.setUserOverlaysVisible(visible2); + }, { injected: await utility.injectedScript(), visible }).catch((e) => debugLogger.log("error", e)); + } + }; + } +}); + +// packages/playwright-core/src/server/screencast.ts +var Screencast; +var init_screencast = __esm({ + "packages/playwright-core/src/server/screencast.ts"() { + "use strict"; + init_manualPromise(); + init_protocolFormatter(); + init_debugLogger(); + Screencast = class { + constructor(page) { + this._clients = /* @__PURE__ */ new Map(); + this.page = page; + this.page.instrumentation.addListener(this, page.browserContext); + } + async handlePageOrContextClose() { + const clients = [...this._clients.keys()]; + this._clients.clear(); + for (const client of clients) { + if (client.gracefulClose) + await client.gracefulClose(); + } + } + dispose() { + for (const client of this._clients.keys()) + client.dispose(); + this._clients.clear(); + this.page.instrumentation.removeListener(this); + } + showActions(options2) { + this._actions = options2; + } + hideActions() { + this._actions = void 0; + } + addClient(client) { + const isFirst = this._clients.size === 0; + this._clients.set(client, new ManualPromise()); + if (isFirst) { + this._startScreencast(client.size, client.quality); + } else if (this._lastFrame) { + const frame = this._lastFrame; + setTimeout(() => { + if (this._clients.has(client)) + void client.onFrame(frame); + }, 0); + } + return { size: this._size }; + } + removeClient(client) { + const disconnected = this._clients.get(client); + if (!disconnected) + return; + this._clients.delete(client); + disconnected.resolve(); + if (!this._clients.size) + this._stopScreencast(); + } + _startScreencast(size, quality) { + this._size = size; + if (!this._size) { + const viewport = this.page.browserContext._options.viewport || { width: 800, height: 600 }; + const scale = Math.min(1, 800 / Math.max(viewport.width, viewport.height)); + this._size = { + width: Math.floor(viewport.width * scale), + height: Math.floor(viewport.height * scale) + }; + } + this._size = { + width: this._size.width & ~1, + height: this._size.height & ~1 + }; + this.page.delegate.startScreencast({ + width: this._size.width, + height: this._size.height, + quality: quality ?? 90 + }); + } + _stopScreencast() { + this._lastFrame = void 0; + this.page.delegate.stopScreencast(); + } + onScreencastFrame(frame, ack) { + this._lastFrame = frame; + const asyncResults = []; + for (const [client, disconnected] of this._clients) { + const result2 = client.onFrame(frame); + if (!result2) + continue; + asyncResults.push(Promise.race([result2.catch(() => { + }), disconnected])); + } + if (ack) { + if (!asyncResults.length) + ack(); + else + Promise.race(asyncResults).then(ack); + } + } + async onBeforeCall(sdkObject, metadata, parentId) { + if (!this._actions) + return; + metadata.annotate = true; + } + async onBeforeInputAction(sdkObject, metadata) { + if (!this._actions) + return; + const page = sdkObject.attribution.page; + if (!page) + return; + const actionTitle2 = renderTitleForCall(metadata); + const utility = await page.mainFrame().utilityContext(); + await utility.evaluate(async (options2) => { + const { injected, duration } = options2; + injected.setScreencastAnnotation(options2); + await new Promise((f) => injected.utils.builtins.setTimeout(f, duration)); + injected.setScreencastAnnotation(null); + }, { + injected: await utility.injectedScript(), + duration: this._actions?.duration ?? 500, + point: metadata.point, + box: metadata.box, + actionTitle: actionTitle2, + position: this._actions?.position, + fontSize: this._actions?.fontSize + }).catch((e) => debugLogger.log("error", e)); + } + }; + } +}); + +// packages/playwright-core/src/server/page.ts +async function ariaSnapshotForFrame(progress2, frame, options2 = {}) { + const snapshot3 = await frame.retryWithProgressAndTimeouts(progress2, [1e3, 2e3, 4e3, 8e3], async (progress3, continuePolling) => { + try { + const context2 = await progress3.race(frame.utilityContext()); + const injectedScript = await progress3.race(context2.injectedScript()); + const snapshotOrRetry = await progress3.race(injectedScript.evaluate((injected, options3) => { + if (options3.info) { + const element2 = injected.querySelector(options3.info.parsed, injected.document, options3.info.strict); + if (!element2) + return false; + return injected.incrementalAriaSnapshot(element2, options3); + } + const node = injected.document.body; + if (!node) + return true; + return injected.incrementalAriaSnapshot(node, options3); + }, { + mode: options2.mode ?? "default", + refPrefix: frame.seq ? "f" + frame.seq : "", + track: options2.track, + doNotRenderActive: options2.doNotRenderActive, + info: options2.info, + depth: options2.depth, + boxes: options2.boxes + })); + if (snapshotOrRetry === true) + return continuePolling; + if (snapshotOrRetry === false) + throw new NonRecoverableDOMError(`Selector "${stringifySelector(options2.info.parsed)}" does not match any element`); + return snapshotOrRetry; + } catch (e) { + if (frame.isNonRetriableError(e)) + throw e; + return continuePolling; + } + }); + const renderedIframeRefs = snapshot3.iframeRefs.filter((ref) => ref in snapshot3.iframeDepths); + progress2.setAllowConcurrentOrNestedRaces(true); + const childSnapshotPromises = renderedIframeRefs.map((ref) => { + const iframeDepth = snapshot3.iframeDepths[ref]; + const childDepth = options2.depth ? options2.depth - iframeDepth - 1 : void 0; + return ariaSnapshotFrameRef(progress2, frame, ref, { ...options2, depth: childDepth }); + }); + const childSnapshots = await Promise.all(childSnapshotPromises); + progress2.setAllowConcurrentOrNestedRaces(false); + const full = []; + let incremental; + if (snapshot3.incremental !== void 0) { + incremental = snapshot3.incremental.split("\n"); + for (let i = 0; i < renderedIframeRefs.length; i++) { + const childSnapshot = childSnapshots[i]; + if (childSnapshot.incremental) + incremental.push(...childSnapshot.incremental); + else if (childSnapshot.full.length) + incremental.push("- iframe [ref=" + renderedIframeRefs[i] + "]:", ...childSnapshot.full.map((l) => " " + l)); + } + } + for (const line of snapshot3.full.split("\n")) { + const match = line.match(/^(\s*)- iframe (?:\[active\] )?\[ref=([^\]]*)\]/); + if (!match) { + full.push(line); + continue; + } + const leadingSpace = match[1]; + const ref = match[2]; + const childSnapshot = childSnapshots[renderedIframeRefs.indexOf(ref)] ?? { full: [] }; + full.push(childSnapshot.full.length ? line + ":" : line); + full.push(...childSnapshot.full.map((l) => leadingSpace + " " + l)); + } + return { full, incremental }; +} +async function ariaSnapshotFrameRef(progress2, parentFrame, frameRef, options2) { + const frameSelector = `aria-ref=${frameRef} >> internal:control=enter-frame`; + const frameBodySelector = `${frameSelector} >> body`; + const child = await progress2.race(parentFrame.selectors.resolveFrameForSelector(frameBodySelector, { strict: true })); + if (!child) + return { full: [] }; + try { + return await ariaSnapshotForFrame(progress2, child.frame, { ...options2, info: void 0 }); + } catch { + return { full: [] }; + } +} +function ensureArrayLimit(array, limit) { + if (array.length > limit) + return array.splice(0, limit / 10); + return []; +} +var PageEvent, navigationMarkSymbol, Page, WorkerEvent, Worker, PageBinding, InitScript; +var init_page = __esm({ + "packages/playwright-core/src/server/page.ts"() { + "use strict"; + init_selectorParser(); + init_manualPromise(); + init_utilityScriptSerializers(); + init_comparators(); + init_debugLogger(); + init_manualPromise(); + init_assert(); + init_protocolFormatter(); + init_stringUtils(); + init_locatorGenerators(); + init_browserContext(); + init_disposable2(); + init_console(); + init_errors(); + init_fileChooser(); + init_frames(); + init_helper(); + init_input(); + init_instrumentation(); + init_javascript(); + init_screenshotter(); + init_callLog(); + init_bindingsControllerSource(); + init_overlay(); + init_dom(); + init_screencast(); + PageEvent = { + Close: "close", + Crash: "crash", + Download: "download", + EmulatedSizeChanged: "emulatedsizechanged", + FileChooser: "filechooser", + FrameAttached: "frameattached", + FrameDetached: "framedetached", + InternalFrameNavigatedToNewDocument: "internalframenavigatedtonewdocument", + LocatorHandlerTriggered: "locatorhandlertriggered", + WebSocket: "websocket", + Worker: "worker" + }; + navigationMarkSymbol = Symbol("navigationMark"); + Page = class _Page extends SdkObject { + constructor(delegate, browserContext) { + super(browserContext, "page"); + this._closedState = "open"; + this.closedPromise = new ManualPromise(); + this._initializedPromise = new ManualPromise(); + this._consoleMessages = []; + this._pageErrors = []; + this._crashed = false; + this.openScope = new LongStandingScope(); + this._emulatedMedia = {}; + this._fileChooserInterceptedBy = /* @__PURE__ */ new Set(); + this._pageBindings = /* @__PURE__ */ new Map(); + this.initScripts = []; + this._workers = /* @__PURE__ */ new Map(); + this.requestInterceptors = []; + this._locatorHandlers = /* @__PURE__ */ new Map(); + this._lastLocatorHandlerUid = 0; + this._locatorHandlerRunningCounter = 0; + this._networkRequests = []; + this.attribution.page = this; + this.delegate = delegate; + this.browserContext = browserContext; + this.keyboard = new Keyboard(delegate.rawKeyboard, this); + this.mouse = new Mouse(delegate.rawMouse, this); + this.touchscreen = new Touchscreen(delegate.rawTouchscreen, this); + this.screenshotter = new Screenshotter(this); + this.frameManager = new FrameManager(this); + this.overlay = new Overlay(this); + this.screencast = new Screencast(this); + if (delegate.pdf) + this.pdf = delegate.pdf.bind(delegate); + this.coverage = delegate.coverage ? delegate.coverage() : null; + this.isStorageStatePage = browserContext.isCreatingStorageStatePage(); + } + static { + this.Events = PageEvent; + } + async reportAsNew(opener, error) { + if (opener) { + const openerPageOrError = await opener.waitForInitializedOrError(); + if (openerPageOrError instanceof _Page && !openerPageOrError.isClosed()) + this._opener = openerPageOrError; + } + this._markInitialized(error); + } + _markInitialized(error = void 0) { + if (error) { + if (this.browserContext.isClosingOrClosed()) + return; + this.frameManager.createDummyMainFrameIfNeeded(); + } + this._initialized = error || this; + this.emitOnContext(BrowserContext.Events.Page, this); + for (const pageError of this._pageErrors) + this.emitOnContext(BrowserContext.Events.PageError, pageError, this); + for (const message of this._consoleMessages) + this.emitOnContext(BrowserContext.Events.Console, message); + if (this.isClosed()) + this.emit(_Page.Events.Close); + else + this.instrumentation.onPageOpen(this); + this._initializedPromise.resolve(this._initialized); + } + initializedOrUndefined() { + return this._initialized ? this : void 0; + } + waitForInitializedOrError() { + return this._initializedPromise; + } + emitOnContext(event, ...args) { + if (this.isStorageStatePage) + return; + this.browserContext.emit(event, ...args); + } + async resetForReuse(progress2) { + await this.mainFrame().gotoImpl(progress2, "about:blank", {}); + this._emulatedSize = void 0; + this._emulatedMedia = {}; + this._extraHTTPHeaders = void 0; + await progress2.race(Promise.all([ + this.delegate.updateEmulatedViewportSize(), + this.delegate.updateEmulateMedia(), + this.delegate.updateExtraHTTPHeaders() + ])); + await this.delegate.resetForReuse(progress2); + } + _didClose() { + this.frameManager.dispose(); + this.screencast.dispose(); + this.overlay.dispose(); + assert(this._closedState !== "closed", "Page closed twice"); + this._closedState = "closed"; + this.emit(_Page.Events.Close); + this.browserContext.emit(BrowserContext.Events.PageClosed, this); + this.closedPromise.resolve(); + this.instrumentation.onPageClose(this); + this.openScope.close(new TargetClosedError(this.closeReason())); + } + _didCrash() { + this.frameManager.dispose(); + this.screencast.dispose(); + this.overlay.dispose(); + this.emit(_Page.Events.Crash); + this._crashed = true; + this.instrumentation.onPageClose(this); + this.openScope.close(new Error("Page crashed")); + } + async _onFileChooserOpened(handle) { + let multiple; + try { + multiple = await handle.evaluate((element2) => !!element2.multiple); + } catch (e) { + return; + } + if (!this.listenerCount(_Page.Events.FileChooser)) { + handle.dispose(); + return; + } + const fileChooser = new FileChooser(handle, multiple); + this.emit(_Page.Events.FileChooser, fileChooser); + } + opener() { + return this._opener; + } + mainFrame() { + return this.frameManager.mainFrame(); + } + frames() { + return this.frameManager.frames(); + } + async exposeBinding(progress2, name, playwrightBinding) { + if (this._pageBindings.has(name)) + throw new Error(`Function "${name}" has been already registered`); + if (this.browserContext._pageBindings.has(name)) + throw new Error(`Function "${name}" has been already registered in the browser context`); + await progress2.race(this.browserContext.exposePlaywrightBindingIfNeeded()); + const binding = new PageBinding(this, name, playwrightBinding); + this._pageBindings.set(name, binding); + try { + await progress2.race(this.delegate.addInitScript(binding.initScript)); + await progress2.race(this.safeNonStallingEvaluateInAllFrames(binding.initScript.source, "main")); + return binding; + } catch (error) { + this._pageBindings.delete(name); + throw error; + } + } + async removeExposedBinding(binding) { + if (this._pageBindings.get(binding.name) !== binding) + return; + this._pageBindings.delete(binding.name); + await this.delegate.removeInitScripts([binding.initScript]); + const cleanup = `{ ${binding.cleanupScript} };`; + await this.safeNonStallingEvaluateInAllFrames(cleanup, "main"); + } + async setExtraHTTPHeaders(progress2, headers) { + const oldHeaders = this._extraHTTPHeaders; + try { + this._extraHTTPHeaders = headers; + await progress2.race(this.delegate.updateExtraHTTPHeaders()); + } catch (error) { + this._extraHTTPHeaders = oldHeaders; + this.delegate.updateExtraHTTPHeaders().catch(() => { + }); + throw error; + } + } + extraHTTPHeaders() { + return this._extraHTTPHeaders; + } + addNetworkRequest(request2) { + this._networkRequests.push(request2); + ensureArrayLimit(this._networkRequests, 100); + } + networkRequests() { + return this._networkRequests; + } + async onBindingCalled(payload, context2) { + if (this._closedState === "closed") + return; + await PageBinding.dispatch(this, payload, context2); + } + addConsoleMessage(worker, type3, args, location2, text2, timestamp) { + const message = new ConsoleMessage(this, worker, type3, text2, args, location2, timestamp); + const intercepted = this.frameManager.interceptConsoleMessage(message); + if (intercepted) { + args.forEach((arg) => arg.dispose()); + return; + } + this._consoleMessages.push(message); + ensureArrayLimit(this._consoleMessages, 200); + if (this._initialized) + this.emitOnContext(BrowserContext.Events.Console, message); + } + clearConsoleMessages() { + this._consoleMessages.length = 0; + } + consoleMessages(filter) { + if (filter === "all") + return this._consoleMessages; + const marked = this._consoleMessages.findLastIndex((m) => m[navigationMarkSymbol]); + return marked === -1 ? this._consoleMessages : this._consoleMessages.slice(marked + 1); + } + addPageError(error, location2) { + const pageError = { error, location: location2 }; + this._pageErrors.push(pageError); + ensureArrayLimit(this._pageErrors, 200); + if (this._initialized) + this.emitOnContext(BrowserContext.Events.PageError, pageError, this); + } + clearPageErrors() { + this._pageErrors.length = 0; + } + pageErrors(filter) { + if (filter === "all") + return this._pageErrors.map((e) => e.error); + const marked = this._pageErrors.findLastIndex((e) => e[navigationMarkSymbol]); + return (marked === -1 ? this._pageErrors : this._pageErrors.slice(marked + 1)).map((e) => e.error); + } + async reload(progress2, options2) { + return this.mainFrame().raceNavigationAction(progress2, async () => { + const [response2] = await Promise.all([ + // Reload must be a new document, and should not be confused with a stray pushState. + this.mainFrame().waitForNavigation(progress2, true, options2), + progress2.race(this.delegate.reload()) + ]); + return response2; + }); + } + async goBack(progress2, options2) { + return this.mainFrame().raceNavigationAction(progress2, async () => { + let error; + const waitPromise = this.mainFrame().waitForNavigation(progress2, false, options2).catch((e) => { + error = e; + return null; + }); + const result2 = await progress2.race(this.delegate.goBack()); + if (!result2) { + waitPromise.catch(() => { + }); + return null; + } + const response2 = await waitPromise; + if (error) + throw error; + return response2; + }); + } + async goForward(progress2, options2) { + return this.mainFrame().raceNavigationAction(progress2, async () => { + let error; + const waitPromise = this.mainFrame().waitForNavigation(progress2, false, options2).catch((e) => { + error = e; + return null; + }); + const result2 = await progress2.race(this.delegate.goForward()); + if (!result2) { + waitPromise.catch(() => { + }); + return null; + } + const response2 = await waitPromise; + if (error) + throw error; + return response2; + }); + } + requestGC(progress2) { + return progress2.race(this.delegate.requestGC()); + } + registerLocatorHandler(selector, noWaitAfter) { + const uid = ++this._lastLocatorHandlerUid; + this._locatorHandlers.set(uid, { selector, noWaitAfter }); + return uid; + } + resolveLocatorHandler(uid, remove) { + const handler = this._locatorHandlers.get(uid); + if (remove) + this._locatorHandlers.delete(uid); + if (handler) { + handler.resolved?.resolve(); + handler.resolved = void 0; + } + } + unregisterLocatorHandler(uid) { + this._locatorHandlers.delete(uid); + } + async performActionPreChecks(progress2) { + await this._performWaitForNavigationCheck(progress2); + await this._performLocatorHandlersCheckpoint(progress2); + await this._performWaitForNavigationCheck(progress2); + } + async _performWaitForNavigationCheck(progress2) { + if (process.env.PLAYWRIGHT_SKIP_NAVIGATION_CHECK) + return; + const mainFrame = this.frameManager.mainFrame(); + if (!mainFrame || !mainFrame.pendingDocument()) + return; + const url2 = mainFrame.pendingDocument()?.request?.url(); + const toUrl = url2 ? `" ${trimStringWithEllipsis(url2, 200)}"` : ""; + progress2.log(` waiting for${toUrl} navigation to finish...`); + await helper.waitForEvent(progress2, mainFrame, Frame.Events.InternalNavigation, (e) => { + if (!e.isPublic) + return false; + if (!e.error) + progress2.log(` navigated to "${trimStringWithEllipsis(mainFrame.url(), 200)}"`); + return true; + }).promise; + } + async _performLocatorHandlersCheckpoint(progress2) { + if (this._locatorHandlerRunningCounter) + return; + for (const [uid, handler] of this._locatorHandlers) { + if (!handler.resolved) { + if (await this.mainFrame().isVisibleInternal(progress2, handler.selector, { strict: true })) { + handler.resolved = new ManualPromise(); + this.emit(_Page.Events.LocatorHandlerTriggered, uid); + } + } + if (handler.resolved) { + ++this._locatorHandlerRunningCounter; + progress2.log(` found ${asLocator(this.browserContext._browser.sdkLanguage(), handler.selector)}, intercepting action to run the handler`); + const promise = handler.resolved.then(async () => { + if (!handler.noWaitAfter) { + progress2.log(` locator handler has finished, waiting for ${asLocator(this.browserContext._browser.sdkLanguage(), handler.selector)} to be hidden`); + await this.mainFrame().waitForSelector(progress2, handler.selector, false, { state: "hidden" }); + } else { + progress2.log(` locator handler has finished`); + } + }); + try { + progress2.setAllowConcurrentOrNestedRaces(true); + await progress2.race(this.openScope.race(promise)); + } finally { + progress2.setAllowConcurrentOrNestedRaces(false); + --this._locatorHandlerRunningCounter; + } + progress2.log(` interception handler has finished, continuing`); + } + } + } + async emulateMedia(progress2, options2) { + const oldEmulatedMedia = { ...this._emulatedMedia }; + if (options2.media !== void 0) + this._emulatedMedia.media = options2.media; + if (options2.colorScheme !== void 0) + this._emulatedMedia.colorScheme = options2.colorScheme; + if (options2.reducedMotion !== void 0) + this._emulatedMedia.reducedMotion = options2.reducedMotion; + if (options2.forcedColors !== void 0) + this._emulatedMedia.forcedColors = options2.forcedColors; + if (options2.contrast !== void 0) + this._emulatedMedia.contrast = options2.contrast; + try { + await progress2.race(this.delegate.updateEmulateMedia()); + } catch (error) { + this._emulatedMedia = oldEmulatedMedia; + this.delegate.updateEmulateMedia().catch(() => { + }); + throw error; + } + } + emulatedMedia() { + const contextOptions = this.browserContext._options; + return { + media: this._emulatedMedia.media || "no-override", + colorScheme: this._emulatedMedia.colorScheme !== void 0 ? this._emulatedMedia.colorScheme : contextOptions.colorScheme ?? "light", + reducedMotion: this._emulatedMedia.reducedMotion !== void 0 ? this._emulatedMedia.reducedMotion : contextOptions.reducedMotion ?? "no-preference", + forcedColors: this._emulatedMedia.forcedColors !== void 0 ? this._emulatedMedia.forcedColors : contextOptions.forcedColors ?? "none", + contrast: this._emulatedMedia.contrast !== void 0 ? this._emulatedMedia.contrast : contextOptions.contrast ?? "no-preference" + }; + } + async setViewportSize(progress2, viewportSize) { + const oldEmulatedSize = this._emulatedSize; + try { + this._setEmulatedSize({ viewport: { ...viewportSize }, screen: { ...viewportSize } }); + await progress2.race(this.delegate.updateEmulatedViewportSize()); + } catch (error) { + this._emulatedSize = oldEmulatedSize; + this.delegate.updateEmulatedViewportSize().catch(() => { + }); + throw error; + } + } + setEmulatedSizeFromWindowOpen(emulatedSize) { + this._setEmulatedSize(emulatedSize); + } + _setEmulatedSize(emulatedSize) { + this._emulatedSize = emulatedSize; + this.emit(_Page.Events.EmulatedSizeChanged); + } + emulatedSize() { + if (this._emulatedSize) + return this._emulatedSize; + const contextOptions = this.browserContext._options; + return contextOptions.viewport ? { viewport: contextOptions.viewport, screen: contextOptions.screen || contextOptions.viewport } : void 0; + } + async bringToFront(progress2) { + await progress2.race(this.delegate.bringToFront()); + } + async addInitScript(progress2, source8) { + return await progress2.race(this._addInitScript(source8)); + } + async _addInitScript(source8) { + const initScript = new InitScript(this, source8); + this.initScripts.push(initScript); + try { + await this.delegate.addInitScript(initScript); + } catch (error) { + initScript.dispose().catch(() => { + }); + throw error; + } + return initScript; + } + async removeInitScript(initScript) { + this.initScripts = this.initScripts.filter((script) => initScript !== script); + await this.delegate.removeInitScripts([initScript]); + } + needsRequestInterception() { + return this.requestInterceptors.length > 0 || this.browserContext.requestInterceptors.length > 0; + } + async addRequestInterceptor(progress2, handler, prepend) { + if (prepend) + this.requestInterceptors.unshift(handler); + else + this.requestInterceptors.push(handler); + await progress2.race(this.delegate.updateRequestInterception()); + } + async removeRequestInterceptor(handler) { + const index = this.requestInterceptors.indexOf(handler); + if (index === -1) + return; + this.requestInterceptors.splice(index, 1); + await this.browserContext.notifyRoutesInFlightAboutRemovedHandler(handler); + await this.delegate.updateRequestInterception(); + } + async expectScreenshot(progress2, options2) { + const locator2 = options2.locator; + const rafrafScreenshot = locator2 ? async (progress3, timeout) => { + return await locator2.frame.rafrafTimeoutScreenshotElementWithProgress(progress3, locator2.selector, timeout, options2 || {}); + } : async (progress3, timeout) => { + await this.performActionPreChecks(progress3); + await this.mainFrame().rafrafTimeout(progress3, timeout); + return await this.screenshotter.screenshotPage(progress3, options2 || {}); + }; + const comparator = getComparator("image/png"); + if (!options2.expected && options2.isNot) + return { errorMessage: '"not" matcher requires expected result' }; + try { + const format2 = validateScreenshotOptions(options2 || {}); + if (format2 !== "png") + throw new Error("Only PNG screenshots are supported"); + } catch (error) { + return { errorMessage: error.message }; + } + let intermediateResult; + const areEqualScreenshots = (actual, expected, previous) => { + const comparatorResult = actual && expected ? comparator(actual, expected, options2) : void 0; + if (comparatorResult !== void 0 && !!comparatorResult === !!options2.isNot) + return true; + if (comparatorResult) + intermediateResult = { errorMessage: comparatorResult.errorMessage, diff: comparatorResult.diff, actual, previous }; + return false; + }; + try { + let actual; + let previous; + const pollIntervals = [0, 100, 250, 500]; + progress2.log(`${renderTitleForCall(progress2.metadata)}${options2.timeout ? ` with timeout ${options2.timeout}ms` : ""}`); + if (options2.expected) + progress2.log(` verifying given screenshot expectation`); + else + progress2.log(` generating new stable screenshot expectation`); + let isFirstIteration = true; + while (true) { + if (this.isClosed()) + throw new Error("The page has closed"); + const screenshotTimeout = pollIntervals.shift() ?? 1e3; + if (screenshotTimeout) + progress2.log(`waiting ${screenshotTimeout}ms before taking screenshot`); + previous = actual; + actual = await rafrafScreenshot(progress2, screenshotTimeout).catch((e) => { + if (this.mainFrame().isNonRetriableError(e)) + throw e; + progress2.log(`failed to take screenshot - ` + e.message); + return void 0; + }); + if (!actual) + continue; + const expectation = options2.expected && isFirstIteration ? options2.expected : previous; + if (areEqualScreenshots(actual, expectation, previous)) + break; + if (intermediateResult) + progress2.log(intermediateResult.errorMessage); + isFirstIteration = false; + } + if (!isFirstIteration) + progress2.log(`captured a stable screenshot`); + if (!options2.expected) + return { actual }; + if (isFirstIteration) { + progress2.log(`screenshot matched expectation`); + return {}; + } + if (areEqualScreenshots(actual, options2.expected, void 0)) { + progress2.log(`screenshot matched expectation`); + return {}; + } + throw new Error(intermediateResult.errorMessage); + } catch (e) { + if (isJavaScriptErrorInEvaluate(e) || isInvalidSelectorError(e)) + throw e; + let errorMessage = e.message; + if (e instanceof TimeoutError && intermediateResult?.previous) + errorMessage = `Failed to take two consecutive stable screenshots.`; + return { + log: compressCallLog(e.message ? [...progress2.metadata.log, e.message] : progress2.metadata.log), + ...intermediateResult, + errorMessage, + timedOut: e instanceof TimeoutError + }; + } + } + async screenshot(progress2, options2) { + return await this.screenshotter.screenshotPage(progress2, options2); + } + async close(progress2, options2 = {}) { + await progress2.race(this._close(options2)); + } + async _close(options2 = {}) { + if (this._closedState === "closed") + return; + if (options2.reason) + this._closeReason = options2.reason; + const runBeforeUnload = !!options2.runBeforeUnload; + if (!runBeforeUnload) + await this.screencast.handlePageOrContextClose(); + if (this._closedState !== "closing") { + if (!runBeforeUnload) + this._closedState = "closing"; + await this.delegate.closePage(runBeforeUnload).catch((e) => debugLogger.log("error", e)); + } + if (!runBeforeUnload) + await this.closedPromise; + } + isClosed() { + return this._closedState === "closed"; + } + hasCrashed() { + return this._crashed; + } + isClosedOrClosingOrCrashed() { + return this._closedState !== "open" || this._crashed; + } + addWorker(workerId, worker) { + this._workers.set(workerId, worker); + this.emit(_Page.Events.Worker, worker); + } + removeWorker(workerId) { + const worker = this._workers.get(workerId); + if (!worker) + return; + worker.didClose(); + this._workers.delete(workerId); + } + clearWorkers() { + for (const [workerId, worker] of this._workers) { + worker.didClose(); + this._workers.delete(workerId); + } + } + async setFileChooserInterceptedBy(progress2, enabled, by) { + await progress2.race(this._setFileChooserInterceptedBy(enabled, by)); + } + async _setFileChooserInterceptedBy(enabled, by) { + const wasIntercepted = this.fileChooserIntercepted(); + if (enabled) + this._fileChooserInterceptedBy.add(by); + else + this._fileChooserInterceptedBy.delete(by); + if (wasIntercepted !== this.fileChooserIntercepted()) + await this.delegate.updateFileChooserInterception(); + } + fileChooserIntercepted() { + return this._fileChooserInterceptedBy.size > 0; + } + frameNavigatedToNewDocument(frame) { + this.emit(_Page.Events.InternalFrameNavigatedToNewDocument, frame); + this.browserContext.emit(BrowserContext.Events.InternalFrameNavigatedToNewDocument, frame, this); + const origin = frame.origin(); + if (origin) + this.browserContext.addVisitedOrigin(origin); + if (frame === this.mainFrame()) { + if (this._consoleMessages.length > 0) + this._consoleMessages[this._consoleMessages.length - 1][navigationMarkSymbol] = true; + if (this._pageErrors.length > 0) + this._pageErrors[this._pageErrors.length - 1][navigationMarkSymbol] = true; + } + } + allInitScripts() { + const bindings = [...this.browserContext._pageBindings.values(), ...this._pageBindings.values()].map((binding) => binding.initScript); + if (this.browserContext.bindingsInitScript) + bindings.unshift(this.browserContext.bindingsInitScript); + return [...bindings, ...this.browserContext.initScripts, ...this.initScripts]; + } + getBinding(name) { + return this._pageBindings.get(name) || this.browserContext._pageBindings.get(name); + } + async safeNonStallingEvaluateInAllFrames(expression2, world, options2 = {}) { + await Promise.all(this.frames().map(async (frame) => { + try { + await frame.nonStallingEvaluateInExistingContext(expression2, world); + } catch (e) { + if (options2.throwOnJSErrors && isJavaScriptErrorInEvaluate(e)) + throw e; + } + })); + } + async hideHighlight() { + await Promise.all(this.frames().map((frame) => frame.hideHighlight().catch(() => { + }))); + } + async setDockTile(image) { + await this.delegate.setDockTile(image); + } + }; + WorkerEvent = { + Console: "console", + Close: "close" + }; + Worker = class _Worker extends SdkObject { + constructor(parent, url2, onDisconnect) { + super(parent, "worker"); + this._executionContextPromise = new ManualPromise(); + this._workerScriptLoaded = false; + this.existingExecutionContext = null; + this.openScope = new LongStandingScope(); + this.attribution.worker = this; + this.url = url2; + this._onDisconnect = onDisconnect; + } + static { + this.Events = WorkerEvent; + } + createExecutionContext(delegate) { + this.existingExecutionContext = new ExecutionContext(this, delegate, "worker"); + if (this._workerScriptLoaded) + this._executionContextPromise.resolve(this.existingExecutionContext); + return this.existingExecutionContext; + } + destroyExecutionContext(errorMessage) { + if (this.existingExecutionContext) + this.existingExecutionContext.contextDestroyed(errorMessage); + this.existingExecutionContext = null; + this._workerScriptLoaded = false; + this._executionContextPromise = new ManualPromise(); + } + workerScriptLoaded() { + this._workerScriptLoaded = true; + if (this.existingExecutionContext) + this._executionContextPromise.resolve(this.existingExecutionContext); + } + didClose() { + if (this.existingExecutionContext) + this.existingExecutionContext.contextDestroyed("Worker was closed"); + this.emit(_Worker.Events.Close, this); + this.openScope.close(new Error("Worker closed")); + } + async evaluateExpression(progress2, expression2, isFunction2, arg) { + return progress2.race(evaluateExpression(await this._executionContextPromise, expression2, { returnByValue: true, isFunction: isFunction2 }, arg)); + } + async evaluateExpressionHandle(progress2, expression2, isFunction2, arg) { + return progress2.race(evaluateExpression(await this._executionContextPromise, expression2, { returnByValue: false, isFunction: isFunction2 }, arg)); + } + async disconnect(progress2, options2 = {}) { + if (!this._onDisconnect) + throw new Error("Cannot disconnect from this worker"); + this._closeReason = options2.reason; + await progress2.race(this._onDisconnect()); + } + }; + PageBinding = class _PageBinding extends DisposableObject { + static { + this.kController = "__playwright__binding__controller__"; + } + static { + this.kBindingName = "__playwright__binding__"; + } + static createInitScript(browserContext) { + return new InitScript(browserContext, ` + (() => { + const module = {}; + ${source4} + const property = '${_PageBinding.kController}'; + if (!globalThis[property]) + globalThis[property] = new (module.exports.BindingsController())(globalThis, '${_PageBinding.kBindingName}'); + })(); + `); + } + constructor(parent, name, playwrightFunction) { + super(parent); + this.name = name; + this.playwrightFunction = playwrightFunction; + this.initScript = new InitScript(parent, `globalThis['${_PageBinding.kController}'].addBinding(${JSON.stringify(name)})`); + this.cleanupScript = `globalThis['${_PageBinding.kController}'].removeBinding(${JSON.stringify(name)})`; + } + static async dispatch(page, payload, context2) { + const { name, seq, serializedArgs } = JSON.parse(payload); + try { + assert(context2.world); + const binding = page.getBinding(name); + if (!binding) + throw new Error(`Function "${name}" is not exposed`); + if (!Array.isArray(serializedArgs)) + throw new Error(`serializedArgs is not an array. This can happen when Array.prototype.toJSON is defined incorrectly`); + const args = serializedArgs.map((a) => parseEvaluationResultValue(a)); + const result2 = await binding.playwrightFunction({ frame: context2.frame, page, context: page.browserContext }, ...args); + context2.evaluateExpressionHandle(`arg => globalThis['${_PageBinding.kController}'].deliverBindingResult(arg)`, { isFunction: true }, { name, seq, result: result2 }).catch((e) => debugLogger.log("error", e)); + } catch (error) { + context2.evaluateExpressionHandle(`arg => globalThis['${_PageBinding.kController}'].deliverBindingResult(arg)`, { isFunction: true }, { name, seq, error }).catch((e) => debugLogger.log("error", e)); + } + } + async dispose() { + await this.parent.removeExposedBinding(this); + } + }; + InitScript = class extends DisposableObject { + constructor(owner, source8) { + super(owner); + this.source = `(() => { + ${source8} + })();`; + } + async dispose() { + await this.parent.removeInitScript(this); + } + }; + } +}); + +// packages/playwright-core/src/server/trace/recorder/snapshotter.ts +var mime5, Snapshotter, kNeedsResetSymbol; +var init_snapshotter = __esm({ + "packages/playwright-core/src/server/trace/recorder/snapshotter.ts"() { + "use strict"; + init_time(); + init_crypto(); + init_debugLogger(); + init_eventsHelper(); + init_snapshotterInjected(); + init_browserContext(); + init_page(); + init_progress(); + mime5 = require("./utilsBundle").mime; + Snapshotter = class { + constructor(context2, delegate) { + this._eventListeners = []; + this._started = false; + this._context = context2; + this._delegate = delegate; + const guid = createGuid(); + this._snapshotStreamer = "__playwright_snapshot_streamer_" + guid; + } + started() { + return this._started; + } + async start(progress2) { + this._started = true; + if (!this._initScript) + await this._initialize(progress2); + await progress2.race(this.reset()); + } + async reset() { + if (this._started) + await this._context.safeNonStallingEvaluateInAllFrames(`window["${this._snapshotStreamer}"].reset()`, "main"); + } + stop() { + this._started = false; + } + async resetForReuse() { + if (this._initScript) { + eventsHelper.removeEventListeners(this._eventListeners); + await this._initScript.dispose(); + this._initScript = void 0; + } + } + async _initialize(progress2) { + for (const page of this._context.pages()) + this._onPage(page); + this._eventListeners = [ + eventsHelper.addEventListener(this._context, BrowserContext.Events.Page, this._onPage.bind(this)) + ]; + const { javaScriptEnabled } = this._context._options; + const initScriptSource = `(${frameSnapshotStreamer})("${this._snapshotStreamer}", ${javaScriptEnabled || javaScriptEnabled === void 0})`; + this._initScript = await this._context.addInitScript(progress2, initScriptSource); + await progress2.race(this._context.safeNonStallingEvaluateInAllFrames(initScriptSource, "main")); + } + dispose() { + eventsHelper.removeEventListeners(this._eventListeners); + } + async _captureFrameSnapshot(frame) { + const needsReset = !!frame[kNeedsResetSymbol]; + frame[kNeedsResetSymbol] = false; + const expression2 = `window["${this._snapshotStreamer}"].captureSnapshot(${needsReset ? "true" : "false"})`; + try { + return await frame.nonStallingRawEvaluateInExistingMainContext(expression2); + } catch (e) { + frame[kNeedsResetSymbol] = true; + debugLogger.log("error", e); + } + } + async captureSnapshot(page, callId, snapshotName) { + const snapshots = page.frames().map(async (frame) => { + const data = await this._captureFrameSnapshot(frame); + if (!data || !this._started) + return; + const snapshot3 = { + callId, + snapshotName, + pageId: page.guid, + frameId: frame.guid, + frameUrl: data.url, + doctype: data.doctype, + html: data.html, + viewport: data.viewport, + timestamp: monotonicTime(), + wallTime: data.wallTime, + collectionTime: data.collectionTime, + resourceOverrides: [], + isMainFrame: page.mainFrame() === frame + }; + for (const { url: url2, content, contentType } of data.resourceOverrides) { + if (typeof content === "string") { + const buffer = Buffer.from(content); + const sha1 = calculateSha1(buffer) + "." + (mime5.getExtension(contentType) || "dat"); + this._delegate.onSnapshotterBlob({ sha1, buffer }); + snapshot3.resourceOverrides.push({ url: url2, sha1 }); + } else { + snapshot3.resourceOverrides.push({ url: url2, ref: content }); + } + } + this._delegate.onFrameSnapshot(snapshot3); + }); + await Promise.all(snapshots); + } + _onPage(page) { + for (const frame of page.frames()) + this._annotateFrameHierarchy(frame); + this._eventListeners.push(eventsHelper.addEventListener(page, Page.Events.FrameAttached, (frame) => this._annotateFrameHierarchy(frame))); + } + _annotateFrameHierarchy(frame) { + (async () => { + const frameElement = await frame.frameElement(nullProgress); + const parent = frame.parentFrame(); + if (!parent) + return; + const context2 = await parent.mainContext(); + await context2?.evaluate(({ snapshotStreamer, frameElement: frameElement2, frameId }) => { + window[snapshotStreamer].markIframe(frameElement2, frameId); + }, { snapshotStreamer: this._snapshotStreamer, frameElement, frameId: frame.guid }); + frameElement.dispose(); + })().catch(() => { + }); + } + }; + kNeedsResetSymbol = Symbol("kNeedsReset"); + } +}); + +// packages/playwright-core/src/server/artifact.ts +var import_fs14, Artifact; +var init_artifact = __esm({ + "packages/playwright-core/src/server/artifact.ts"() { + "use strict"; + import_fs14 = __toESM(require("fs")); + init_manualPromise(); + init_assert(); + init_errors(); + init_instrumentation(); + Artifact = class 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; + } + async localPathAfterFinished(progress2) { + return await progress2.race(this._localPathAfterFinished()); + } + async failureError(progress2) { + return await progress2.race(this._failureError()); + } + async cancel(progress2) { + return await progress2.race(this._cancel()); + } + async delete(progress2) { + return await progress2.race(this._delete()); + } + localPath() { + return this._localPath; + } + async _localPathAfterFinished() { + if (this._unaccessibleErrorMessage) + throw new Error(this._unaccessibleErrorMessage); + await this._finishedPromise; + if (this._failureErrorValue) + throw this._failureErrorValue; + return this._localPath; + } + saveAs(progress2, saveCallback) { + if (this._unaccessibleErrorMessage) + throw new Error(this._unaccessibleErrorMessage); + if (this._deleted) + throw new Error(`File already deleted. Save before deleting.`); + if (this._failureErrorValue) + throw this._failureErrorValue; + if (this._finished) { + saveCallback(this._localPath).catch(() => { + }); + return; + } + this._saveCallbacks.push(saveCallback); + } + async _failureError() { + if (this._unaccessibleErrorMessage) + return this._unaccessibleErrorMessage; + await this._finishedPromise; + return this._failureErrorValue?.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 import_fs14.default.promises.unlink(fileName).catch((e) => { + }); + } + async deleteOnContextClose() { + if (this._deleted) + return; + this._deleted = true; + if (!this._unaccessibleErrorMessage) + await import_fs14.default.promises.unlink(this._localPath).catch((e) => { + }); + await this.reportFinished(new TargetClosedError(this.closeReason())); + } + async reportFinished(error) { + if (this._finished) + return; + this._finished = true; + this._failureErrorValue = error; + if (error) { + for (const callback of this._saveCallbacks) + await callback("", error); + } else { + for (const callback of this._saveCallbacks) + await callback(this._localPath); + } + this._saveCallbacks = []; + this._finishedPromise.resolve(); + } + }; + } +}); + +// packages/playwright-core/src/protocol/validatorPrimitives.ts +function findValidator(type3, method, kind) { + const validator = maybeFindValidator(type3, method, kind); + if (!validator) + throw new ValidationError(`Unknown scheme for ${kind}: ${type3}.${method}`); + return validator; +} +function maybeFindValidator(type3, method, kind) { + const schemeName = type3 + (kind === "Initializer" ? "" : method[0].toUpperCase() + method.substring(1)) + kind; + return scheme[schemeName]; +} +function createMetadataValidator() { + return tOptional(scheme["Metadata"]); +} +var ValidationError, scheme, tFloat, tInt, tBoolean, tString, tBinary, tAny, tOptional, tArray, tObject, tEnum, tChannel, tType; +var init_validatorPrimitives = __esm({ + "packages/playwright-core/src/protocol/validatorPrimitives.ts"() { + "use strict"; + ValidationError = class extends Error { + }; + scheme = {}; + tFloat = (arg, path59, context2) => { + if (arg instanceof Number) + return arg.valueOf(); + if (typeof arg === "number") + return arg; + throw new ValidationError(`${path59}: expected float, got ${typeof arg}`); + }; + tInt = (arg, path59, context2) => { + let value2; + if (arg instanceof Number) + value2 = arg.valueOf(); + else if (typeof arg === "number") + value2 = arg; + else + throw new ValidationError(`${path59}: expected integer, got ${typeof arg}`); + if (!Number.isInteger(value2)) + throw new ValidationError(`${path59}: expected integer, got float ${value2}`); + return value2; + }; + tBoolean = (arg, path59, context2) => { + if (arg instanceof Boolean) + return arg.valueOf(); + if (typeof arg === "boolean") + return arg; + throw new ValidationError(`${path59}: expected boolean, got ${typeof arg}`); + }; + tString = (arg, path59, context2) => { + if (arg instanceof String) + return arg.valueOf(); + if (typeof arg === "string") + return arg; + throw new ValidationError(`${path59}: expected string, got ${typeof arg}`); + }; + tBinary = (arg, path59, context2) => { + if (context2.binary === "fromBase64") { + if (arg instanceof String) + return Buffer.from(arg.valueOf(), "base64"); + if (typeof arg === "string") + return Buffer.from(arg, "base64"); + throw new ValidationError(`${path59}: expected base64-encoded buffer, got ${typeof arg}`); + } + if (context2.binary === "toBase64") { + if (!(arg instanceof Buffer)) + throw new ValidationError(`${path59}: expected Buffer, got ${typeof arg}`); + return arg.toString("base64"); + } + if (context2.binary === "buffer") { + if (!(arg instanceof Buffer) && !(arg instanceof Object)) + throw new ValidationError(`${path59}: expected Buffer, got ${typeof arg}`); + return arg; + } + throw new ValidationError(`Unsupported binary behavior "${context2.binary}"`); + }; + tAny = (arg, path59, context2) => { + return arg; + }; + tOptional = (v) => { + return (arg, path59, context2) => { + if (Object.is(arg, void 0)) + return arg; + return v(arg, path59, context2); + }; + }; + tArray = (v) => { + return (arg, path59, context2) => { + if (!Array.isArray(arg)) + throw new ValidationError(`${path59}: expected array, got ${typeof arg}`); + return arg.map((x, index) => v(x, path59 + "[" + index + "]", context2)); + }; + }; + tObject = (s) => { + return (arg, path59, context2) => { + if (Object.is(arg, null)) + throw new ValidationError(`${path59}: expected object, got null`); + if (typeof arg !== "object") + throw new ValidationError(`${path59}: expected object, got ${typeof arg}`); + const result2 = {}; + for (const [key, v] of Object.entries(s)) { + const value2 = v(arg[key], path59 ? path59 + "." + key : key, context2); + if (!Object.is(value2, void 0)) + result2[key] = value2; + } + if (context2.isUnderTest()) { + for (const [key, value2] of Object.entries(arg)) { + if (key.startsWith("__testHook")) + result2[key] = value2; + } + } + return result2; + }; + }; + tEnum = (e) => { + return (arg, path59, context2) => { + if (!e.includes(arg)) + throw new ValidationError(`${path59}: expected one of (${e.join("|")})`); + return arg; + }; + }; + tChannel = (names) => { + return (arg, path59, context2) => { + return context2.tChannelImpl(names, arg, path59, context2); + }; + }; + tType = (name) => { + return (arg, path59, context2) => { + const v = scheme[name]; + if (!v) + throw new ValidationError(path59 + ': unknown type "' + name + '"'); + return v(arg, path59, context2); + }; + }; + } +}); + +// packages/playwright-core/src/protocol/validator.ts +var init_validator = __esm({ + "packages/playwright-core/src/protocol/validator.ts"() { + "use strict"; + init_validatorPrimitives(); + init_validatorPrimitives(); + scheme.AndroidInitializer = tOptional(tObject({})); + scheme.AndroidDevicesParams = tObject({ + host: tOptional(tString), + port: tOptional(tInt), + 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: tFloat + }); + scheme.AndroidDeviceWaitResult = tOptional(tObject({})); + scheme.AndroidDeviceFillParams = tObject({ + androidSelector: tType("AndroidSelector"), + text: tString, + timeout: tFloat + }); + scheme.AndroidDeviceFillResult = tOptional(tObject({})); + scheme.AndroidDeviceTapParams = tObject({ + androidSelector: tType("AndroidSelector"), + duration: tOptional(tFloat), + timeout: tFloat + }); + scheme.AndroidDeviceTapResult = tOptional(tObject({})); + scheme.AndroidDeviceDragParams = tObject({ + androidSelector: tType("AndroidSelector"), + dest: tType("Point"), + speed: tOptional(tFloat), + timeout: tFloat + }); + scheme.AndroidDeviceDragResult = tOptional(tObject({})); + scheme.AndroidDeviceFlingParams = tObject({ + androidSelector: tType("AndroidSelector"), + direction: tEnum(["up", "down", "left", "right"]), + speed: tOptional(tFloat), + timeout: tFloat + }); + scheme.AndroidDeviceFlingResult = tOptional(tObject({})); + scheme.AndroidDeviceLongTapParams = tObject({ + androidSelector: tType("AndroidSelector"), + timeout: tFloat + }); + scheme.AndroidDeviceLongTapResult = tOptional(tObject({})); + scheme.AndroidDevicePinchCloseParams = tObject({ + androidSelector: tType("AndroidSelector"), + percent: tFloat, + speed: tOptional(tFloat), + timeout: tFloat + }); + scheme.AndroidDevicePinchCloseResult = tOptional(tObject({})); + scheme.AndroidDevicePinchOpenParams = tObject({ + androidSelector: tType("AndroidSelector"), + percent: tFloat, + speed: tOptional(tFloat), + timeout: tFloat + }); + scheme.AndroidDevicePinchOpenResult = tOptional(tObject({})); + scheme.AndroidDeviceScrollParams = tObject({ + androidSelector: tType("AndroidSelector"), + direction: tEnum(["up", "down", "left", "right"]), + percent: tFloat, + speed: tOptional(tFloat), + timeout: tFloat + }); + scheme.AndroidDeviceScrollResult = tOptional(tObject({})); + scheme.AndroidDeviceSwipeParams = tObject({ + androidSelector: tType("AndroidSelector"), + direction: tEnum(["up", "down", "left", "right"]), + percent: tFloat, + speed: tOptional(tFloat), + timeout: tFloat + }); + 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: tInt + }); + scheme.AndroidDeviceInputSwipeResult = tOptional(tObject({})); + scheme.AndroidDeviceInputDragParams = tObject({ + from: tType("Point"), + to: tType("Point"), + steps: tInt + }); + scheme.AndroidDeviceInputDragResult = tOptional(tObject({})); + scheme.AndroidDeviceLaunchBrowserParams = tObject({ + noDefaultViewport: tOptional(tBoolean), + viewport: tOptional(tObject({ + width: tInt, + height: tInt + })), + screen: tOptional(tObject({ + width: tInt, + height: tInt + })), + 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: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })), + 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(tFloat), + 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: tOptional(tString), + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + showActions: tOptional(tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt) + })) + })), + 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(tInt) + }); + 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: tInt, + pkg: tString, + socketName: tString + }); + scheme.AndroidSelector = tObject({ + checkable: tOptional(tBoolean), + checked: tOptional(tBoolean), + clazz: tOptional(tString), + clickable: tOptional(tBoolean), + depth: tOptional(tInt), + 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(tInt) + })), + 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.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: tFloat, + failOnStatusCode: tOptional(tBoolean), + ignoreHTTPSErrors: tOptional(tBoolean), + maxRedirects: tOptional(tInt), + maxRetries: tOptional(tInt) + }); + 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: tInt, + statusText: tString, + headers: tArray(tType("NameValue")) + }); + 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(tInt) + }); + 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.BrowserInitializer = tObject({ + version: tString, + name: tString, + browserName: tEnum(["chromium", "firefox", "webkit"]) + }); + scheme.BrowserContextEvent = tObject({ + context: tChannel(["BrowserContext"]) + }); + scheme.BrowserCloseEvent = tOptional(tObject({})); + scheme.BrowserStartServerParams = tObject({ + title: tString, + workspaceDir: tOptional(tString), + metadata: tOptional(tAny), + host: tOptional(tString), + port: tOptional(tInt) + }); + scheme.BrowserStartServerResult = tObject({ + endpoint: tString + }); + scheme.BrowserStopServerParams = tOptional(tObject({})); + scheme.BrowserStopServerResult = 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: tInt, + height: tInt + })), + screen: tOptional(tObject({ + width: tInt, + height: tInt + })), + 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: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })), + 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(tFloat), + 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: tOptional(tString), + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + showActions: tOptional(tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt) + })) + })), + 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: tInt, + height: tInt + })), + screen: tOptional(tObject({ + width: tInt, + height: tInt + })), + 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: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })), + 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(tFloat), + 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: tOptional(tString), + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + showActions: tOptional(tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt) + })) + })), + 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.BrowserDisconnectFromReusedContextParams = tObject({ + reason: tString + }); + scheme.BrowserDisconnectFromReusedContextResult = 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.BrowserContextInitializer = tObject({ + debugger: tChannel(["Debugger"]), + requestContext: tChannel(["APIRequestContext"]), + tracing: tChannel(["Tracing"]), + options: tObject({ + noDefaultViewport: tOptional(tBoolean), + viewport: tOptional(tObject({ + width: tInt, + height: tInt + })), + screen: tOptional(tObject({ + width: tInt, + height: tInt + })), + 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: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })), + 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(tFloat), + 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: tOptional(tString), + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + showActions: tOptional(tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt) + })) + })), + 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: tInt, + columnNumber: tInt + }), + timestamp: tFloat, + page: tOptional(tChannel(["Page"])), + worker: tOptional(tChannel(["Worker"])) + }); + 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"]), + location: tObject({ + url: tString, + line: tInt, + column: tInt + }) + }); + scheme.BrowserContextRouteEvent = tObject({ + route: tChannel(["Route"]) + }); + scheme.BrowserContextWebSocketRouteEvent = tObject({ + webSocketRoute: tChannel(["WebSocketRoute"]) + }); + 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: tFloat, + page: tOptional(tChannel(["Page"])) + }); + scheme.BrowserContextRequestFinishedEvent = tObject({ + request: tChannel(["Request"]), + response: tOptional(tChannel(["Response"])), + responseEndTiming: tFloat, + page: tOptional(tChannel(["Page"])) + }); + scheme.BrowserContextResponseEvent = tObject({ + response: tChannel(["Response"]), + page: tOptional(tChannel(["Page"])) + }); + scheme.BrowserContextRecorderEventEvent = tObject({ + event: tEnum(["actionAdded", "actionUpdated", "signalAdded"]), + data: tAny, + page: tChannel(["Page"]), + code: tString + }); + scheme.BrowserContextAddCookiesParams = tObject({ + cookies: tArray(tType("SetNetworkCookie")) + }); + scheme.BrowserContextAddCookiesResult = tOptional(tObject({})); + scheme.BrowserContextAddInitScriptParams = tObject({ + source: tString + }); + scheme.BrowserContextAddInitScriptResult = tObject({ + disposable: tChannel(["Disposable"]) + }); + 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 + }); + scheme.BrowserContextExposeBindingResult = tObject({ + disposable: tChannel(["Disposable"]) + }); + 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: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })) + }); + 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), + urlPattern: tOptional(tType("URLPattern")) + })) + }); + scheme.BrowserContextSetNetworkInterceptionPatternsResult = tOptional(tObject({})); + scheme.BrowserContextSetWebSocketInterceptionPatternsParams = tObject({ + patterns: tArray(tObject({ + glob: tOptional(tString), + regexSource: tOptional(tString), + regexFlags: tOptional(tString), + urlPattern: tOptional(tType("URLPattern")) + })) + }); + 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.BrowserContextSetStorageStateParams = tObject({ + storageState: tOptional(tObject({ + cookies: tOptional(tArray(tType("SetNetworkCookie"))), + origins: tOptional(tArray(tType("SetOriginStorage"))) + })) + }); + scheme.BrowserContextSetStorageStateResult = tOptional(tObject({})); + scheme.BrowserContextPauseParams = tOptional(tObject({})); + scheme.BrowserContextPauseResult = tOptional(tObject({})); + scheme.BrowserContextEnableRecorderParams = tObject({ + language: tOptional(tString), + mode: tOptional(tEnum(["inspecting", "recording"])), + recorderMode: tOptional(tEnum(["default", "api"])), + 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.BrowserContextDisableRecorderParams = tOptional(tObject({})); + scheme.BrowserContextDisableRecorderResult = tOptional(tObject({})); + scheme.BrowserContextExposeConsoleApiParams = tOptional(tObject({})); + scheme.BrowserContextExposeConsoleApiResult = tOptional(tObject({})); + scheme.BrowserContextNewCDPSessionParams = tObject({ + page: tOptional(tChannel(["Page"])), + frame: tOptional(tChannel(["Frame"])) + }); + scheme.BrowserContextNewCDPSessionResult = tObject({ + session: tChannel(["CDPSession"]) + }); + scheme.BrowserContextCreateTempFilesParams = tObject({ + rootDirName: tOptional(tString), + items: tArray(tObject({ + name: tString, + lastModifiedMs: tOptional(tFloat) + })) + }); + 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(tFloat), + ticksString: tOptional(tString) + }); + scheme.BrowserContextClockFastForwardResult = tOptional(tObject({})); + scheme.BrowserContextClockInstallParams = tObject({ + timeNumber: tOptional(tFloat), + timeString: tOptional(tString) + }); + scheme.BrowserContextClockInstallResult = tOptional(tObject({})); + scheme.BrowserContextClockPauseAtParams = tObject({ + timeNumber: tOptional(tFloat), + timeString: tOptional(tString) + }); + scheme.BrowserContextClockPauseAtResult = tOptional(tObject({})); + scheme.BrowserContextClockResumeParams = tOptional(tObject({})); + scheme.BrowserContextClockResumeResult = tOptional(tObject({})); + scheme.BrowserContextClockRunForParams = tObject({ + ticksNumber: tOptional(tFloat), + ticksString: tOptional(tString) + }); + scheme.BrowserContextClockRunForResult = tOptional(tObject({})); + scheme.BrowserContextClockSetFixedTimeParams = tObject({ + timeNumber: tOptional(tFloat), + timeString: tOptional(tString) + }); + scheme.BrowserContextClockSetFixedTimeResult = tOptional(tObject({})); + scheme.BrowserContextClockSetSystemTimeParams = tObject({ + timeNumber: tOptional(tFloat), + timeString: tOptional(tString) + }); + scheme.BrowserContextClockSetSystemTimeResult = 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)), + handleSIGINT: tOptional(tBoolean), + handleSIGTERM: tOptional(tBoolean), + handleSIGHUP: tOptional(tBoolean), + timeout: tFloat, + env: tOptional(tArray(tType("NameValue"))), + headless: tOptional(tBoolean), + proxy: tOptional(tObject({ + server: tString, + bypass: tOptional(tString), + username: tOptional(tString), + password: tOptional(tString) + })), + downloadsPath: tOptional(tString), + tracesDir: tOptional(tString), + artifactsDir: tOptional(tString), + chromiumSandbox: tOptional(tBoolean), + firefoxUserPrefs: tOptional(tAny), + cdpPort: tOptional(tInt), + slowMo: tOptional(tFloat) + }); + 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)), + handleSIGINT: tOptional(tBoolean), + handleSIGTERM: tOptional(tBoolean), + handleSIGHUP: tOptional(tBoolean), + timeout: tFloat, + env: tOptional(tArray(tType("NameValue"))), + headless: tOptional(tBoolean), + proxy: tOptional(tObject({ + server: tString, + bypass: tOptional(tString), + username: tOptional(tString), + password: tOptional(tString) + })), + downloadsPath: tOptional(tString), + tracesDir: tOptional(tString), + artifactsDir: tOptional(tString), + chromiumSandbox: tOptional(tBoolean), + firefoxUserPrefs: tOptional(tAny), + cdpPort: tOptional(tInt), + noDefaultViewport: tOptional(tBoolean), + viewport: tOptional(tObject({ + width: tInt, + height: tInt + })), + screen: tOptional(tObject({ + width: tInt, + height: tInt + })), + 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: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })), + 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(tFloat), + 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: tOptional(tString), + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + showActions: tOptional(tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt) + })) + })), + strictSelectors: tOptional(tBoolean), + serviceWorkers: tOptional(tEnum(["allow", "block"])), + selectorEngines: tOptional(tArray(tType("SelectorEngine"))), + testIdAttributeName: tOptional(tString), + userDataDir: tString, + slowMo: tOptional(tFloat) + }); + scheme.BrowserTypeLaunchPersistentContextResult = tObject({ + browser: tChannel(["Browser"]), + context: tChannel(["BrowserContext"]) + }); + scheme.BrowserTypeConnectOverCDPParams = tObject({ + endpointURL: tString, + headers: tOptional(tArray(tType("NameValue"))), + slowMo: tOptional(tFloat), + timeout: tFloat, + isLocal: tOptional(tBoolean), + noDefaults: tOptional(tBoolean) + }); + scheme.BrowserTypeConnectOverCDPResult = tObject({ + browser: tChannel(["Browser"]), + defaultContext: tOptional(tChannel(["BrowserContext"])) + }); + scheme.BrowserTypeConnectToWorkerParams = tObject({ + endpoint: tString, + timeout: tFloat + }); + scheme.BrowserTypeConnectToWorkerResult = tObject({ + worker: tChannel(["Worker"]) + }); + scheme.Metadata = tObject({ + location: tOptional(tObject({ + file: tString, + line: tOptional(tInt), + column: tOptional(tInt) + })), + title: tOptional(tString), + internal: tOptional(tBoolean), + stepId: tOptional(tString) + }); + scheme.ClientSideCallMetadata = tObject({ + id: tInt, + stack: tOptional(tArray(tType("StackFrame"))) + }); + scheme.SDKLanguage = tEnum(["javascript", "python", "java", "csharp"]); + scheme.DisposableInitializer = tOptional(tObject({})); + scheme.DisposableDisposeParams = tOptional(tObject({})); + scheme.DisposableDisposeResult = tOptional(tObject({})); + 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.AndroidDeviceWaitForEventInfoParams = tType("EventTargetWaitForEventInfoParams"); + scheme.BrowserContextWaitForEventInfoParams = tType("EventTargetWaitForEventInfoParams"); + scheme.ElectronApplicationWaitForEventInfoParams = tType("EventTargetWaitForEventInfoParams"); + scheme.WebSocketWaitForEventInfoParams = tType("EventTargetWaitForEventInfoParams"); + scheme.PageWaitForEventInfoParams = tType("EventTargetWaitForEventInfoParams"); + scheme.DebuggerWaitForEventInfoParams = tType("EventTargetWaitForEventInfoParams"); + scheme.WorkerWaitForEventInfoParams = tType("EventTargetWaitForEventInfoParams"); + scheme.EventTargetWaitForEventInfoResult = tOptional(tObject({})); + scheme.AndroidDeviceWaitForEventInfoResult = tType("EventTargetWaitForEventInfoResult"); + scheme.BrowserContextWaitForEventInfoResult = tType("EventTargetWaitForEventInfoResult"); + scheme.ElectronApplicationWaitForEventInfoResult = tType("EventTargetWaitForEventInfoResult"); + scheme.WebSocketWaitForEventInfoResult = tType("EventTargetWaitForEventInfoResult"); + scheme.PageWaitForEventInfoResult = tType("EventTargetWaitForEventInfoResult"); + scheme.DebuggerWaitForEventInfoResult = tType("EventTargetWaitForEventInfoResult"); + scheme.WorkerWaitForEventInfoResult = tType("EventTargetWaitForEventInfoResult"); + scheme.ElectronInitializer = tOptional(tObject({})); + scheme.ElectronLaunchParams = tObject({ + executablePath: tOptional(tString), + args: tOptional(tArray(tString)), + chromiumSandbox: tOptional(tBoolean), + cwd: tOptional(tString), + env: tOptional(tArray(tType("NameValue"))), + timeout: tFloat, + 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: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })), + httpCredentials: tOptional(tObject({ + username: tString, + password: tString, + origin: tOptional(tString) + })), + ignoreHTTPSErrors: tOptional(tBoolean), + locale: tOptional(tString), + offline: tOptional(tBoolean), + recordVideo: tOptional(tObject({ + dir: tOptional(tString), + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + showActions: tOptional(tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt) + })) + })), + strictSelectors: tOptional(tBoolean), + timezoneId: tOptional(tString), + tracesDir: tOptional(tString), + artifactsDir: 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: tInt, + columnNumber: tInt + }), + timestamp: tFloat + }); + 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.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({ + mode: tOptional(tEnum(["ai", "default"])), + track: tOptional(tString), + selector: tOptional(tString), + depth: tOptional(tInt), + boxes: tOptional(tBoolean), + timeout: tFloat + }); + scheme.FrameAriaSnapshotResult = tObject({ + snapshot: tString + }); + scheme.FrameBlurParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tFloat + }); + scheme.FrameBlurResult = tOptional(tObject({})); + scheme.FrameCheckParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + force: tOptional(tBoolean), + position: tOptional(tType("Point")), + timeout: tFloat, + 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(tFloat), + button: tOptional(tEnum(["left", "right", "middle"])), + clickCount: tOptional(tInt), + timeout: tFloat, + trial: tOptional(tBoolean), + steps: tOptional(tInt) + }); + scheme.FrameClickResult = tOptional(tObject({})); + scheme.FrameContentParams = tOptional(tObject({})); + scheme.FrameContentResult = tObject({ + value: tString + }); + scheme.FrameDragAndDropParams = tObject({ + source: tString, + target: tString, + force: tOptional(tBoolean), + timeout: tFloat, + trial: tOptional(tBoolean), + sourcePosition: tOptional(tType("Point")), + targetPosition: tOptional(tType("Point")), + strict: tOptional(tBoolean), + steps: tOptional(tInt) + }); + scheme.FrameDragAndDropResult = tOptional(tObject({})); + scheme.FrameDropParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + position: tOptional(tType("Point")), + payloads: tOptional(tArray(tObject({ + name: tString, + mimeType: tOptional(tString), + buffer: tBinary + }))), + localPaths: tOptional(tArray(tString)), + streams: tOptional(tArray(tChannel(["WritableStream"]))), + data: tOptional(tArray(tObject({ + mimeType: tString, + value: tString + }))), + timeout: tFloat + }); + scheme.FrameDropResult = 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(tFloat), + button: tOptional(tEnum(["left", "right", "middle"])), + timeout: tFloat, + trial: tOptional(tBoolean), + steps: tOptional(tInt) + }); + scheme.FrameDblclickResult = tOptional(tObject({})); + scheme.FrameDispatchEventParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + type: tString, + eventInit: tType("SerializedArgument"), + timeout: tFloat + }); + 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: tFloat + }); + scheme.FrameFillResult = tOptional(tObject({})); + scheme.FrameFocusParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tFloat + }); + scheme.FrameFocusResult = tOptional(tObject({})); + scheme.FrameFrameElementParams = tOptional(tObject({})); + scheme.FrameFrameElementResult = tObject({ + element: tChannel(["ElementHandle"]) + }); + scheme.FrameResolveSelectorParams = tObject({ + selector: tString + }); + scheme.FrameResolveSelectorResult = tObject({ + resolvedSelector: tString + }); + scheme.FrameHighlightParams = tObject({ + selector: tString, + style: tOptional(tString) + }); + scheme.FrameHighlightResult = tOptional(tObject({})); + scheme.FrameHideHighlightParams = tObject({ + selector: tString + }); + scheme.FrameHideHighlightResult = tOptional(tObject({})); + scheme.FrameGetAttributeParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + name: tString, + timeout: tFloat + }); + scheme.FrameGetAttributeResult = tObject({ + value: tOptional(tString) + }); + scheme.FrameGotoParams = tObject({ + url: tString, + timeout: tFloat, + 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: tFloat, + trial: tOptional(tBoolean) + }); + scheme.FrameHoverResult = tOptional(tObject({})); + scheme.FrameInnerHTMLParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tFloat + }); + scheme.FrameInnerHTMLResult = tObject({ + value: tString + }); + scheme.FrameInnerTextParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tFloat + }); + scheme.FrameInnerTextResult = tObject({ + value: tString + }); + scheme.FrameInputValueParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tFloat + }); + scheme.FrameInputValueResult = tObject({ + value: tString + }); + scheme.FrameIsCheckedParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tFloat + }); + scheme.FrameIsCheckedResult = tObject({ + value: tBoolean + }); + scheme.FrameIsDisabledParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tFloat + }); + scheme.FrameIsDisabledResult = tObject({ + value: tBoolean + }); + scheme.FrameIsEnabledParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tFloat + }); + 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: tFloat + }); + scheme.FrameIsEditableResult = tObject({ + value: tBoolean + }); + scheme.FramePressParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + key: tString, + delay: tOptional(tFloat), + noWaitAfter: tOptional(tBoolean), + timeout: tFloat + }); + 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: tInt + }); + 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(tInt) + }))), + force: tOptional(tBoolean), + timeout: tFloat + }); + scheme.FrameSelectOptionResult = tObject({ + values: tArray(tString) + }); + scheme.FrameSetContentParams = tObject({ + html: tString, + timeout: tFloat, + 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: tFloat + }); + 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: tFloat, + trial: tOptional(tBoolean) + }); + scheme.FrameTapResult = tOptional(tObject({})); + scheme.FrameTextContentParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tFloat + }); + 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(tFloat), + timeout: tFloat + }); + scheme.FrameTypeResult = tOptional(tObject({})); + scheme.FrameUncheckParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + force: tOptional(tBoolean), + position: tOptional(tType("Point")), + timeout: tFloat, + trial: tOptional(tBoolean) + }); + scheme.FrameUncheckResult = tOptional(tObject({})); + scheme.FrameWaitForTimeoutParams = tObject({ + waitTimeout: tFloat + }); + scheme.FrameWaitForTimeoutResult = tOptional(tObject({})); + scheme.FrameWaitForFunctionParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument"), + timeout: tFloat, + pollingInterval: tOptional(tFloat) + }); + scheme.FrameWaitForFunctionResult = tObject({ + handle: tChannel(["ElementHandle", "JSHandle"]) + }); + scheme.FrameWaitForSelectorParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tFloat, + state: tOptional(tEnum(["attached", "detached", "visible", "hidden"])), + omitReturnValue: tOptional(tBoolean) + }); + scheme.FrameWaitForSelectorResult = tObject({ + element: tOptional(tChannel(["ElementHandle"])) + }); + scheme.FrameExpectParams = tObject({ + selector: tOptional(tString), + expression: tString, + expressionArg: tOptional(tAny), + pseudo: tOptional(tEnum(["before", "after"])), + expectedText: tOptional(tArray(tType("ExpectedTextValue"))), + expectedNumber: tOptional(tFloat), + expectedValue: tOptional(tType("SerializedArgument")), + useInnerText: tOptional(tBoolean), + isNot: tBoolean, + timeout: tFloat + }); + scheme.FrameExpectResult = tObject({ + matches: tBoolean, + received: tOptional(tObject({ + value: tOptional(tType("SerializedValue")), + ariaSnapshot: tOptional(tString) + })), + timedOut: tOptional(tBoolean), + errorMessage: tOptional(tString), + log: tOptional(tArray(tString)) + }); + 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: tFloat, + 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(tFloat), + button: tOptional(tEnum(["left", "right", "middle"])), + clickCount: tOptional(tInt), + timeout: tFloat, + trial: tOptional(tBoolean), + steps: tOptional(tInt) + }); + 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(tFloat), + button: tOptional(tEnum(["left", "right", "middle"])), + timeout: tFloat, + trial: tOptional(tBoolean), + steps: tOptional(tInt) + }); + 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: tFloat + }); + scheme.ElementHandleFillResult = tOptional(tObject({})); + scheme.ElementHandleFocusParams = tOptional(tObject({})); + scheme.ElementHandleFocusResult = tOptional(tObject({})); + 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: tFloat, + 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(tFloat), + timeout: tFloat, + 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: tFloat, + type: tOptional(tEnum(["png", "jpeg"])), + quality: tOptional(tInt), + 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: tFloat + }); + 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(tInt) + }))), + force: tOptional(tBoolean), + timeout: tFloat + }); + scheme.ElementHandleSelectOptionResult = tObject({ + values: tArray(tString) + }); + scheme.ElementHandleSelectTextParams = tObject({ + force: tOptional(tBoolean), + timeout: tFloat + }); + 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: tFloat + }); + scheme.ElementHandleSetInputFilesResult = tOptional(tObject({})); + scheme.ElementHandleTapParams = tObject({ + force: tOptional(tBoolean), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + timeout: tFloat, + trial: tOptional(tBoolean) + }); + scheme.ElementHandleTapResult = tOptional(tObject({})); + scheme.ElementHandleTextContentParams = tOptional(tObject({})); + scheme.ElementHandleTextContentResult = tObject({ + value: tOptional(tString) + }); + scheme.ElementHandleTypeParams = tObject({ + text: tString, + delay: tOptional(tFloat), + timeout: tFloat + }); + scheme.ElementHandleTypeResult = tOptional(tObject({})); + scheme.ElementHandleUncheckParams = tObject({ + force: tOptional(tBoolean), + position: tOptional(tType("Point")), + timeout: tFloat, + trial: tOptional(tBoolean) + }); + scheme.ElementHandleUncheckResult = tOptional(tObject({})); + scheme.ElementHandleWaitForElementStateParams = tObject({ + state: tEnum(["visible", "hidden", "stable", "enabled", "disabled", "editable"]), + timeout: tFloat + }); + scheme.ElementHandleWaitForElementStateResult = tOptional(tObject({})); + scheme.ElementHandleWaitForSelectorParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tFloat, + state: tOptional(tEnum(["attached", "detached", "visible", "hidden"])) + }); + scheme.ElementHandleWaitForSelectorResult = tObject({ + element: tOptional(tChannel(["ElementHandle"])) + }); + scheme.LocalUtilsInitializer = tObject({ + deviceDescriptors: tArray(tObject({ + name: tString, + descriptor: tObject({ + userAgent: tString, + viewport: tObject({ + width: tInt, + height: tInt + }), + screen: tOptional(tObject({ + width: tInt, + height: tInt + })), + deviceScaleFactor: tFloat, + 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, + additionalSources: tOptional(tArray(tString)) + }); + 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(tInt), + headers: tOptional(tArray(tType("NameValue"))), + body: tOptional(tBinary) + }); + scheme.LocalUtilsHarCloseParams = tObject({ + harId: tString + }); + scheme.LocalUtilsHarCloseResult = tOptional(tObject({})); + scheme.LocalUtilsHarUnzipParams = tObject({ + zipFile: tString, + harFile: tString, + resourcesDir: tOptional(tString) + }); + scheme.LocalUtilsHarUnzipResult = tOptional(tObject({})); + scheme.LocalUtilsConnectParams = tObject({ + endpoint: tString, + headers: tOptional(tAny), + exposeNetwork: tOptional(tString), + slowMo: tOptional(tFloat), + timeout: tFloat, + socksProxyRedirectPortForTest: tOptional(tInt) + }); + scheme.LocalUtilsConnectResult = tObject({ + pipe: tChannel(["JsonPipe"]), + headers: tArray(tType("NameValue")) + }); + scheme.LocalUtilsTracingStartedParams = tObject({ + tracesDir: tOptional(tString), + traceName: tString, + live: tOptional(tBoolean) + }); + 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.SetNetworkCookie = tObject({ + name: tString, + value: tString, + url: tOptional(tString), + domain: tOptional(tString), + path: tOptional(tString), + expires: tOptional(tFloat), + httpOnly: tOptional(tBoolean), + secure: tOptional(tBoolean), + sameSite: tOptional(tEnum(["Strict", "Lax", "None"])), + partitionKey: tOptional(tString), + _crHasCrossSiteAncestor: tOptional(tBoolean) + }); + scheme.NetworkCookie = tObject({ + name: tString, + value: tString, + domain: tString, + path: tString, + expires: tFloat, + httpOnly: tBoolean, + secure: tBoolean, + sameSite: tEnum(["Strict", "Lax", "None"]), + partitionKey: tOptional(tString), + _crHasCrossSiteAncestor: tOptional(tBoolean) + }); + 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(tInt), + headers: tOptional(tArray(tType("NameValue"))), + body: tOptional(tString), + isBase64: tOptional(tBoolean), + fetchResponseUid: tOptional(tString) + }); + scheme.RouteFulfillResult = tOptional(tObject({})); + scheme.WebSocketRouteInitializer = tObject({ + url: tString, + protocols: tArray(tString) + }); + scheme.WebSocketRouteMessageFromPageEvent = tObject({ + message: tString, + isBase64: tBoolean + }); + scheme.WebSocketRouteMessageFromServerEvent = tObject({ + message: tString, + isBase64: tBoolean + }); + scheme.WebSocketRouteClosePageEvent = tObject({ + code: tOptional(tInt), + reason: tOptional(tString), + wasClean: tBoolean + }); + scheme.WebSocketRouteCloseServerEvent = tObject({ + code: tOptional(tInt), + 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(tInt), + reason: tOptional(tString), + wasClean: tBoolean + }); + scheme.WebSocketRouteClosePageResult = tOptional(tObject({})); + scheme.WebSocketRouteCloseServerParams = tObject({ + code: tOptional(tInt), + reason: tOptional(tString), + wasClean: tBoolean + }); + scheme.WebSocketRouteCloseServerResult = tOptional(tObject({})); + scheme.ResourceTiming = tObject({ + startTime: tFloat, + domainLookupStart: tFloat, + domainLookupEnd: tFloat, + connectStart: tFloat, + secureConnectionStart: tFloat, + connectEnd: tFloat, + requestStart: tFloat, + responseStart: tFloat + }); + scheme.ResponseInitializer = tObject({ + request: tChannel(["Request"]), + url: tString, + status: tInt, + 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.ResponseHttpVersionParams = tOptional(tObject({})); + scheme.ResponseHttpVersionResult = tObject({ + value: tString + }); + scheme.ResponseSizesParams = tOptional(tObject({})); + scheme.ResponseSizesResult = tObject({ + sizes: tType("RequestSizes") + }); + scheme.SecurityDetails = tObject({ + issuer: tOptional(tString), + protocol: tOptional(tString), + subjectName: tOptional(tString), + validFrom: tOptional(tFloat), + validTo: tOptional(tFloat) + }); + scheme.RequestSizes = tObject({ + requestBodySize: tInt, + requestHeadersSize: tInt, + responseBodySize: tInt, + responseHeadersSize: tInt + }); + scheme.RemoteAddr = tObject({ + ipAddress: tString, + port: tInt + }); + scheme.WebSocketInitializer = tObject({ + url: tString + }); + scheme.WebSocketOpenEvent = tOptional(tObject({})); + scheme.WebSocketFrameSentEvent = tObject({ + opcode: tInt, + data: tString + }); + scheme.WebSocketFrameReceivedEvent = tObject({ + opcode: tInt, + data: tString + }); + scheme.WebSocketSocketErrorEvent = tObject({ + error: tString + }); + scheme.WebSocketCloseEvent = tOptional(tObject({})); + scheme.PageInitializer = tObject({ + mainFrame: tChannel(["Frame"]), + viewportSize: tOptional(tObject({ + width: tInt, + height: tInt + })), + isClosed: tBoolean, + opener: tOptional(tChannel(["Page"])), + video: tOptional(tChannel(["Artifact"])) + }); + 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: tInt, + height: tInt + })) + }); + scheme.PageFileChooserEvent = tObject({ + element: tChannel(["ElementHandle"]), + isMultiple: tBoolean + }); + scheme.PageFrameAttachedEvent = tObject({ + frame: tChannel(["Frame"]) + }); + scheme.PageFrameDetachedEvent = tObject({ + frame: tChannel(["Frame"]) + }); + scheme.PageLocatorHandlerTriggeredEvent = tObject({ + uid: tInt + }); + scheme.PageRouteEvent = tObject({ + route: tChannel(["Route"]) + }); + scheme.PageScreencastFrameEvent = tObject({ + data: tBinary, + viewportWidth: tInt, + viewportHeight: tInt + }); + scheme.PageWebSocketRouteEvent = tObject({ + webSocketRoute: tChannel(["WebSocketRoute"]) + }); + scheme.PageWebSocketEvent = tObject({ + webSocket: tChannel(["WebSocket"]) + }); + scheme.PageWorkerEvent = tObject({ + worker: tChannel(["Worker"]) + }); + scheme.PageAddInitScriptParams = tObject({ + source: tString + }); + scheme.PageAddInitScriptResult = tObject({ + disposable: tChannel(["Disposable"]) + }); + scheme.PageCloseParams = tObject({ + runBeforeUnload: tOptional(tBoolean), + reason: tOptional(tString) + }); + scheme.PageCloseResult = tOptional(tObject({})); + scheme.PageClearConsoleMessagesParams = tOptional(tObject({})); + scheme.PageClearConsoleMessagesResult = tOptional(tObject({})); + scheme.PageConsoleMessagesParams = tObject({ + filter: tOptional(tType("ConsoleMessagesFilter")) + }); + scheme.PageConsoleMessagesResult = tObject({ + messages: tArray(tObject({ + type: tString, + text: tString, + args: tArray(tChannel(["ElementHandle", "JSHandle"])), + location: tObject({ + url: tString, + lineNumber: tInt, + columnNumber: tInt + }), + timestamp: tFloat + })) + }); + 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 + }); + scheme.PageExposeBindingResult = tObject({ + disposable: tChannel(["Disposable"]) + }); + scheme.PageGoBackParams = tObject({ + timeout: tFloat, + waitUntil: tOptional(tType("LifecycleEvent")) + }); + scheme.PageGoBackResult = tObject({ + response: tOptional(tChannel(["Response"])) + }); + scheme.PageGoForwardParams = tObject({ + timeout: tFloat, + 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: tInt + }); + scheme.PageResolveLocatorHandlerNoReplyParams = tObject({ + uid: tInt, + remove: tOptional(tBoolean) + }); + scheme.PageResolveLocatorHandlerNoReplyResult = tOptional(tObject({})); + scheme.PageUnregisterLocatorHandlerParams = tObject({ + uid: tInt + }); + scheme.PageUnregisterLocatorHandlerResult = tOptional(tObject({})); + scheme.PageReloadParams = tObject({ + timeout: tFloat, + waitUntil: tOptional(tType("LifecycleEvent")) + }); + scheme.PageReloadResult = tObject({ + response: tOptional(tChannel(["Response"])) + }); + scheme.PageExpectScreenshotParams = tObject({ + expected: tOptional(tBinary), + timeout: tFloat, + isNot: tBoolean, + locator: tOptional(tObject({ + frame: tChannel(["Frame"]), + selector: tString + })), + comparator: tOptional(tString), + maxDiffPixels: tOptional(tInt), + maxDiffPixelRatio: tOptional(tFloat), + threshold: tOptional(tFloat), + 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: tFloat, + type: tOptional(tEnum(["png", "jpeg"])), + quality: tOptional(tInt), + 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), + urlPattern: tOptional(tType("URLPattern")) + })) + }); + scheme.PageSetNetworkInterceptionPatternsResult = tOptional(tObject({})); + scheme.PageSetWebSocketInterceptionPatternsParams = tObject({ + patterns: tArray(tObject({ + glob: tOptional(tString), + regexSource: tOptional(tString), + regexFlags: tOptional(tString), + urlPattern: tOptional(tType("URLPattern")) + })) + }); + scheme.PageSetWebSocketInterceptionPatternsResult = tOptional(tObject({})); + scheme.PageSetViewportSizeParams = tObject({ + viewportSize: tObject({ + width: tInt, + height: tInt + }) + }); + 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(tFloat) + }); + scheme.PageKeyboardTypeResult = tOptional(tObject({})); + scheme.PageKeyboardPressParams = tObject({ + key: tString, + delay: tOptional(tFloat) + }); + scheme.PageKeyboardPressResult = tOptional(tObject({})); + scheme.PageMouseMoveParams = tObject({ + x: tFloat, + y: tFloat, + steps: tOptional(tInt) + }); + scheme.PageMouseMoveResult = tOptional(tObject({})); + scheme.PageMouseDownParams = tObject({ + button: tOptional(tEnum(["left", "right", "middle"])), + clickCount: tOptional(tInt) + }); + scheme.PageMouseDownResult = tOptional(tObject({})); + scheme.PageMouseUpParams = tObject({ + button: tOptional(tEnum(["left", "right", "middle"])), + clickCount: tOptional(tInt) + }); + scheme.PageMouseUpResult = tOptional(tObject({})); + scheme.PageMouseClickParams = tObject({ + x: tFloat, + y: tFloat, + delay: tOptional(tFloat), + button: tOptional(tEnum(["left", "right", "middle"])), + clickCount: tOptional(tInt) + }); + scheme.PageMouseClickResult = tOptional(tObject({})); + scheme.PageMouseWheelParams = tObject({ + deltaX: tFloat, + deltaY: tFloat + }); + scheme.PageMouseWheelResult = tOptional(tObject({})); + scheme.PageTouchscreenTapParams = tObject({ + x: tFloat, + y: tFloat + }); + scheme.PageTouchscreenTapResult = tOptional(tObject({})); + scheme.PageClearPageErrorsParams = tOptional(tObject({})); + scheme.PageClearPageErrorsResult = tOptional(tObject({})); + scheme.PagePageErrorsParams = tObject({ + filter: tOptional(tType("ConsoleMessagesFilter")) + }); + scheme.PagePageErrorsResult = tObject({ + errors: tArray(tType("SerializedError")) + }); + scheme.PagePdfParams = tObject({ + scale: tOptional(tFloat), + 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.PageRequestsParams = tOptional(tObject({})); + scheme.PageRequestsResult = tObject({ + requests: tArray(tChannel(["Request"])) + }); + 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: tInt, + endOffset: tInt, + count: tInt + })) + })) + })) + }); + 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: tInt, + end: tInt + })) + })) + }); + scheme.PageBringToFrontParams = tOptional(tObject({})); + scheme.PageBringToFrontResult = tOptional(tObject({})); + scheme.PagePickLocatorParams = tOptional(tObject({})); + scheme.PagePickLocatorResult = tObject({ + selector: tString + }); + scheme.PageCancelPickLocatorParams = tOptional(tObject({})); + scheme.PageCancelPickLocatorResult = tOptional(tObject({})); + scheme.PageHideHighlightParams = tOptional(tObject({})); + scheme.PageHideHighlightResult = tOptional(tObject({})); + scheme.PageScreencastShowOverlayParams = tObject({ + html: tString, + duration: tOptional(tFloat) + }); + scheme.PageScreencastShowOverlayResult = tObject({ + id: tString + }); + scheme.PageScreencastRemoveOverlayParams = tObject({ + id: tString + }); + scheme.PageScreencastRemoveOverlayResult = tOptional(tObject({})); + scheme.PageScreencastChapterParams = tObject({ + title: tString, + description: tOptional(tString), + duration: tOptional(tFloat) + }); + scheme.PageScreencastChapterResult = tOptional(tObject({})); + scheme.PageScreencastSetOverlayVisibleParams = tObject({ + visible: tBoolean + }); + scheme.PageScreencastSetOverlayVisibleResult = tOptional(tObject({})); + scheme.PageScreencastShowActionsParams = tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt) + }); + scheme.PageScreencastShowActionsResult = tOptional(tObject({})); + scheme.PageScreencastHideActionsParams = tOptional(tObject({})); + scheme.PageScreencastHideActionsResult = tOptional(tObject({})); + scheme.PageScreencastStartParams = tObject({ + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + quality: tOptional(tInt), + sendFrames: tOptional(tBoolean), + record: tOptional(tBoolean) + }); + scheme.PageScreencastStartResult = tObject({ + artifact: tOptional(tChannel(["Artifact"])) + }); + scheme.PageScreencastStopParams = tOptional(tObject({})); + scheme.PageScreencastStopResult = tOptional(tObject({})); + scheme.PageUpdateSubscriptionParams = tObject({ + event: tEnum(["console", "dialog", "fileChooser", "request", "response", "requestFinished", "requestFailed"]), + enabled: tBoolean + }); + scheme.PageUpdateSubscriptionResult = tOptional(tObject({})); + scheme.PageSetDockTileParams = tObject({ + image: tBinary + }); + scheme.PageSetDockTileResult = tOptional(tObject({})); + scheme.RootInitializer = tOptional(tObject({})); + scheme.RootInitializeParams = tObject({ + sdkLanguage: tType("SDKLanguage") + }); + scheme.RootInitializeResult = tObject({ + playwright: tChannel(["Playwright"]) + }); + scheme.PlaywrightInitializer = tObject({ + chromium: tChannel(["BrowserType"]), + firefox: tChannel(["BrowserType"]), + webkit: 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(tInt), + 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.DebugControllerInitializer = tOptional(tObject({})); + scheme.DebugControllerInspectRequestedEvent = tObject({ + selector: tString, + locator: tString, + ariaSnapshot: tString + }); + scheme.DebugControllerSetModeRequestedEvent = tObject({ + mode: tString + }); + scheme.DebugControllerStateChangedEvent = tObject({ + pageCount: tInt + }); + 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: tType("SDKLanguage") + }); + scheme.DebugControllerInitializeResult = tOptional(tObject({})); + scheme.DebugControllerSetReportStateChangedParams = tObject({ + enabled: tBoolean + }); + scheme.DebugControllerSetReportStateChangedResult = tOptional(tObject({})); + scheme.DebugControllerSetRecorderModeParams = tObject({ + mode: tEnum(["inspecting", "recording", "none"]), + testIdAttributeName: tOptional(tString), + generateAutoExpect: tOptional(tBoolean) + }); + 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.SocksSupportInitializer = tOptional(tObject({})); + scheme.SocksSupportSocksRequestedEvent = tObject({ + uid: tString, + host: tString, + port: tInt + }); + scheme.SocksSupportSocksDataEvent = tObject({ + uid: tString, + data: tBinary + }); + scheme.SocksSupportSocksClosedEvent = tObject({ + uid: tString + }); + scheme.SocksSupportSocksConnectedParams = tObject({ + uid: tString, + host: tString, + port: tInt + }); + 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.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({})); + 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.FormField = tObject({ + name: tString, + value: tOptional(tString), + file: tOptional(tObject({ + name: tString, + mimeType: tOptional(tString), + buffer: tBinary + })) + }); + scheme.LifecycleEvent = tEnum(["load", "domcontentloaded", "networkidle", "commit"]); + scheme.ConsoleMessagesFilter = tEnum(["all", "since-navigation"]); + scheme.RecorderSource = tObject({ + isRecorded: tBoolean, + id: tString, + label: tString, + text: tString, + language: tString, + highlight: tArray(tObject({ + line: tInt, + type: tString + })), + revealLine: tOptional(tInt), + group: tOptional(tString) + }); + scheme.IndexedDBDatabase = tObject({ + name: tString, + version: tInt, + 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.RecordHarOptions = tObject({ + content: tOptional(tEnum(["embed", "attach", "omit"])), + mode: tOptional(tEnum(["full", "minimal"])), + urlGlob: tOptional(tString), + urlRegexSource: tOptional(tString), + urlRegexFlags: tOptional(tString), + harPath: tOptional(tString), + resourcesDir: tOptional(tString) + }); + scheme.CDPSessionInitializer = tOptional(tObject({})); + scheme.CDPSessionEventEvent = tObject({ + method: tString, + params: tOptional(tAny) + }); + scheme.CDPSessionCloseEvent = tOptional(tObject({})); + scheme.CDPSessionSendParams = tObject({ + method: tString, + params: tOptional(tAny) + }); + scheme.CDPSessionSendResult = tObject({ + result: tAny + }); + scheme.CDPSessionDetachParams = tOptional(tObject({})); + scheme.CDPSessionDetachResult = tOptional(tObject({})); + scheme.BindingCallInitializer = tObject({ + frame: tChannel(["Frame"]), + name: tString, + args: tArray(tType("SerializedValue")) + }); + scheme.BindingCallRejectParams = tObject({ + error: tType("SerializedError") + }); + scheme.BindingCallRejectResult = tOptional(tObject({})); + scheme.BindingCallResolveParams = tObject({ + result: tType("SerializedArgument") + }); + scheme.BindingCallResolveResult = tOptional(tObject({})); + scheme.DebuggerInitializer = tOptional(tObject({})); + scheme.DebuggerPausedStateChangedEvent = tObject({ + pausedDetails: tOptional(tObject({ + location: tObject({ + file: tString, + line: tOptional(tInt), + column: tOptional(tInt) + }), + title: tString, + stack: tOptional(tString) + })) + }); + scheme.DebuggerRequestPauseParams = tOptional(tObject({})); + scheme.DebuggerRequestPauseResult = tOptional(tObject({})); + scheme.DebuggerResumeParams = tOptional(tObject({})); + scheme.DebuggerResumeResult = tOptional(tObject({})); + scheme.DebuggerNextParams = tOptional(tObject({})); + scheme.DebuggerNextResult = tOptional(tObject({})); + scheme.DebuggerRunToParams = tObject({ + location: tObject({ + file: tString, + line: tOptional(tInt), + column: tOptional(tInt) + }) + }); + scheme.DebuggerRunToResult = 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.SerializedValue = tObject({ + n: tOptional(tFloat), + 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(tInt), + id: tOptional(tInt), + ref: tOptional(tInt) + }); + scheme.SerializedArgument = tObject({ + value: tType("SerializedValue"), + handles: tArray(tChannel("*")) + }); + scheme.SerializedError = tObject({ + error: tOptional(tObject({ + message: tString, + name: tString, + stack: tOptional(tString) + })), + value: tOptional(tType("SerializedValue")) + }); + scheme.StackFrame = tObject({ + file: tString, + line: tInt, + column: tInt, + function: tOptional(tString) + }); + scheme.Point = tObject({ + x: tFloat, + y: tFloat + }); + scheme.Rect = tObject({ + x: tFloat, + y: tFloat, + width: tFloat, + height: tFloat + }); + scheme.URLPattern = tObject({ + hash: tString, + hostname: tString, + password: tString, + pathname: tString, + port: tString, + protocol: tString, + search: tString, + username: tString + }); + scheme.NameValue = tObject({ + name: tString, + value: tString + }); + 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(tInt), + column: tOptional(tInt) + })) + }); + 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.TracingHarStartParams = tObject({ + page: tOptional(tChannel(["Page"])), + options: tType("RecordHarOptions") + }); + scheme.TracingHarStartResult = tObject({ + harId: tString + }); + scheme.TracingHarExportParams = tObject({ + harId: tOptional(tString), + mode: tEnum(["archive", "entries"]) + }); + scheme.TracingHarExportResult = tObject({ + artifact: tOptional(tChannel(["Artifact"])), + entries: tOptional(tArray(tType("NameValue"))) + }); + scheme.WorkerInitializer = tObject({ + url: tString + }); + scheme.WorkerConsoleEvent = tObject({ + type: tString, + text: tString, + args: tArray(tChannel(["ElementHandle", "JSHandle"])), + location: tObject({ + url: tString, + lineNumber: tInt, + columnNumber: tInt + }), + timestamp: tFloat + }); + scheme.WorkerCloseEvent = tOptional(tObject({})); + scheme.WorkerDisconnectParams = tObject({ + reason: tOptional(tString) + }); + scheme.WorkerDisconnectResult = 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.WorkerUpdateSubscriptionParams = tObject({ + event: tEnum(["console"]), + enabled: tBoolean + }); + scheme.WorkerUpdateSubscriptionResult = tOptional(tObject({})); + } +}); + +// packages/playwright-core/src/server/dispatchers/dispatcher.ts +function setMaxDispatchersForTest(value2) { + maxDispatchersOverride = value2; +} +function maxDispatchersForBucket(gcBucket) { + return maxDispatchersOverride ?? { + "JSHandle": 1e5, + "ElementHandle": 1e5 + }[gcBucket] ?? 1e4; +} +var import_events5, metadataValidator, maxDispatchersOverride, Dispatcher, RootDispatcher, DispatcherConnection; +var init_dispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/dispatcher.ts"() { + "use strict"; + import_events5 = require("events"); + init_protocolMetainfo(); + init_eventsHelper(); + init_debug(); + init_assert(); + init_time(); + init_stackTrace(); + init_validator(); + init_errors(); + init_instrumentation(); + init_protocolError(); + init_callLog(); + init_progress(); + metadataValidator = createMetadataValidator(); + Dispatcher = class extends import_events5.EventEmitter { + constructor(parent, object, type3, initializer, gcBucket) { + super(); + this._dispatchers = /* @__PURE__ */ new Map(); + this._disposed = false; + this._eventListeners = []; + this._activeProgressControllers = /* @__PURE__ */ new Set(); + 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 = type3; + this._object = object; + this._gcBucket = gcBucket ?? type3; + 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, type3, 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 _runCommand(callMetadata, method, validParams) { + const controller = ProgressController.createForSdkObject(this._object, callMetadata); + this._activeProgressControllers.add(controller); + try { + return await controller.run((progress2) => this[method](validParams, progress2), validParams?.timeout); + } finally { + this._activeProgressControllers.delete(controller); + } + } + _dispatchEvent(method, params2) { + if (this._disposed) { + if (isUnderTest()) + throw new Error(`${this._guid} is sending "${String(method)}" event after being disposed`); + return; + } + this.connection.sendEvent(this, method, params2); + } + _dispose(reason) { + this._disposeRecursively(new TargetClosedError(this._object.closeReason())); + this.connection.sendDispose(this, reason); + } + _onDispose() { + } + async stopPendingOperations(error) { + const controllers = []; + const collect = (dispatcher) => { + controllers.push(...dispatcher._activeProgressControllers); + for (const child of [...dispatcher._dispatchers.values()]) + collect(child); + }; + collect(this); + await Promise.all(controllers.map((controller) => controller.abort(error))); + } + _disposeRecursively(error) { + assert(!this._disposed, `${this._guid} is disposed more than once`); + for (const controller of this._activeProgressControllers) { + if (!controller.metadata.potentiallyClosesScope) + controller.abort(error).catch(() => { + }); + } + this._onDispose(); + this._disposed = true; + eventsHelper.removeEventListeners(this._eventListeners); + this._parent?._dispatchers.delete(this._guid); + const list = this.connection._dispatchersByBucket.get(this._gcBucket); + 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(error); + this._dispatchers.clear(); + } + _debugScopeState() { + return { + _guid: this._guid, + objects: Array.from(this._dispatchers.values()).map((o) => o._debugScopeState()) + }; + } + async waitForEventInfo() { + } + }; + RootDispatcher = class extends Dispatcher { + constructor(connection, createPlaywright2) { + super(connection, createRootSdkObject(), "Root", {}); + this.createPlaywright = createPlaywright2; + this._initialized = false; + } + async initialize(params2, progress2) { + assert(this.createPlaywright); + assert(!this._initialized); + this._initialized = true; + return { + playwright: await progress2.race(this.createPlaywright(this, params2)) + }; + } + }; + DispatcherConnection = class { + 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, params2) { + const validator = findValidator(dispatcher._type, event, "Event"); + params2 = validator(params2, "", this._validatorToWireContext()); + this.onmessage({ guid: dispatcher._guid, method: event, params: params2 }); + } + sendCreate(parent, type3, guid, initializer) { + const validator = findValidator(type3, "", "Initializer"); + initializer = validator(initializer, "", this._validatorToWireContext()); + this.onmessage({ guid: parent._guid, method: "__create__", params: { type: type3, 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, path59, context2) { + if (arg && typeof arg === "object" && typeof arg.guid === "string") { + const guid = arg.guid; + const dispatcher = this._dispatcherByGuid.get(guid); + if (!dispatcher) + throw new ValidationError(`${path59}: no object with guid ${guid}`); + if (names !== "*" && !names.includes(dispatcher._type)) + throw new ValidationError(`${path59}: object with guid ${guid} has type ${dispatcher._type}, expected ${names.toString()}`); + return dispatcher; + } + throw new ValidationError(`${path59}: expected guid for ${names.toString()}`); + } + _tChannelImplToWire(names, arg, path59, context2) { + if (arg instanceof Dispatcher) { + if (names !== "*" && !names.includes(arg._type)) + throw new ValidationError(`${path59}: dispatcher with guid ${arg._guid} has type ${arg._type}, expected ${names.toString()}`); + return { guid: arg._guid }; + } + throw new ValidationError(`${path59}: 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) { + const { id, guid, method, params: params2, metadata } = message; + const dispatcher = this._dispatcherByGuid.get(guid); + if (!dispatcher) { + this.onmessage({ id, error: serializeError(new TargetClosedError(void 0)) }); + return; + } + let validParams; + let validMetadata; + try { + const validator = findValidator(dispatcher._type, method, "Params"); + const validatorContext = this._validatorFromWireContext(); + validParams = validator(params2, "", 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(e) }); + return; + } + const metainfo = getMetainfo({ type: dispatcher._type, method }); + if (metainfo?.internal) { + validMetadata.internal = true; + } + const sdkObject = dispatcher._object; + const callMetadata = { + id: `call@${id}`, + location: validMetadata.location, + title: validMetadata.title, + internal: validMetadata.internal, + stepId: validMetadata.stepId, + objectId: sdkObject.guid, + pageId: sdkObject.attribution?.page?.guid, + frameId: sdkObject.attribution?.frame?.guid, + startTime: monotonicTime(), + endTime: 0, + type: dispatcher._type, + method, + params: params2 || {}, + log: [] + }; + if (params2?.info?.waitId) { + const info = params2.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.instrumentation.onBeforeCall(sdkObject, callMetadata); + const response2 = { id }; + try { + if (this._dispatcherByGuid.get(guid) !== dispatcher) + throw new TargetClosedError(sdkObject.closeReason()); + const result2 = await dispatcher._runCommand(callMetadata, method, validParams); + const validator = findValidator(dispatcher._type, method, "Result"); + response2.result = validator(result2, "", this._validatorToWireContext()); + callMetadata.result = result2; + } catch (e) { + if (isTargetClosedError(e)) { + const reason = sdkObject.closeReason(); + if (reason) + rewriteErrorMessage(e, reason); + } else if (isProtocolError(e)) { + if (e.type === "closed") + e = new TargetClosedError(sdkObject.closeReason(), e.browserLogMessage()); + else if (e.type === "crashed") + rewriteErrorMessage(e, "Target crashed " + e.browserLogMessage()); + } + response2.error = serializeError(e); + callMetadata.error = response2.error; + } finally { + callMetadata.endTime = monotonicTime(); + await sdkObject.instrumentation.onAfterCall(sdkObject, callMetadata); + if (metainfo?.slowMo) + await this._doSlowMo(sdkObject); + } + if (response2.error) + response2.log = compressCallLog(callMetadata.log); + this.onmessage(response2); + } + async _doSlowMo(sdkObject) { + const slowMo = sdkObject.attribution.browser?.options.slowMo; + if (slowMo) + await new Promise((f) => setTimeout(f, slowMo)); + } + }; + } +}); + +// packages/playwright-core/src/server/har/harTracer.ts +function createHarEntry(pageRef, method, url2, frameref, options2) { + const harEntry = { + pageref: pageRef, + startedDateTime: (/* @__PURE__ */ new Date()).toISOString(), + time: -1, + request: { + method, + url: url2.toString(), + httpVersion: FALLBACK_HTTP_VERSION, + cookies: [], + headers: [], + queryString: [...url2.searchParams].map((e) => ({ name: e[0], value: e[1] })), + headersSize: -1, + bodySize: -1 + }, + response: { + status: -1, + statusText: "", + httpVersion: FALLBACK_HTTP_VERSION, + cookies: [], + headers: [], + content: { + size: -1, + mimeType: "x-unknown" + }, + headersSize: -1, + bodySize: -1, + redirectURL: "", + _transferSize: options2.omitSizes ? void 0 : -1 + }, + cache: {}, + timings: { + send: -1, + wait: -1, + receive: -1 + }, + _frameref: options2.includeTraceInfo ? frameref : void 0, + _monotonicTime: options2.includeTraceInfo ? monotonicTime() : void 0 + }; + return harEntry; +} +function parseCookie(c) { + const cookie = { + name: "", + value: "" + }; + let first = true; + for (const pair of c.split(/; */)) { + const indexOfEquals = pair.indexOf("="); + const name = indexOfEquals !== -1 ? pair.substr(0, indexOfEquals).trim() : pair.trim(); + const value2 = indexOfEquals !== -1 ? pair.substr(indexOfEquals + 1, pair.length).trim() : ""; + if (first) { + first = false; + cookie.name = name; + cookie.value = value2; + continue; + } + if (name === "Domain") + cookie.domain = value2; + if (name === "Expires") + cookie.expires = safeDateToISOString(value2); + if (name === "HttpOnly") + cookie.httpOnly = true; + if (name === "Max-Age") + cookie.expires = safeDateToISOString(Date.now() + +value2 * 1e3); + if (name === "Path") + cookie.path = value2; + if (name === "SameSite") + cookie.sameSite = value2; + if (name === "Secure") + cookie.secure = true; + } + return cookie; +} +function safeDateToISOString(value2) { + try { + return new Date(value2).toISOString(); + } catch (e) { + } +} +var mime6, FALLBACK_HTTP_VERSION, HarTracer, startedDateSymbol; +var init_harTracer = __esm({ + "packages/playwright-core/src/server/har/harTracer.ts"() { + "use strict"; + init_manualPromise(); + init_eventsHelper(); + init_assert(); + init_crypto(); + init_time(); + init_mimeType(); + init_urlMatch(); + init_userAgent(); + init_browserContext(); + init_fetch(); + init_frames(); + init_helper(); + init_network2(); + init_progress(); + mime6 = require("./utilsBundle").mime; + FALLBACK_HTTP_VERSION = "HTTP/1.1"; + HarTracer = class { + constructor(context2, page, delegate, options2) { + this._barrierPromises = /* @__PURE__ */ new Set(); + this._pageEntries = /* @__PURE__ */ new Map(); + this._eventListeners = []; + this._started = false; + this._context = context2; + this._page = page; + this._delegate = delegate; + this._options = options2; + if (options2.slimMode) { + options2.omitSecurityDetails = true; + options2.omitCookies = true; + options2.omitTiming = true; + options2.omitServerIP = true; + options2.omitSizes = true; + options2.omitPages = true; + } + this._entrySymbol = Symbol("requestHarEntry"); + this._baseURL = context2 instanceof APIRequestContext ? context2._defaultOptions().baseURL : context2._options.baseURL; + } + start(options2) { + if (this._started) + return; + this._options.omitScripts = options2.omitScripts; + this._started = true; + const apiRequest = this._context instanceof APIRequestContext ? this._context : this._context.fetchRequest; + this._eventListeners = [ + eventsHelper.addEventListener(apiRequest, APIRequestContext.Events.Request, (event) => this._onAPIRequest(event)), + eventsHelper.addEventListener(apiRequest, APIRequestContext.Events.RequestFinished, (event) => this._onAPIRequestFinished(event)) + ]; + if (this._context instanceof BrowserContext) { + this._eventListeners.push( + eventsHelper.addEventListener(this._context, BrowserContext.Events.Page, (page) => this._createPageEntryIfNeeded(page)), + eventsHelper.addEventListener(this._context, BrowserContext.Events.Request, (request2) => this._onRequest(request2)), + eventsHelper.addEventListener(this._context, BrowserContext.Events.RequestFinished, ({ request: request2, response: response2 }) => this._onRequestFinished(request2, response2).catch(() => { + })), + eventsHelper.addEventListener(this._context, BrowserContext.Events.RequestFailed, (request2) => this._onRequestFailed(request2)), + eventsHelper.addEventListener(this._context, BrowserContext.Events.Response, (response2) => this._onResponse(response2)), + eventsHelper.addEventListener(this._context, BrowserContext.Events.RequestAborted, (request2) => this._onRequestAborted(request2)), + eventsHelper.addEventListener(this._context, BrowserContext.Events.RequestFulfilled, (request2) => this._onRequestFulfilled(request2)), + eventsHelper.addEventListener(this._context, BrowserContext.Events.RequestContinued, (request2) => this._onRequestContinued(request2)) + ); + for (const page of this._context.pages()) + this._createPageEntryIfNeeded(page); + } + } + _shouldIncludeEntryWithUrl(urlString) { + return !this._options.urlFilter || urlMatches(this._baseURL, urlString, this._options.urlFilter); + } + _entryForRequest(request2) { + return request2[this._entrySymbol]; + } + _createPageEntryIfNeeded(page) { + if (!page) + return; + if (this._options.omitPages) + return; + if (this._page && page !== this._page) + return; + let pageEntry = this._pageEntries.get(page); + if (!pageEntry) { + const date = /* @__PURE__ */ new Date(); + pageEntry = { + startedDateTime: date.toISOString(), + id: page.guid, + title: "", + pageTimings: this._options.omitTiming ? {} : { + onContentLoad: -1, + onLoad: -1 + } + }; + pageEntry[startedDateSymbol] = date; + page.mainFrame().on(Frame.Events.AddLifecycle, (event) => { + if (event === "load") + this._onLoad(page, pageEntry); + if (event === "domcontentloaded") + this._onDOMContentLoaded(page, pageEntry); + }); + this._pageEntries.set(page, pageEntry); + } + return pageEntry; + } + _onDOMContentLoaded(page, pageEntry) { + const promise = page.mainFrame().evaluateExpression(nullProgress, String(() => { + return { + title: document.title, + domContentLoaded: performance.timing.domContentLoadedEventStart + }; + }), { isFunction: true, world: "utility" }).then((result2) => { + pageEntry.title = result2.title; + if (!this._options.omitTiming) + pageEntry.pageTimings.onContentLoad = result2.domContentLoaded; + }).catch(() => { + }); + this._addBarrier(page, promise); + } + _onLoad(page, pageEntry) { + const promise = page.mainFrame().evaluateExpression(nullProgress, String(() => { + return { + title: document.title, + loaded: performance.timing.loadEventStart + }; + }), { isFunction: true, world: "utility" }).then((result2) => { + pageEntry.title = result2.title; + if (!this._options.omitTiming) + pageEntry.pageTimings.onLoad = result2.loaded; + }).catch(() => { + }); + this._addBarrier(page, promise); + } + _addBarrier(target, promise) { + if (!target) + return null; + if (!this._options.waitForContentOnStop) + return; + const race = target.openScope.safeRace(promise); + this._barrierPromises.add(race); + race.then(() => this._barrierPromises.delete(race)); + } + _onAPIRequest(event) { + if (!this._shouldIncludeEntryWithUrl(event.url.toString())) + return; + const harEntry = createHarEntry(void 0, event.method, event.url, void 0, this._options); + harEntry._apiRequest = true; + if (!this._options.omitCookies) + harEntry.request.cookies = event.cookies; + harEntry.request.headers = Object.entries(event.headers).map(([name, value2]) => ({ name, value: value2 })); + harEntry.request.postData = this._postDataForBuffer(event.postData || null, event.headers["content-type"], this._options.content); + if (!this._options.omitSizes) + harEntry.request.bodySize = event.postData?.length || 0; + event[this._entrySymbol] = harEntry; + if (this._started) + this._delegate.onEntryStarted(harEntry); + } + _onAPIRequestFinished(event) { + const harEntry = this._entryForRequest(event.requestEvent); + if (!harEntry) + return; + harEntry.response.status = event.statusCode; + harEntry.response.statusText = event.statusMessage; + harEntry.response.httpVersion = event.httpVersion; + harEntry.response.redirectURL = event.headers.location || ""; + if (!this._options.omitServerIP) { + harEntry.serverIPAddress = event.serverIPAddress; + harEntry._serverPort = event.serverPort; + } + if (!this._options.omitTiming) { + harEntry.timings = event.timings; + this._computeHarEntryTotalTime(harEntry); + } + if (!this._options.omitSecurityDetails) + harEntry._securityDetails = event.securityDetails; + for (let i = 0; i < event.rawHeaders.length; i += 2) { + harEntry.response.headers.push({ + name: event.rawHeaders[i], + value: event.rawHeaders[i + 1] + }); + } + harEntry.response.cookies = this._options.omitCookies ? [] : event.cookies.map((c) => { + return { + ...c, + expires: c.expires === -1 ? void 0 : safeDateToISOString(c.expires) + }; + }); + const content = harEntry.response.content; + const contentType = event.headers["content-type"]; + if (contentType) + content.mimeType = contentType; + this._storeResponseContent(event.body, content, "other"); + if (!this._options.omitSizes) + harEntry.response.bodySize = event.body?.length ?? 0; + if (this._started) + this._delegate.onEntryFinished(harEntry); + } + _onRequest(request2) { + if (!this._shouldIncludeEntryWithUrl(request2.url())) + return; + const page = request2.frame()?._page; + if (this._page && page !== this._page) + return; + const url2 = parseURL2(request2.url()); + if (!url2) + return; + const pageEntry = this._createPageEntryIfNeeded(page); + const harEntry = createHarEntry(pageEntry?.id, request2.method(), url2, request2.frame()?.guid, this._options); + this._recordRequestHeadersAndCookies(harEntry, request2.headers()); + harEntry.request.postData = this._postDataForRequest(request2, this._options.content); + if (!this._options.omitSizes) + harEntry.request.bodySize = request2.bodySize(); + if (request2.redirectedFrom()) { + const fromEntry = this._entryForRequest(request2.redirectedFrom()); + if (fromEntry) + fromEntry.response.redirectURL = request2.url(); + } + request2[this._entrySymbol] = harEntry; + assert(this._started); + this._delegate.onEntryStarted(harEntry); + } + _recordRequestHeadersAndCookies(harEntry, headers) { + if (!this._options.omitCookies) { + harEntry.request.cookies = []; + for (const header of headers.filter((header2) => header2.name.toLowerCase() === "cookie")) + harEntry.request.cookies.push(...header.value.split(";").map(parseCookie)); + } + harEntry.request.headers = headers; + } + _recordRequestOverrides(harEntry, request2) { + if (!request2.overrides() || !this._options.recordRequestOverrides) + return; + harEntry.request.method = request2.method(); + harEntry.request.url = request2.url(); + harEntry.request.postData = this._postDataForRequest(request2, this._options.content); + this._recordRequestHeadersAndCookies(harEntry, request2.headers()); + } + async _onRequestFinished(request2, response2) { + if (!response2) + return; + const harEntry = this._entryForRequest(request2); + if (!harEntry) + return; + const page = request2.frame()?._page; + if (!this._options.omitServerIP) { + this._addBarrier(page || request2.serviceWorker(), response2.serverAddr(nullProgress).then((server) => { + if (server?.ipAddress) + harEntry.serverIPAddress = server.ipAddress; + if (server?.port) + harEntry._serverPort = server.port; + })); + } + if (!this._options.omitSecurityDetails) { + this._addBarrier(page || request2.serviceWorker(), response2.securityDetails(nullProgress).then((details) => { + if (details) + harEntry._securityDetails = details; + })); + } + const compressionCalculationBarrier = this._options.omitSizes ? void 0 : { + _encodedBodySize: -1, + _decodedBodySize: -1, + barrier: new ManualPromise(), + _check: function() { + if (this._encodedBodySize !== -1 && this._decodedBodySize !== -1) { + harEntry.response.content.compression = Math.max(0, this._decodedBodySize - this._encodedBodySize); + this.barrier.resolve(); + } + }, + setEncodedBodySize: function(encodedBodySize) { + this._encodedBodySize = encodedBodySize; + this._check(); + }, + setDecodedBodySize: function(decodedBodySize) { + this._decodedBodySize = decodedBodySize; + this._check(); + } + }; + if (compressionCalculationBarrier) + this._addBarrier(page || request2.serviceWorker(), compressionCalculationBarrier.barrier); + const promise = response2.internalBody().then((buffer) => { + if (this._options.omitScripts && request2.resourceType() === "script") { + compressionCalculationBarrier?.setDecodedBodySize(0); + return; + } + const content = harEntry.response.content; + compressionCalculationBarrier?.setDecodedBodySize(buffer.length); + this._storeResponseContent(buffer, content, request2.resourceType()); + }).catch(() => { + compressionCalculationBarrier?.setDecodedBodySize(0); + }).then(() => { + if (this._started) + this._delegate.onEntryFinished(harEntry); + }); + this._addBarrier(page || request2.serviceWorker(), promise); + this._addBarrier(page || request2.serviceWorker(), response2.httpVersion(nullProgress).then((httpVersion) => { + harEntry.request.httpVersion = httpVersion; + harEntry.response.httpVersion = httpVersion; + })); + const timing = response2.timing(); + harEntry.timings.receive = response2.request()._responseEndTiming !== -1 ? helper.millisToRoundishMillis(response2.request()._responseEndTiming - timing.responseStart) : -1; + this._computeHarEntryTotalTime(harEntry); + if (!this._options.omitSizes) { + this._addBarrier(page || request2.serviceWorker(), response2.sizes(nullProgress).then((sizes) => { + harEntry.response.bodySize = sizes.responseBodySize; + harEntry.response.headersSize = sizes.responseHeadersSize; + harEntry.response._transferSize = sizes.transferSize; + harEntry.request.headersSize = sizes.requestHeadersSize; + compressionCalculationBarrier?.setEncodedBodySize(sizes.responseBodySize); + })); + } + } + async _onRequestFailed(request2) { + const harEntry = this._entryForRequest(request2); + if (!harEntry) + return; + if (request2._failureText !== null) + harEntry.response._failureText = request2._failureText; + this._recordRequestOverrides(harEntry, request2); + if (this._started) + this._delegate.onEntryFinished(harEntry); + } + _onRequestAborted(request2) { + const harEntry = this._entryForRequest(request2); + if (harEntry) + harEntry._wasAborted = true; + } + _onRequestFulfilled(request2) { + const harEntry = this._entryForRequest(request2); + if (harEntry) + harEntry._wasFulfilled = true; + } + _onRequestContinued(request2) { + const harEntry = this._entryForRequest(request2); + if (harEntry) + harEntry._wasContinued = true; + } + _storeResponseContent(buffer, content, resourceType) { + if (!buffer) { + content.size = 0; + return; + } + if (!this._options.omitSizes) + content.size = buffer.length; + if (this._options.content === "embed") { + if (isTextualMimeType(content.mimeType) && resourceType !== "font") { + content.text = buffer.toString(); + } else { + content.text = buffer.toString("base64"); + content.encoding = "base64"; + } + } else if (this._options.content === "attach") { + const sha1 = calculateSha1(buffer) + "." + (mime6.getExtension(content.mimeType) || "dat"); + if (this._options.includeTraceInfo) + content._sha1 = sha1; + else + content._file = sha1; + if (this._started) + this._delegate.onContentBlob(sha1, buffer); + } + } + _onResponse(response2) { + const harEntry = this._entryForRequest(response2.request()); + if (!harEntry) + return; + const page = response2.frame()?._page; + const pageEntry = this._createPageEntryIfNeeded(page); + const request2 = response2.request(); + harEntry.response = { + status: response2.status(), + statusText: response2.statusText(), + httpVersion: FALLBACK_HTTP_VERSION, + // These are bad values that will be overwritten below. + cookies: [], + headers: [], + content: { + size: -1, + mimeType: "x-unknown" + }, + headersSize: -1, + bodySize: -1, + redirectURL: "", + _transferSize: this._options.omitSizes ? void 0 : -1 + }; + if (!this._options.omitTiming) { + const startDateTime = pageEntry ? pageEntry[startedDateSymbol].valueOf() : 0; + const timing = response2.timing(); + if (pageEntry && startDateTime > timing.startTime) + pageEntry.startedDateTime = new Date(timing.startTime).toISOString(); + const dns2 = timing.domainLookupEnd !== -1 ? helper.millisToRoundishMillis(timing.domainLookupEnd - timing.domainLookupStart) : -1; + const connect2 = timing.connectEnd !== -1 ? helper.millisToRoundishMillis(timing.connectEnd - timing.connectStart) : -1; + const ssl = timing.connectEnd !== -1 ? helper.millisToRoundishMillis(timing.connectEnd - timing.secureConnectionStart) : -1; + const wait2 = timing.responseStart !== -1 ? helper.millisToRoundishMillis(timing.responseStart - timing.requestStart) : -1; + const receive = -1; + harEntry.timings = { + dns: dns2, + connect: connect2, + ssl, + send: 0, + wait: wait2, + receive + }; + this._computeHarEntryTotalTime(harEntry); + } + this._recordRequestOverrides(harEntry, request2); + this._addBarrier(page || request2.serviceWorker(), request2.rawRequestHeaders(nullProgress).then((headers) => { + this._recordRequestHeadersAndCookies(harEntry, headers); + })); + this._recordResponseHeaders(harEntry, response2.headers()); + this._addBarrier(page || request2.serviceWorker(), response2.rawResponseHeaders(nullProgress).then((headers) => { + this._recordResponseHeaders(harEntry, headers); + })); + } + _recordResponseHeaders(harEntry, headers) { + if (!this._options.omitCookies) { + harEntry.response.cookies = headers.filter((header) => header.name.toLowerCase() === "set-cookie").map((header) => parseCookie(header.value)); + } + harEntry.response.headers = headers; + const contentType = headers.find((header) => header.name.toLowerCase() === "content-type"); + if (contentType) + harEntry.response.content.mimeType = contentType.value; + } + _computeHarEntryTotalTime(harEntry) { + harEntry.time = [ + harEntry.timings.dns, + harEntry.timings.connect, + harEntry.timings.ssl, + harEntry.timings.wait, + harEntry.timings.receive + ].reduce((pre, cur) => (cur || -1) > 0 ? cur + pre : pre, 0); + } + async flush() { + await Promise.all(this._barrierPromises); + } + stop() { + this._started = false; + eventsHelper.removeEventListeners(this._eventListeners); + this._barrierPromises.clear(); + const context2 = this._context instanceof BrowserContext ? this._context : void 0; + const log2 = { + version: "1.2", + creator: { + name: "Playwright", + version: getPlaywrightVersion() + }, + browser: { + name: context2?._browser.options.name || "", + version: context2?._browser.version() || "" + }, + pages: this._pageEntries.size ? Array.from(this._pageEntries.values()) : void 0, + entries: [] + }; + if (!this._options.omitTiming) { + for (const pageEntry of log2.pages || []) { + const startDateTime = pageEntry[startedDateSymbol].valueOf(); + if (typeof pageEntry.pageTimings.onContentLoad === "number" && pageEntry.pageTimings.onContentLoad >= 0) + pageEntry.pageTimings.onContentLoad -= startDateTime; + else + pageEntry.pageTimings.onContentLoad = -1; + if (typeof pageEntry.pageTimings.onLoad === "number" && pageEntry.pageTimings.onLoad >= 0) + pageEntry.pageTimings.onLoad -= startDateTime; + else + pageEntry.pageTimings.onLoad = -1; + } + } + this._pageEntries.clear(); + return log2; + } + _postDataForRequest(request2, content) { + const postData = request2.postDataBuffer(); + if (!postData) + return; + const contentType = request2.headerValue("content-type"); + return this._postDataForBuffer(postData, contentType, content); + } + _postDataForBuffer(postData, contentType, content) { + if (!postData) + return; + contentType ??= "application/octet-stream"; + const result2 = { + mimeType: contentType, + text: "", + params: [] + }; + if (content === "embed" && contentType !== "application/octet-stream") + result2.text = postData.toString(); + if (content === "attach") { + const sha1 = calculateSha1(postData) + "." + (mime6.getExtension(contentType) || "dat"); + if (this._options.includeTraceInfo) + result2._sha1 = sha1; + else + result2._file = sha1; + this._delegate.onContentBlob(sha1, postData); + } + if (contentType === "application/x-www-form-urlencoded") { + const parsed = new URLSearchParams(postData.toString()); + for (const [name, value2] of parsed.entries()) + result2.params.push({ name, value: value2 }); + } + return result2; + } + }; + startedDateSymbol = Symbol("startedDate"); + } +}); + +// packages/playwright-core/src/server/har/harRecorder.ts +var import_path14, HarRecorder; +var init_harRecorder = __esm({ + "packages/playwright-core/src/server/har/harRecorder.ts"() { + "use strict"; + import_path14 = __toESM(require("path")); + init_serializedFS(); + init_artifact(); + init_harTracer(); + HarRecorder = class { + constructor(context2, fallbackDir, harId, page, options2) { + this._fs = new SerializedFS(); + this._isFlushed = false; + this._entries = []; + this._writtenContentEntries = /* @__PURE__ */ new Set(); + this._context = context2; + const isServer = !!context2.attribution.playwright.options.isServer; + this._harFilePath = !isServer && options2.harPath ? options2.harPath : import_path14.default.join(fallbackDir, `${harId}.har`); + if (!isServer && options2.resourcesDir) + this._resourcesDir = options2.resourcesDir; + else if (!isServer && options2.harPath) + this._resourcesDir = import_path14.default.dirname(options2.harPath); + else + this._resourcesDir = import_path14.default.join(fallbackDir, `${harId}-resources`); + const urlFilterRe = options2.urlRegexSource !== void 0 && options2.urlRegexFlags !== void 0 ? new RegExp(options2.urlRegexSource, options2.urlRegexFlags) : void 0; + const content = options2.content || "embed"; + this._tracer = new HarTracer(context2, page, this, { + content, + slimMode: options2.mode === "minimal", + includeTraceInfo: false, + recordRequestOverrides: true, + waitForContentOnStop: true, + urlFilter: urlFilterRe ?? options2.urlGlob + }); + this._tracer.start({ omitScripts: false }); + } + onEntryStarted(entry) { + this._entries.push(entry); + } + onEntryFinished(entry) { + } + onContentBlob(sha1, buffer) { + if (this._writtenContentEntries.has(sha1)) + return; + if (!this._writtenContentEntries.size) + this._fs.mkdir(this._resourcesDir); + this._writtenContentEntries.add(sha1); + this._fs.writeFile( + import_path14.default.join(this._resourcesDir, sha1), + buffer, + true + /* skipIfExists */ + ); + } + async _flush() { + if (this._isFlushed) + return; + this._isFlushed = true; + await this._tracer.flush(); + const log2 = this._tracer.stop(); + log2.entries = this._entries; + this._fs.mkdir(import_path14.default.dirname(this._harFilePath)); + const file = this._harFilePath; + this._fs.writeFile(file, ""); + this._fs.appendFile(file, '{"log":{"version":' + JSON.stringify(log2.version)); + this._fs.appendFile(file, ',"creator":' + JSON.stringify(log2.creator)); + if (log2.browser) + this._fs.appendFile(file, ',"browser":' + JSON.stringify(log2.browser)); + if (log2.pages) { + this._fs.appendFile(file, ',"pages":['); + for (let i = 0; i < log2.pages.length; i++) { + if (i) + this._fs.appendFile(file, ","); + this._fs.appendFile(file, JSON.stringify(log2.pages[i])); + } + this._fs.appendFile(file, "]"); + } + this._fs.appendFile(file, ',"entries":['); + for (let i = 0; i < log2.entries.length; i++) { + if (i) + this._fs.appendFile(file, ","); + this._fs.appendFile(file, JSON.stringify(log2.entries[i])); + } + this._fs.appendFile(file, "]"); + if (log2.comment !== void 0) + this._fs.appendFile(file, ',"comment":' + JSON.stringify(log2.comment)); + this._fs.appendFile( + file, + "}}", + true + /* flush */ + ); + } + async flush() { + await this._flush(); + const error = await this._fs.syncAndGetError(); + if (error) + throw error; + } + async export(mode) { + await this._flush(); + const entries = [{ name: "har.har", value: this._harFilePath }]; + for (const sha1 of this._writtenContentEntries) + entries.push({ name: sha1, value: import_path14.default.join(this._resourcesDir, sha1) }); + const zipPath = this._harFilePath + ".zip"; + if (mode === "archive") + this._fs.zip(entries, zipPath); + const error = await this._fs.syncAndGetError(); + if (error) + throw error; + if (mode === "entries") + return { entries }; + const artifact = new Artifact(this._context, zipPath); + artifact.reportFinished(); + return { artifact }; + } + }; + } +}); + +// packages/playwright-core/src/server/trace/recorder/tracing.ts +function visitTraceEvent(object, sha1s) { + if (Array.isArray(object)) + return object.map((o) => visitTraceEvent(o, sha1s)); + if (object instanceof Dispatcher) + return `<${object._type}>`; + if (object instanceof Buffer) + return ``; + if (object instanceof Date) + return object; + if (typeof object === "object") { + const result2 = {}; + for (const key in object) { + if (key === "sha1" || key === "_sha1" || key.endsWith("Sha1")) { + const sha1 = object[key]; + if (sha1) + sha1s.add(sha1); + } + result2[key] = visitTraceEvent(object[key], sha1s); + } + return result2; + } + return object; +} +function createBeforeActionTraceEvent(metadata, parentId) { + if (metadata.internal || metadata.method.startsWith("tracing")) + return null; + const event = { + type: "before", + callId: metadata.id, + startTime: metadata.startTime, + title: metadata.title, + class: metadata.type, + method: metadata.method, + params: metadata.params, + stepId: metadata.stepId, + pageId: metadata.pageId + }; + if (parentId) + event.parentId = parentId; + return event; +} +function createInputActionTraceEvent(metadata) { + if (metadata.internal || metadata.method.startsWith("tracing")) + return null; + return { + type: "input", + callId: metadata.id, + point: metadata.point + }; +} +function createActionLogTraceEvent(metadata, message) { + if (metadata.internal || metadata.method.startsWith("tracing")) + return null; + return { + type: "log", + callId: metadata.id, + time: monotonicTime(), + message + }; +} +function createAfterActionTraceEvent(metadata) { + if (metadata.internal || metadata.method.startsWith("tracing")) + return null; + return { + type: "after", + callId: metadata.id, + endTime: metadata.endTime, + error: metadata.error?.error, + result: metadata.result, + point: metadata.point + }; +} +var import_fs15, import_os5, import_path15, version, Tracing, throttledRate, unthrottleDuration, ScreencastTracingRecorder; +var init_tracing = __esm({ + "packages/playwright-core/src/server/trace/recorder/tracing.ts"() { + "use strict"; + import_fs15 = __toESM(require("fs")); + import_os5 = __toESM(require("os")); + import_path15 = __toESM(require("path")); + init_protocolMetainfo(); + init_assert(); + init_time(); + init_manualPromise(); + init_eventsHelper(); + init_crypto(); + init_fileUtils(); + init_serializedFS(); + init_userAgent(); + init_snapshotter(); + init_artifact(); + init_browserContext(); + init_dispatcher(); + init_errors(); + init_harRecorder(); + init_harTracer(); + init_instrumentation(); + init_progress(); + version = 8; + Tracing = class extends SdkObject { + constructor(context2, tracesDir) { + super(context2, "tracing"); + this._fs = new SerializedFS(); + this._screencastListeners = []; + this._pageTracingRecorders = /* @__PURE__ */ new Map(); + this._eventListeners = []; + this._isStopping = false; + this._allResources = /* @__PURE__ */ new Set(); + this._pendingHarEntries = /* @__PURE__ */ new Set(); + this._started = false; + this.harRecorders = /* @__PURE__ */ new Map(); + this._context = context2; + this._precreatedTracesDir = tracesDir; + this._harTracer = new HarTracer(context2, null, this, { + content: "attach", + includeTraceInfo: true, + recordRequestOverrides: false, + waitForContentOnStop: false + }); + const testIdAttributeName2 = "selectors" in context2 ? context2.selectors().testIdAttributeName() : void 0; + this._contextCreatedEvent = { + version, + type: "context-options", + origin: "library", + browserName: "", + playwrightVersion: getPlaywrightVersion(), + options: {}, + platform: process.platform, + wallTime: 0, + monotonicTime: 0, + sdkLanguage: this._sdkLanguage(), + testIdAttributeName: testIdAttributeName2, + contextId: context2.guid + }; + if (context2 instanceof BrowserContext) { + this._snapshotter = new Snapshotter(context2, this); + assert(tracesDir, "tracesDir must be specified for BrowserContext"); + this._contextCreatedEvent.browserName = context2._browser.options.name; + this._contextCreatedEvent.channel = context2._browser.options.channel; + this._contextCreatedEvent.options = context2._options; + } + } + _sdkLanguage() { + return this._context instanceof BrowserContext ? this._context._browser.sdkLanguage() : this._context.attribution.playwright.options.sdkLanguage; + } + async resetForReuse(progress2) { + await this.stopChunk(progress2, { mode: "discard" }).catch(() => { + }); + await progress2.race(this._stop()); + if (this._snapshotter) + await progress2.race(this._snapshotter.resetForReuse()); + } + start(progress2, options2) { + if (this._isStopping) + throw new Error("Cannot start tracing while stopping"); + if (this._state) + throw new Error("Tracing has been already started"); + this._contextCreatedEvent.sdkLanguage = this._sdkLanguage(); + const traceName = options2.name || createGuid(); + const tracesDir = this._createTracesDirIfNeeded(); + this._state = { + options: options2, + traceName, + tracesDir, + traceFile: import_path15.default.join(tracesDir, traceName + ".trace"), + networkFile: import_path15.default.join(tracesDir, traceName + ".network"), + resourcesDir: import_path15.default.join(tracesDir, "resources"), + chunkOrdinal: 0, + traceSha1s: /* @__PURE__ */ new Set(), + networkSha1s: /* @__PURE__ */ new Set(), + recording: false, + callIds: /* @__PURE__ */ new Set(), + groupStack: [] + }; + this._fs.mkdir(this._state.resourcesDir); + this._fs.writeFile(this._state.networkFile, ""); + if (options2.snapshots) + this._harTracer.start({ omitScripts: !options2.live }); + this._started = true; + } + async startChunk(progress2, options2 = {}) { + if (this._state && this._state.recording) + await this.stopChunk(progress2, { mode: "discard" }); + if (!this._state) + throw new Error("Must start tracing before starting a new chunk"); + if (this._isStopping) + throw new Error("Cannot start a trace chunk while stopping"); + this._state.recording = true; + this._state.callIds.clear(); + const preserveNetworkResources = this._context instanceof BrowserContext; + if (options2.name && options2.name !== this._state.traceName) + this._changeTraceName(this._state, options2.name, preserveNetworkResources); + else + this._allocateNewTraceFile(this._state); + if (!preserveNetworkResources) + this._fs.writeFile(this._state.networkFile, ""); + this._fs.mkdir(import_path15.default.dirname(this._state.traceFile)); + const event = { + ...this._contextCreatedEvent, + title: options2.title, + wallTime: Date.now(), + monotonicTime: monotonicTime() + }; + this._appendTraceEvent(event); + this._context.instrumentation.addListener(this, this._context); + this._eventListeners.push( + eventsHelper.addEventListener(this._context, BrowserContext.Events.Console, this._onConsoleMessage.bind(this)), + eventsHelper.addEventListener(this._context, BrowserContext.Events.PageError, this._onPageError.bind(this)) + ); + if (this._state.options.screenshots) + this._startScreencast(); + if (this._state.options.snapshots) + await this._snapshotter?.start(progress2); + return { traceName: this._state.traceName }; + } + _currentGroupId() { + return this._state?.groupStack.length ? this._state.groupStack[this._state.groupStack.length - 1] : void 0; + } + group(progress2, name, location2) { + if (!this._state) + return; + const metadata = progress2.metadata; + const stackFrames = []; + const { file, line, column } = location2 ?? metadata.location ?? {}; + if (file) { + stackFrames.push({ + file, + line: line ?? 0, + column: column ?? 0 + }); + } + const event = { + type: "before", + callId: metadata.id, + startTime: metadata.startTime, + title: name, + class: "Tracing", + method: "tracingGroup", + params: {}, + stepId: metadata.stepId, + stack: stackFrames + }; + if (this._currentGroupId()) + event.parentId = this._currentGroupId(); + this._state.groupStack.push(event.callId); + this._appendTraceEvent(event); + } + groupEnd(progress2) { + this._groupEnd(); + } + _groupEnd() { + if (!this._state) + return; + const callId = this._state.groupStack.pop(); + if (!callId) + return; + const event = { + type: "after", + callId, + endTime: monotonicTime() + }; + this._appendTraceEvent(event); + } + _startScreencast() { + if (!(this._context instanceof BrowserContext)) + return; + for (const page of this._context.pages()) + this._startScreencastInPage(page); + this._screencastListeners.push( + eventsHelper.addEventListener(this._context, BrowserContext.Events.Page, this._startScreencastInPage.bind(this)) + ); + } + _stopScreencast() { + eventsHelper.removeEventListeners(this._screencastListeners); + for (const recorder of this._pageTracingRecorders.values()) + recorder.dispose(); + this._pageTracingRecorders.clear(); + } + _allocateNewTraceFile(state) { + const suffix = state.chunkOrdinal ? `-chunk${state.chunkOrdinal}` : ``; + state.chunkOrdinal++; + state.traceFile = import_path15.default.join(state.tracesDir, `${state.traceName}${suffix}.trace`); + } + _changeTraceName(state, name, preserveNetworkResources) { + state.traceName = name; + state.chunkOrdinal = 0; + this._allocateNewTraceFile(state); + const newNetworkFile = import_path15.default.join(state.tracesDir, name + ".network"); + if (preserveNetworkResources) + this._fs.copyFile(state.networkFile, newNetworkFile); + state.networkFile = newNetworkFile; + } + async stop(progress2) { + await progress2.race(this._stop()); + } + async _stop() { + if (!this._state) + return; + if (this._isStopping) + throw new Error(`Tracing is already stopping`); + if (this._state.recording) + throw new Error(`Must stop trace file before stopping tracing`); + this._closeAllGroups(); + this._harTracer.stop(); + this.flushHarEntries(); + await this._fs.syncAndGetError().finally(() => { + this._state = void 0; + }); + } + async deleteTmpTracesDir() { + if (this._tracesTmpDir) + await removeFolders([this._tracesTmpDir]); + } + _createTracesDirIfNeeded() { + if (this._precreatedTracesDir) + return this._precreatedTracesDir; + this._tracesTmpDir = import_fs15.default.mkdtempSync(import_path15.default.join(import_os5.default.tmpdir(), "playwright-tracing-")); + return this._tracesTmpDir; + } + abort() { + this._snapshotter?.dispose(); + this._harTracer.stop(); + } + async flush() { + this.abort(); + for (const harRecorder of this.harRecorders.values()) + await harRecorder.flush(); + await this._fs.syncAndGetError(); + } + harStart(page, options2) { + const harId = createGuid(); + const artifactsDir = this._context instanceof BrowserContext ? this._context._browser.options.artifactsDir : this._createTracesDirIfNeeded(); + this.harRecorders.set(harId, new HarRecorder(this._context, artifactsDir, harId, page, options2)); + return harId; + } + async harExport(progress2, harId, mode) { + const recorder = this.harRecorders.get(harId || ""); + const result2 = await progress2.race(recorder.export(mode)); + this.harRecorders.delete(harId || ""); + return result2; + } + _closeAllGroups() { + while (this._currentGroupId()) + this._groupEnd(); + } + async stopChunk(progress2, params2) { + if (this._isStopping) + throw new Error(`Tracing is already stopping`); + this._isStopping = true; + if (!this._state || !this._state.recording) { + this._isStopping = false; + if (params2.mode !== "discard") + throw new Error(`Must start tracing before stopping`); + return {}; + } + this._closeAllGroups(); + this._context.instrumentation.removeListener(this); + eventsHelper.removeEventListeners(this._eventListeners); + if (this._state.options.screenshots) + this._stopScreencast(); + if (this._state.options.snapshots) + this._snapshotter?.stop(); + this.flushHarEntries(); + const newNetworkFile = import_path15.default.join(this._state.tracesDir, this._state.traceName + `-pwnetcopy-${this._state.chunkOrdinal}.network`); + const entries = []; + entries.push({ name: "trace.trace", value: this._state.traceFile }); + entries.push({ name: "trace.network", value: newNetworkFile }); + for (const sha1 of /* @__PURE__ */ new Set([...this._state.traceSha1s, ...this._state.networkSha1s])) + entries.push({ name: import_path15.default.join("resources", sha1), value: import_path15.default.join(this._state.resourcesDir, sha1) }); + this._state.traceSha1s = /* @__PURE__ */ new Set(); + if (params2.mode === "discard") { + this._isStopping = false; + this._state.recording = false; + return {}; + } + this._fs.copyFile(this._state.networkFile, newNetworkFile); + const zipFileName = this._state.traceFile + ".zip"; + if (params2.mode === "archive") + this._fs.zip(entries, zipFileName); + let error; + try { + await progress2.race(this._fs.syncAndGetError()); + } catch (e) { + error = e; + } + this._isStopping = false; + if (this._state) + this._state.recording = false; + if (error) { + if (!isAbortError(error) && this._context instanceof BrowserContext && !this._context._browser.isConnected()) + return {}; + throw error; + } + if (params2.mode === "entries") + return { entries }; + const artifact = new Artifact(this._context, zipFileName); + artifact.reportFinished(); + return { artifact }; + } + async _captureSnapshot(snapshotName, sdkObject, metadata) { + if (!snapshotName || !sdkObject.attribution.page) + return; + await this._snapshotter?.captureSnapshot(sdkObject.attribution.page, metadata.id, snapshotName).catch(() => { + }); + } + _shouldCaptureSnapshot(sdkObject, metadata, phase) { + if (!sdkObject.attribution.page || !this._snapshotter?.started()) + return; + const metainfo = getMetainfo(metadata); + if (!metainfo?.snapshot) + return false; + switch (phase) { + case "before": + return !metainfo.input || !!metainfo.isAutoWaiting; + case "input": + return !!metainfo.input; + case "after": + return true; + } + } + onBeforeCall(sdkObject, metadata, parentId) { + const event = createBeforeActionTraceEvent(metadata, parentId ?? this._currentGroupId()); + if (!event) + return Promise.resolve(); + this._temporarilyDisableThrottling(sdkObject.attribution.page); + if (this._shouldCaptureSnapshot(sdkObject, metadata, "before")) + event.beforeSnapshot = `before@${metadata.id}`; + this._state?.callIds.add(metadata.id); + this._appendTraceEvent(event); + return this._captureSnapshot(event.beforeSnapshot, sdkObject, metadata); + } + onBeforeInputAction(sdkObject, metadata) { + if (!this._state?.callIds.has(metadata.id)) + return Promise.resolve(); + const event = createInputActionTraceEvent(metadata); + if (!event) + return Promise.resolve(); + this._temporarilyDisableThrottling(sdkObject.attribution.page); + if (this._shouldCaptureSnapshot(sdkObject, metadata, "input")) + event.inputSnapshot = `input@${metadata.id}`; + this._appendTraceEvent(event); + return this._captureSnapshot(event.inputSnapshot, sdkObject, metadata); + } + onCallLog(sdkObject, metadata, logName, message) { + if (!this._state?.callIds.has(metadata.id)) + return; + if (metadata.internal) + return; + if (logName !== "api") + return; + const event = createActionLogTraceEvent(metadata, message); + if (event) + this._appendTraceEvent(event); + } + onAfterCall(sdkObject, metadata) { + if (!this._state?.callIds.has(metadata.id)) + return Promise.resolve(); + this._state?.callIds.delete(metadata.id); + const event = createAfterActionTraceEvent(metadata); + if (!event) + return Promise.resolve(); + this._temporarilyDisableThrottling(sdkObject.attribution.page); + if (this._shouldCaptureSnapshot(sdkObject, metadata, "after")) + event.afterSnapshot = `after@${metadata.id}`; + this._appendTraceEvent(event); + return this._captureSnapshot(event.afterSnapshot, sdkObject, metadata); + } + onEntryStarted(entry) { + this._pendingHarEntries.add(entry); + } + onEntryFinished(entry) { + this._pendingHarEntries.delete(entry); + const event = { type: "resource-snapshot", snapshot: entry }; + const visited = visitTraceEvent(event, this._state.networkSha1s); + this._fs.appendFile( + this._state.networkFile, + JSON.stringify(visited) + "\n", + true + /* flush */ + ); + } + flushHarEntries() { + const harLines = []; + for (const entry of this._pendingHarEntries) { + const event = { type: "resource-snapshot", snapshot: entry }; + const visited = visitTraceEvent(event, this._state.networkSha1s); + harLines.push(JSON.stringify(visited)); + } + this._pendingHarEntries.clear(); + if (harLines.length) + this._fs.appendFile( + this._state.networkFile, + harLines.join("\n") + "\n", + true + /* flush */ + ); + } + onContentBlob(sha1, buffer) { + this._appendResource(sha1, buffer); + } + onSnapshotterBlob(blob) { + this._appendResource(blob.sha1, blob.buffer); + } + onFrameSnapshot(snapshot3) { + this._appendTraceEvent({ type: "frame-snapshot", snapshot: snapshot3 }); + } + _onConsoleMessage(message) { + const event = { + type: "console", + messageType: message.type(), + text: message.text(), + args: message.args().map((a) => ({ preview: a.toString(), value: a.rawValue() })), + location: message.location(), + time: monotonicTime(), + pageId: message.page()?.guid + }; + this._appendTraceEvent(event); + } + onDialog(dialog) { + const event = { + type: "event", + time: monotonicTime(), + class: "BrowserContext", + method: "dialog", + params: { pageId: dialog.page().guid, type: dialog.type(), message: dialog.message(), defaultValue: dialog.defaultValue() } + }; + this._appendTraceEvent(event); + } + onDownload(page, download) { + const event = { + type: "event", + time: monotonicTime(), + class: "BrowserContext", + method: "download", + params: { pageId: page.guid, url: download.url, suggestedFilename: download.suggestedFilename() } + }; + this._appendTraceEvent(event); + } + onPageOpen(page) { + const event = { + type: "event", + time: monotonicTime(), + class: "BrowserContext", + method: "page", + params: { pageId: page.guid, openerPageId: page.opener()?.guid } + }; + this._appendTraceEvent(event); + } + onPageClose(page) { + const event = { + type: "event", + time: monotonicTime(), + class: "BrowserContext", + method: "pageClosed", + params: { pageId: page.guid } + }; + this._appendTraceEvent(event); + } + dispose(params2) { + if (this._started) + this.stopChunk(nullProgress, params2).then(() => this._stop()).catch(() => { + }); + this._started = false; + } + _onPageError(pageError, page) { + const event = { + type: "event", + time: monotonicTime(), + class: "BrowserContext", + method: "pageError", + params: { + error: serializeError(pageError.error), + location: { + url: pageError.location.url, + line: pageError.location.lineNumber, + column: pageError.location.columnNumber + } + }, + pageId: page.guid + }; + this._appendTraceEvent(event); + } + _temporarilyDisableThrottling(page) { + if (page) + this._pageTracingRecorders.get(page)?.temporarilyDisableThrottling(); + } + _startScreencastInPage(page) { + const prefix = page.guid; + const onFrame = (params2) => { + const suffix = Date.now(); + const sha1 = `${prefix}-${suffix}.jpeg`; + const event = { + type: "screencast-frame", + pageId: page.guid, + sha1, + width: params2.viewportWidth, + height: params2.viewportHeight, + timestamp: monotonicTime(), + frameSwapWallTime: params2.frameSwapWallTime + }; + this._appendResource(sha1, params2.buffer); + this._appendTraceEvent(event); + }; + this._pageTracingRecorders.set(page, new ScreencastTracingRecorder(page.screencast, onFrame)); + } + _appendTraceEvent(event) { + const visited = visitTraceEvent(event, this._state.traceSha1s); + const flush = this._state.options.live || event.type !== "event" && event.type !== "console" && event.type !== "log"; + this._fs.appendFile(this._state.traceFile, JSON.stringify(visited) + "\n", flush); + } + _appendResource(sha1, buffer) { + if (this._allResources.has(sha1)) + return; + this._allResources.add(sha1); + const resourcePath = import_path15.default.join(this._state.resourcesDir, sha1); + this._fs.writeFile( + resourcePath, + buffer, + true + /* skipIfExists */ + ); + } + }; + throttledRate = 200; + unthrottleDuration = 500; + ScreencastTracingRecorder = class { + constructor(screencast, onFrame) { + this._unthrottledUntil = 0; + this._screencast = screencast; + this._client = { + onFrame: (frame) => { + const time = monotonicTime(); + if (time < this._unthrottledUntil) { + onFrame(frame); + return; + } + if (this._pendingAck) + return; + onFrame(frame); + this._pendingAck = new ManualPromise(); + this._timer = setTimeout(() => this._clearPendingAck(), throttledRate); + return this._pendingAck; + }, + gracefulClose: () => this.dispose(), + dispose: () => this.dispose() + }; + this._screencast.addClient(this._client); + } + dispose() { + this._screencast.removeClient(this._client); + this._clearPendingAck(); + } + temporarilyDisableThrottling() { + this._unthrottledUntil = monotonicTime() + unthrottleDuration; + this._clearPendingAck(); + } + _clearPendingAck() { + this._pendingAck?.resolve(); + this._pendingAck = void 0; + if (this._timer) { + clearTimeout(this._timer); + this._timer = void 0; + } + } + }; + } +}); + +// packages/playwright-core/src/server/fetch.ts +function toHeadersArray(rawHeaders) { + const result2 = []; + for (let i = 0; i < rawHeaders.length; i += 2) + result2.push({ name: rawHeaders[i], value: rawHeaders[i + 1] }); + return result2; +} +function parseCookie2(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(params2, headers) { + assert((params2.postData ? 1 : 0) + (params2.jsonData ? 1 : 0) + (params2.formData ? 1 : 0) + (params2.multipartData ? 1 : 0) <= 1, `Only one of 'data', 'form' or 'multipart' can be specified`); + if (params2.jsonData !== void 0) { + setHeader(headers, "content-type", "application/json", true); + return Buffer.from(params2.jsonData, "utf8"); + } else if (params2.formData) { + const searchParams = new URLSearchParams(); + for (const { name, value: value2 } of params2.formData) + searchParams.append(name, value2); + setHeader(headers, "content-type", "application/x-www-form-urlencoded", true); + return Buffer.from(searchParams.toString(), "utf8"); + } else if (params2.multipartData) { + const formData = new MultipartFormData(); + for (const field of params2.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 (params2.postData !== void 0) { + setHeader(headers, "content-type", "application/octet-stream", true); + return params2.postData; + } + return void 0; +} +function setHeader(headers, name, value2, keepExisting = false) { + const existing = Object.entries(headers).find((pair) => pair[0].toLowerCase() === name.toLowerCase()); + if (!existing) + headers[name] = value2; + else if (!keepExisting) + headers[existing[0]] = value2; +} +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) { + const existing = Object.entries(headers).find((pair) => pair[0].toLowerCase() === name.toLowerCase()); + if (existing) + delete headers[existing[0]]; +} +function setBasicAuthorizationHeader(headers, credentials) { + const { username, password } = credentials; + const encoded = Buffer.from(`${username || ""}:${password || ""}`).toString("base64"); + setHeader(headers, "authorization", `Basic ${encoded}`); +} +var import_http3, import_https3, import_stream4, import_tls3, zlib, APIRequestContext, SafeEmptyStreamTransform, BrowserContextAPIRequestContext, GlobalAPIRequestContext, redirectStatus; +var init_fetch = __esm({ + "packages/playwright-core/src/server/fetch.ts"() { + "use strict"; + import_http3 = __toESM(require("http")); + import_https3 = __toESM(require("https")); + import_stream4 = require("stream"); + import_tls3 = require("tls"); + zlib = __toESM(require("zlib")); + init_crypto(); + init_happyEyeballs(); + init_assert(); + init_urlMatch(); + init_eventsHelper(); + init_time(); + init_network(); + init_userAgent(); + init_browserContext(); + init_cookieStore(); + init_formData(); + init_instrumentation(); + init_progress(); + init_socksClientCertificatesInterceptor(); + init_tracing(); + APIRequestContext = class _APIRequestContext extends SdkObject { + constructor(parent) { + super(parent, "request-context"); + this.fetchResponses = /* @__PURE__ */ new Map(); + this.fetchLog = /* @__PURE__ */ new Map(); + _APIRequestContext.allInstances.add(this); + } + static { + this.Events = { + Dispose: "dispose", + Request: "request", + RequestFinished: "requestfinished" + }; + } + static { + this.allInstances = /* @__PURE__ */ new Set(); + } + static findResponseBody(guid) { + for (const request2 of _APIRequestContext.allInstances) { + const body = request2.fetchResponses.get(guid); + if (body) + return body; + } + return void 0; + } + fetchResponseBody(progress2, fetchUid) { + return this.fetchResponses.get(fetchUid); + } + fetchLogForUid(progress2, fetchUid) { + return this.fetchLog.get(fetchUid) || []; + } + disposeResponse(progress2, fetchUid) { + this._disposeResponse(fetchUid); + } + _disposeImpl() { + _APIRequestContext.allInstances.delete(this); + this.fetchResponses.clear(); + this.fetchLog.clear(); + this.emit(_APIRequestContext.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(progress2, params2) { + const defaults = this._defaultOptions(); + const headers = { + "user-agent": defaults.userAgent, + "accept": "*/*", + "accept-encoding": "gzip,deflate,br" + }; + if (defaults.extraHTTPHeaders) { + for (const { name, value: value2 } of defaults.extraHTTPHeaders) + setHeader(headers, name, value2); + } + if (params2.headers) { + for (const { name, value: value2 } of params2.headers) + setHeader(headers, name, value2); + } + const requestUrl = new URL(constructURLBasedOnBaseURL(defaults.baseURL, params2.url)); + if (params2.encodedParams) { + requestUrl.search = params2.encodedParams; + } else if (params2.params) { + for (const { name, value: value2 } of params2.params) + requestUrl.searchParams.append(name, value2); + } + const credentials = this._getHttpCredentials(requestUrl); + if (credentials?.send === "always") + setBasicAuthorizationHeader(headers, credentials); + const method = params2.method?.toUpperCase() || "GET"; + const proxy = defaults.proxy; + let agent; + if (proxy?.server !== "per-context") + agent = createProxyAgent(proxy, requestUrl); + let maxRedirects = params2.maxRedirects ?? (defaults.maxRedirects ?? 20); + maxRedirects = maxRedirects === 0 ? -1 : maxRedirects; + const options2 = { + method, + headers, + agent, + maxRedirects, + ...getMatchingTLSOptionsForOrigin(this._defaultOptions().clientCertificates, requestUrl.origin), + __testHookLookup: params2.__testHookLookup + }; + if (params2.ignoreHTTPSErrors || defaults.ignoreHTTPSErrors) + options2.rejectUnauthorized = false; + const postData = serializePostData(params2, headers); + if (postData) + setHeader(headers, "content-length", String(postData.byteLength)); + const fetchResponse = await this._sendRequestWithRetries(progress2, requestUrl, options2, postData, params2.maxRetries); + const fetchUid = this._storeResponseBody(fetchResponse.body); + this.fetchLog.set(fetchUid, progress2.metadata.log); + const failOnStatusCode = params2.failOnStatusCode !== void 0 ? params2.failOnStatusCode : !!defaults.failOnStatusCode; + if (failOnStatusCode && (fetchResponse.status < 200 || fetchResponse.status >= 400)) { + let responseText = ""; + if (fetchResponse.body.byteLength) { + let text2 = fetchResponse.body.toString("utf8"); + if (text2.length > 1e3) + text2 = text2.substring(0, 997) + "..."; + responseText = ` +Response text: +${text2}`; + } + 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 = parseCookie2(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(progress2, url2, headers) { + if (getHeader(headers, "cookie") !== void 0) + return; + const contextCookies = await this.cookies(progress2, 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 ??= 0; + let backoff = 250; + for (let i = 0; i <= maxRetries; i++) { + try { + return await this._sendRequest(progress2, url2, options2, postData); + } catch (e) { + if (isAbortError(e)) + throw e; + e = rewriteOpenSSLErrorIfNeeded(e); + if (maxRetries === 0) + throw e; + if (i === maxRetries) + 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 progress2.wait(backoff); + backoff *= 2; + } + } + throw new Error("Unreachable"); + } + async _sendRequest(progress2, url2, options2, postData) { + await this._updateRequestCookieHeader(progress2, url2, options2.headers); + const requestCookies = getHeader(options2.headers, "cookie")?.split(";").map((p) => { + const indexOfEquals = p.indexOf("="); + const name = indexOfEquals !== -1 ? p.substring(0, indexOfEquals).trim() : p.trim(); + const value2 = indexOfEquals !== -1 ? p.substring(indexOfEquals + 1).trim() : ""; + return { name, value: value2 }; + }) || []; + const requestEvent = { + url: url2, + method: options2.method, + headers: options2.headers, + cookies: requestCookies, + postData + }; + this.emit(_APIRequestContext.Events.Request, requestEvent); + let destroyRequest; + progress2.setAllowConcurrentOrNestedRaces(true); + const resultPromise = new Promise((fulfill, reject) => { + const requestConstructor = (url2.protocol === "https:" ? import_https3.default : import_http3.default).request; + const agent = options2.agent || (url2.protocol === "https:" ? httpsHappyEyeballsAgent : httpHappyEyeballsAgent); + const requestOptions = { ...options2, agent }; + 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(_APIRequestContext.Events.RequestFinished, requestFinishedEvent); + }; + progress2.log(`\u2190 ${response2.statusCode} ${response2.statusMessage}`); + for (const [name, value2] of Object.entries(response2.headers)) + progress2.log(` ${name}: ${value2}`); + 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.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, + __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 (error) { + reject(new Error(`uri requested responds with an invalid redirect URL: ${locationHeaderValue}`)); + request2.destroy(); + return; + } + if (headers["host"]) + headers["host"] = locationURL.host; + if (locationURL.origin !== url2.origin) + removeHeader(headers, "authorization"); + Object.assign( + redirectOptions, + getMatchingTLSOptionsForOrigin(this._defaultOptions().clientCertificates, locationURL.origin) + ); + 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?.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 encoding = response2.headers["content-encoding"]; + if (encoding === "gzip" || encoding === "x-gzip") { + transform2 = zlib.createGunzip({ + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH + }); + } else if (encoding === "br") { + transform2 = zlib.createBrotliDecompress({ + flush: zlib.constants.BROTLI_OPERATION_FLUSH, + finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH + }); + } else if (encoding === "deflate") { + transform2 = zlib.createInflate(); + } + if (transform2) { + const emptyStreamTransform = new SafeEmptyStreamTransform(notifyBodyFinished); + body = (0, import_stream4.pipeline)(response2, emptyStreamTransform, transform2, (e) => { + if (e) + reject(new Error(`failed to decompress '${encoding}' encoding: ${e.message}`)); + }); + body.on("error", (e) => reject(new Error(`failed to decompress '${encoding}' encoding: ${e}`))); + } else { + body.on("error", reject); + } + body.on("data", (chunk) => chunks.push(chunk)); + body.on("end", notifyBodyFinished); + }); + request2.on("error", reject); + destroyRequest = () => request2.destroy(); + listeners.push( + eventsHelper.addEventListener(this, _APIRequestContext.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 import_tls3.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(`\u2192 ${options2.method} ${url2.toString()}`); + if (options2.headers) { + for (const [name, value2] of Object.entries(options2.headers)) + progress2.log(` ${name}: ${value2}`); + } + if (postData) + request2.write(postData); + request2.end(); + }); + return progress2.race(resultPromise).catch((error) => { + destroyRequest?.(); + throw error; + }).finally(() => { + progress2.setAllowConcurrentOrNestedRaces(false); + }); + } + _getHttpCredentials(url2) { + if (!this._defaultOptions().httpCredentials?.origin || url2.origin.toLowerCase() === this._defaultOptions().httpCredentials?.origin?.toLowerCase()) + return this._defaultOptions().httpCredentials; + return void 0; + } + }; + SafeEmptyStreamTransform = class extends import_stream4.Transform { + constructor(onEmptyStreamCallback) { + super(); + this._receivedSomeData = false; + this._onEmptyStreamCallback = onEmptyStreamCallback; + } + _transform(chunk, encoding, callback) { + this._receivedSomeData = true; + callback(null, chunk); + } + _flush(callback) { + if (this._receivedSomeData) + callback(null); + else + this._onEmptyStreamCallback(); + } + }; + BrowserContextAPIRequestContext = class extends APIRequestContext { + constructor(context2) { + super(context2); + this._context = context2; + context2.once(BrowserContext.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(progress2, url2) { + return await this._context.cookies(progress2, url2.toString()); + } + async storageState(progress2, indexedDB) { + return this._context.storageState(progress2, indexedDB); + } + }; + GlobalAPIRequestContext = class extends APIRequestContext { + constructor(playwright2, options2) { + super(playwright2); + this._cookieStore = new CookieStore(); + this.attribution.context = this; + if (options2.storageState) { + this._origins = options2.storageState.origins?.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(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(progress2, url2) { + return this._cookieStore.cookies(url2); + } + async storageState(progress2, indexedDB = false) { + return { + cookies: this._cookieStore.allCookies(), + origins: (this._origins || []).map((origin) => ({ ...origin, indexedDB: indexedDB ? origin.indexedDB : [] })) + }; + } + }; + redirectStatus = [301, 302, 303, 307, 308]; + } +}); + +// packages/playwright-core/src/server/utils.ts +async function fetchData(progress2, params2, onError) { + const promise = new ManualPromise(); + const { cancel } = httpRequest(params2, async (response2) => { + if (response2.statusCode !== 200) { + const error = onError ? await onError(params2, response2) : new Error(`fetch failed: server returned code ${response2.statusCode}. URL: ${params2.url}`); + promise.reject(error); + return; + } + let body = ""; + response2.on("data", (chunk) => body += chunk); + response2.on("error", (error) => promise.reject(error)); + response2.on("end", () => promise.resolve(body)); + }, (error) => promise.reject(error)); + if (!progress2) + return promise; + try { + return await progress2.race(promise); + } catch (error) { + cancel(error); + throw error; + } +} +var init_utils2 = __esm({ + "packages/playwright-core/src/server/utils.ts"() { + "use strict"; + init_manualPromise(); + init_network(); + } +}); + +// packages/playwright-core/src/server/registry/nativeDeps.ts +var deps; +var init_nativeDeps = __esm({ + "packages/playwright-core/src/server/registry/nativeDeps.ts"() { + "use strict"; + 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", + "libavcodec60", + "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" + } + }, + "debian13-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: [ + "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: [ + "libasound2", + "libatk1.0-0t64", + "libcairo-gobject2", + "libcairo2", + "libdbus-1-3", + "libdbus-glib-1-2", + "libfontconfig1", + "libfreetype6", + "libgdk-pixbuf-2.0-0", + "libglib2.0-0t64", + "libgtk-3-0t64", + "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-0t64", + "libatk1.0-0t64", + "libcairo2", + "libdbus-1-3", + "libdrm2", + "libegl1", + "libenchant-2-2", + "libepoxy0", + "libevdev2", + "libfontconfig1", + "libfreetype6", + "libgbm1", + "libgdk-pixbuf-2.0-0", + "libgles2", + "libglib2.0-0t64", + "libglx0", + "libgstreamer-gl1.0-0", + "libgstreamer-plugins-base1.0-0", + "libgstreamer1.0-0", + "libgtk-4-1", + "libgudev-1.0-0", + "libharfbuzz-icu0", + "libharfbuzz0b", + "libhyphen0", + "libicu76", + "libjpeg62-turbo", + "liblcms2-2", + "libmanette-0.2-0", + "libnotify4", + "libopengl0", + "libopenjp2-7", + "libopus0", + "libpango-1.0-0", + "libpng16-16t64", + "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-7t64", + "libavif16" + ], + lib2package: { + "libicudata.so.74": "libicu76", + "libicui18n.so.74": "libicu76", + "libicuuc.so.74": "libicu76", + "libevent-2.1.so.7": "libevent-2.1-7t64", + "libpng16.so.16": "libpng16-16t64", + "libgdk-3.so.0": "libgtk-3-0t64", + "libgtk-3.so.0": "libgtk-3-0t64", + "libavif.so.16": "libavif16", + "libsoup-3.0.so.0": "libsoup-3.0-0", + "libasound.so.2": "libasound2t64", + "libatk-1.0.so.0": "libatk1.0-0t64", + "libatk-bridge-2.0.so.0": "libatk-bridge2.0-0t64", + "libatspi.so.0": "libatspi2.0-0t64", + "libcairo.so.2": "libcairo2", + "libcups.so.2": "libcups2t64", + "libdbus-1.so.3": "libdbus-1-3", + "libdrm.so.2": "libdrm2", + "libgbm.so.1": "libgbm1", + "libgio-2.0.so.0": "libglib2.0-0t64", + "libglib-2.0.so.0": "libglib2.0-0t64", + "libgobject-2.0.so.0": "libglib2.0-0t64", + "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 + } + }; + deps["debian13-arm64"] = { + tools: [...deps["debian13-x64"].tools], + chromium: [...deps["debian13-x64"].chromium], + firefox: [ + ...deps["debian13-x64"].firefox + ], + webkit: [ + ...deps["debian13-x64"].webkit + ], + lib2package: { + ...deps["debian13-x64"].lib2package + } + }; + } +}); + +// packages/playwright-core/src/server/registry/dependencies.ts +async function writeDockerVersion(dockerImageNameTemplate) { + await import_fs16.default.promises.mkdir(import_path16.default.dirname(dockerVersionFilePath), { recursive: true }); + await import_fs16.default.promises.writeFile(dockerVersionFilePath, JSON.stringify(dockerVersion(dockerImageNameTemplate), null, 2), "utf8"); + await import_fs16.default.promises.chmod(dockerVersionFilePath, 511); +} +function dockerVersion(dockerImageNameTemplate) { + return { + driverVersion: languageBindingVersion, + dockerImageName: dockerImageNameTemplate.replace("%version%", languageBindingVersion) + }; +} +function readDockerVersionSync() { + try { + const data = JSON.parse(import_fs16.default.readFileSync(dockerVersionFilePath, "utf8")); + return { + ...data, + dockerImageNameTemplate: data.dockerImageName.replace(data.driverVersion, "%version%") + }; + } catch (e) { + return null; + } +} +function isSupportedWindowsVersion() { + if (import_os6.default.platform() !== "win32" || import_os6.default.arch() !== "x64") + return false; + const [major, minor] = import_os6.default.release().split(".").map((token) => parseInt(token, 10)); + return major > 6 || major === 6 && minor > 1; +} +async function installDependenciesWindows(targets, dryRun) { + if (targets.has("chromium")) { + const command = "powershell.exe"; + const args = ["-ExecutionPolicy", "Bypass", "-File", import_path16.default.join(binPath, "install_media_pack.ps1")]; + if (dryRun) { + console.log(`${command} ${quoteProcessArgs(args).join(" ")}`); + return; + } + const { code } = await spawnAsync(command, args, { cwd: binPath, 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) { + await reportMissingDependenciesLinux(uniqueLibraries); + return; + } + console.log(`Installing dependencies...`); + const commands2 = []; + commands2.push("apt-get update"); + commands2.push([ + "apt-get", + "install", + "-y", + "--no-install-recommends", + ...uniqueLibraries + ].join(" ")); + const { command, args, elevatedPermissions } = await transformCommandsForRoot(commands2); + if (elevatedPermissions) + console.log("Switching to root user to install dependencies..."); + const child = childProcess2.spawn(command, args, { stdio: "inherit" }); + 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 reportMissingDependenciesLinux(packages) { + const { code, stdout, stderr, error } = await spawnAsync("apt-get", ["install", "-s", "--no-install-recommends", ...packages], {}); + if (error) + throw new Error(`Failed to run 'apt-get install -s' to simulate dependency install: ${error.message}`); + if (code !== 0) + throw new Error(`'apt-get install -s' exited with code ${code}: +${stderr || stdout}`); + const missingPackages = []; + for (const line of stdout.split("\n")) { + const match = /^Inst (\S+) /.exec(line); + if (match) + missingPackages.push(match[1]); + } + if (!missingPackages.length) { + console.log("All system dependencies are installed."); + return; + } + console.log(`Missing system dependencies (${missingPackages.length}): +${missingPackages.sort().map((p) => ` ${p}`).join("\n")}`); + process.exitCode = 1; +} +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) { + 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] ? { + ...deps[hostPlatform]?.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 = process.getuid?.() && import_os6.default.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 (import_os6.default.platform()) { + case "linux": + return basename.endsWith(".so") || basename.includes(".so."); + case "win32": + return basename.endsWith(".dll"); + default: + return false; + } +} +async function executablesOrSharedLibraries(directoryPath) { + if (!import_fs16.default.existsSync(directoryPath)) + return []; + const allPaths = (await import_fs16.default.promises.readdir(directoryPath)).map((file) => import_path16.default.resolve(directoryPath, file)); + const allStats = await Promise.all(allPaths.map((aPath) => import_fs16.default.promises.stat(aPath))); + const filePaths = allPaths.filter((aPath, index) => allStats[index].isFile()); + const executablersOrLibraries = (await Promise.all(filePaths.map(async (filePath) => { + const basename = import_path16.default.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 = import_path16.default.dirname(filePath); + const { stdout, code } = await spawnAsync(executable, [filePath], { + cwd: dirname, + env: { + ...process.env, + LD_LIBRARY_PATH: process.env.LD_LIBRARY_PATH ? `${process.env.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 = import_path16.default.dirname(filePath); + let LD_LIBRARY_PATH = extraLDPaths.join(":"); + if (process.env.LD_LIBRARY_PATH) + LD_LIBRARY_PATH = `${process.env.LD_LIBRARY_PATH}:${LD_LIBRARY_PATH}`; + const { stdout, code } = await spawnAsync("ldd", [filePath], { + cwd: dirname, + env: { + ...process.env, + 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 } = await spawnAsync("/sbin/ldconfig", ["-p"], {}); + if (code !== 0 || error) + return []; + const isLibraryAvailable = (library) => stdout.toLowerCase().includes(library.toLowerCase()); + return libraries.filter((library) => !isLibraryAvailable(library)); +} +function quoteProcessArgs(args) { + return args.map((arg) => { + if (arg.includes(" ")) + return `"${arg}"`; + return arg; + }); +} +async function transformCommandsForRoot(commands2) { + const isRoot = process.getuid?.() === 0; + if (isRoot) + return { command: "sh", args: ["-c", `${commands2.join("&& ")}`], elevatedPermissions: false }; + const sudoExists = await spawnAsync("which", ["sudo"]); + if (sudoExists.code === 0) + return { command: "sudo", args: ["--", "sh", "-c", `${commands2.join("&& ")}`], elevatedPermissions: true }; + return { command: "su", args: ["root", "-c", `${commands2.join("&& ")}`], elevatedPermissions: true }; +} +var childProcess2, import_fs16, import_os6, import_path16, languageBindingVersion, dockerVersionFilePath, checkExecutable, MANUAL_LIBRARY_TO_PACKAGE_NAME_UBUNTU; +var init_dependencies = __esm({ + "packages/playwright-core/src/server/registry/dependencies.ts"() { + "use strict"; + childProcess2 = __toESM(require("child_process")); + import_fs16 = __toESM(require("fs")); + import_os6 = __toESM(require("os")); + import_path16 = __toESM(require("path")); + init_ascii(); + init_hostPlatform(); + init_spawnAsync(); + init_userAgent(); + init_nativeDeps(); + init_package(); + init_registry(); + languageBindingVersion = process.env.PW_CLI_DISPLAY_VERSION || packageJSON.version; + dockerVersionFilePath = "/ms-playwright/.docker-info"; + checkExecutable = (filePath) => { + if (process.platform === "win32") + return filePath.endsWith(".exe"); + return import_fs16.default.promises.access(filePath, import_fs16.default.constants.X_OK).then(() => true).catch(() => false); + }; + 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" + }; + } +}); + +// packages/playwright-core/src/server/registry/browserFetcher.ts +async function downloadBrowserWithProgressBar(title, browserDirectory, executablePath, downloadURLs, downloadFileName, downloadSocketTimeout, force) { + if (await existsAsync(browserDirectoryToMarkerFilePath(browserDirectory))) { + debugLogger.log("install", `${title} is already downloaded.`); + if (force) + debugLogger.log("install", `force-downloading ${title}.`); + else + return; + } + const uniqueTempDir = await import_fs17.default.promises.mkdtemp(import_path17.default.join(import_os7.default.tmpdir(), "playwright-download-")); + const zipPath = import_path17.default.join(uniqueTempDir, 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}` + colors3.dim(` from ${url2}`)); + const { error } = await downloadBrowserWithProgressBarOutOfProcess(title, browserDirectory, url2, zipPath, executablePath, downloadSocketTimeout); + if (!error) { + debugLogger.log("install", `SUCCESS installing ${title}`); + break; + } + if (await existsAsync(zipPath)) + await import_fs17.default.promises.unlink(zipPath); + if (await existsAsync(browserDirectory)) + await removeFolders([browserDirectory]); + const errorMessage = error?.message || ""; + debugLogger.log("install", `attempt #${attempt} - ERROR: ${errorMessage}`); + if (attempt >= retryCount) + throw error; + } + } catch (e) { + debugLogger.log("install", `FAILED installation ${title} with error: ${e}`); + process.exitCode = 1; + throw e; + } finally { + await removeFolders([uniqueTempDir]); + } + logPolitely(`${title} downloaded to ${browserDirectory}`); +} +function downloadBrowserWithProgressBarOutOfProcess(title, browserDirectory, url2, zipPath, executablePath, socketTimeout) { + const cp = childProcess3.fork(libPath("entry", "oopBrowserDownload.js")); + const promise = new ManualPromise(); + const progress2 = getDownloadProgress(); + cp.on("message", (message) => { + if (message?.method === "log") + debugLogger.log("install", message.params.message); + if (message?.method === "progress") + progress2(message.params.done, message.params.total); + }); + cp.on("exit", (code) => { + if (code !== 0) { + promise.resolve({ error: new Error(`Download failure, code=${code}`) }); + return; + } + if (!import_fs17.default.existsSync(browserDirectoryToMarkerFilePath(browserDirectory))) + promise.resolve({ error: new Error(`Download failure, ${browserDirectoryToMarkerFilePath(browserDirectory)} does not exist`) }); + else + promise.resolve({ error: null }); + }); + cp.on("error", (error) => { + promise.resolve({ error }); + }); + 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() + }; + cp.send({ method: "download", params: downloadParams }); + return promise; +} +function logPolitely(toBeLogged) { + const logLevel = process.env.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 ProgressBar( + `${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(`|${"\u25A0".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`; +} +var childProcess3, import_fs17, import_os7, import_path17, ProgressBar, colors3; +var init_browserFetcher = __esm({ + "packages/playwright-core/src/server/registry/browserFetcher.ts"() { + "use strict"; + childProcess3 = __toESM(require("child_process")); + import_fs17 = __toESM(require("fs")); + import_os7 = __toESM(require("os")); + import_path17 = __toESM(require("path")); + init_manualPromise(); + init_debugLogger(); + init_fileUtils(); + init_userAgent(); + init_package(); + init_registry(); + ProgressBar = require("./utilsBundle").progress; + colors3 = require("./utilsBundle").colors; + } +}); + +// packages/playwright-core/src/server/registry/oopDownloadBrowserMain.ts +function log(message) { + process.send?.({ method: "log", params: { message } }); +} +function progress(done, total) { + process.send?.({ method: "progress", params: { done, total } }); +} +function browserDirectoryToMarkerFilePath2(browserDirectory) { + return import_path18.default.join(browserDirectory, "INSTALLATION_COMPLETE"); +} +function downloadFile(options2) { + let downloadedBytes = 0; + let totalBytes = 0; + let chunked = false; + const promise = new ManualPromise(); + httpRequest({ + url: options2.url, + headers: { + "User-Agent": options2.userAgent + }, + socketTimeout: options2.socketTimeout + }, (response2) => { + log(`-- response status code: ${response2.statusCode}`); + if (response2.statusCode !== 200) { + let content = ""; + const handleError = () => { + const error = new Error(`Download failed: server returned code ${response2.statusCode} body '${content}'. URL: ${options2.url}`); + response2.resume(); + promise.reject(error); + }; + response2.on("data", (chunk) => content += chunk).on("end", handleError).on("error", handleError); + return; + } + chunked = response2.headers["transfer-encoding"] === "chunked"; + log(`-- is chunked: ${chunked}`); + totalBytes = parseInt(response2.headers["content-length"] || "0", 10); + log(`-- total bytes: ${totalBytes}`); + const file = import_fs18.default.createWriteStream(options2.zipPath); + file.on("finish", () => { + if (!chunked && downloadedBytes !== totalBytes) { + log(`-- download failed, size mismatch: ${downloadedBytes} != ${totalBytes}`); + promise.reject(new Error(`Download failed: size mismatch, file size: ${downloadedBytes}, expected size: ${totalBytes} URL: ${options2.url}`)); + } else { + log(`-- download complete, size: ${downloadedBytes}`); + promise.resolve(); + } + }); + file.on("error", (error) => promise.reject(error)); + response2.pipe(file); + response2.on("data", onData); + response2.on("error", (error) => { + file.close(); + if (error?.code === "ECONNRESET") { + log(`-- download failed, server closed connection`); + promise.reject(new Error(`Download failed: server closed connection. URL: ${options2.url}`)); + } else { + log(`-- download failed, unexpected error`); + promise.reject(new Error(`Download failed: ${error?.message ?? error}. URL: ${options2.url}`)); + } + }); + }, (error) => promise.reject(error)); + return promise; + function onData(chunk) { + downloadedBytes += chunk.length; + if (!chunked) + progress(downloadedBytes, totalBytes); + } +} +async function main(options2) { + await downloadFile(options2); + log(`SUCCESS downloading ${options2.title}`); + log(`removing existing browser directory if any`); + await removeFolders([options2.browserDirectory]); + log(`extracting archive`); + await extractZip(options2.zipPath, { dir: options2.browserDirectory }); + if (options2.executablePath) { + log(`fixing permissions at ${options2.executablePath}`); + await import_fs18.default.promises.chmod(options2.executablePath, 493); + } + await import_fs18.default.promises.writeFile(browserDirectoryToMarkerFilePath2(options2.browserDirectory), ""); +} +function runOopDownloadBrowserMain() { + process.on("message", async (message) => { + const { method, params: params2 } = message; + if (method === "download") { + try { + await main(params2); + process.exit(0); + } catch (e) { + console.error(e); + process.exit(1); + } + } + }); + process.on("disconnect", () => { + process.exit(0); + }); +} +var import_fs18, import_path18; +var init_oopDownloadBrowserMain = __esm({ + "packages/playwright-core/src/server/registry/oopDownloadBrowserMain.ts"() { + "use strict"; + import_fs18 = __toESM(require("fs")); + import_path18 = __toESM(require("path")); + init_manualPromise(); + init_network(); + init_fileUtils(); + init_extractZip(); + } +}); + +// packages/playwright-core/src/server/registry/index.ts +var registry_exports = {}; +__export(registry_exports, { + Registry: () => Registry, + browserDirectoryToMarkerFilePath: () => browserDirectoryToMarkerFilePath, + buildPlaywrightCLICommand: () => buildPlaywrightCLICommand, + defaultCacheDirectory: () => defaultCacheDirectory, + defaultRegistryDirectory: () => defaultRegistryDirectory, + findChromiumChannelBestEffort: () => findChromiumChannelBestEffort, + installBrowsersForNpmInstall: () => installBrowsersForNpmInstall, + registry: () => registry, + registryDirectory: () => registryDirectory, + runOopDownloadBrowserMain: () => runOopDownloadBrowserMain, + writeDockerVersion: () => writeDockerVersion +}); +function cftUrl(suffix) { + return ({ browserVersion }) => { + return { + path: `builds/cft/${browserVersion}/${suffix}`, + mirrors: [ + "https://cdn.playwright.dev" + ] + }; + }; +} +function isBrowserDirectory(browserDirectory) { + const baseName = import_path19.default.basename(browserDirectory); + for (const browserName of allDownloadableDirectoriesThatEverExisted) { + 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, + title: obj["title"], + 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: import_path19.default.join(registryDirectory, browserDirectoryPrefix.replace(/-/g, "_") + "-" + revision) + }; + return descriptor; + }); +} +function browserDirectoryToMarkerFilePath(browserDirectory) { + return import_path19.default.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}`; + } + } +} +async function installBrowsersForNpmInstall(browsers) { + if (getAsBooleanFromENV("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD")) { + logPolitely("Skipping browsers download because `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` env variable is set"); + return false; + } + const executables = []; + if (process.platform === "win32") + executables.push(registry.findExecutable("winldd")); + for (const browserName of browsers) { + const executable = registry.findExecutable(browserName); + if (!executable || executable.installType === "none") + throw new Error(`Cannot install ${browserName}`); + executables.push(executable); + } + await registry.install(executables); +} +function findChromiumChannelBestEffort(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 result2 = {}; + for (const [key, value2] of Object.entries(json)) + result2[key.toLowerCase()] = lowercaseAllKeys(value2); + return result2; +} +var import_fs19, import_os8, import_path19, util2, PACKAGE_PATH, BIN_PATH, PLAYWRIGHT_CDN_MIRRORS, EXECUTABLE_PATHS, DOWNLOAD_PATHS, defaultCacheDirectory, defaultRegistryDirectory, registryDirectory, allDownloadableDirectoriesThatEverExisted, chromiumAliases, Registry, registry; +var init_registry = __esm({ + "packages/playwright-core/src/server/registry/index.ts"() { + "use strict"; + import_fs19 = __toESM(require("fs")); + import_os8 = __toESM(require("os")); + import_path19 = __toESM(require("path")); + util2 = __toESM(require("util")); + init_ascii(); + init_debugLogger(); + init_hostPlatform(); + init_network(); + init_spawnAsync(); + init_fileUtils(); + init_crypto(); + init_env(); + init_lockfile(); + init_utils2(); + init_userAgent(); + init_dependencies(); + init_dependencies(); + init_browserFetcher(); + init_package(); + init_dependencies(); + init_oopDownloadBrowserMain(); + PACKAGE_PATH = packageRoot; + BIN_PATH = binPath; + 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 (process.env.PW_TEST_CDN_THAT_SHOULD_WORK) { + for (let i = 0; i < PLAYWRIGHT_CDN_MIRRORS.length; i++) { + const cdn = PLAYWRIGHT_CDN_MIRRORS[i]; + if (cdn !== process.env.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(); + } + } + } + EXECUTABLE_PATHS = { + "chromium": { + "": void 0, + "linux-x64": ["chrome-linux64", "chrome"], + "linux-arm64": ["chrome-linux", "chrome"], + // non-cft build + "mac-x64": ["chrome-mac-x64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"], + "mac-arm64": ["chrome-mac-arm64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"], + "win-x64": ["chrome-win64", "chrome.exe"] + }, + "chromium-headless-shell": { + "": void 0, + "linux-x64": ["chrome-headless-shell-linux64", "chrome-headless-shell"], + "linux-arm64": ["chrome-linux", "headless_shell"], + // non-cft build + "mac-x64": ["chrome-headless-shell-mac-x64", "chrome-headless-shell"], + "mac-arm64": ["chrome-headless-shell-mac-arm64", "chrome-headless-shell"], + "win-x64": ["chrome-headless-shell-win64", "chrome-headless-shell.exe"] + }, + "chromium-tip-of-tree": { + "": void 0, + "linux-x64": ["chrome-linux64", "chrome"], + "linux-arm64": ["chrome-linux", "chrome"], + // non-cft build + "mac-x64": ["chrome-mac-x64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"], + "mac-arm64": ["chrome-mac-arm64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"], + "win-x64": ["chrome-win64", "chrome.exe"] + }, + "chromium-tip-of-tree-headless-shell": { + "": void 0, + "linux-x64": ["chrome-headless-shell-linux64", "chrome-headless-shell"], + "linux-arm64": ["chrome-linux", "headless_shell"], + // non-cft build + "mac-x64": ["chrome-headless-shell-mac-x64", "chrome-headless-shell"], + "mac-arm64": ["chrome-headless-shell-mac-arm64", "chrome-headless-shell"], + "win-x64": ["chrome-headless-shell-win64", "chrome-headless-shell.exe"] + }, + "firefox": { + "": void 0, + "linux-x64": ["firefox", "firefox"], + "linux-arm64": ["firefox", "firefox"], + "mac-x64": ["firefox", "Nightly.app", "Contents", "MacOS", "firefox"], + "mac-arm64": ["firefox", "Nightly.app", "Contents", "MacOS", "firefox"], + "win-x64": ["firefox", "firefox.exe"] + }, + "webkit": { + "": void 0, + "linux-x64": ["pw_run.sh"], + "linux-arm64": ["pw_run.sh"], + "mac-x64": ["pw_run.sh"], + "mac-arm64": ["pw_run.sh"], + "win-x64": ["Playwright.exe"] + }, + "ffmpeg": { + "": void 0, + "linux-x64": ["ffmpeg-linux"], + "linux-arm64": ["ffmpeg-linux"], + "mac-x64": ["ffmpeg-mac"], + "mac-arm64": ["ffmpeg-mac"], + "win-x64": ["ffmpeg-win64.exe"] + }, + "winldd": { + "": void 0, + "linux-x64": void 0, + "linux-arm64": void 0, + "mac-x64": void 0, + "mac-arm64": void 0, + "win-x64": ["PrintDeps.exe"] + } + }; + DOWNLOAD_PATHS = { + "chromium": { + "": void 0, + "ubuntu18.04-x64": void 0, + "ubuntu20.04-x64": cftUrl("linux64/chrome-linux64.zip"), + "ubuntu22.04-x64": cftUrl("linux64/chrome-linux64.zip"), + "ubuntu24.04-x64": cftUrl("linux64/chrome-linux64.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": cftUrl("linux64/chrome-linux64.zip"), + "debian11-arm64": "builds/chromium/%s/chromium-linux-arm64.zip", + "debian12-x64": cftUrl("linux64/chrome-linux64.zip"), + "debian12-arm64": "builds/chromium/%s/chromium-linux-arm64.zip", + "debian13-x64": cftUrl("linux64/chrome-linux64.zip"), + "debian13-arm64": "builds/chromium/%s/chromium-linux-arm64.zip", + "mac10.13": cftUrl("mac-x64/chrome-mac-x64.zip"), + "mac10.14": cftUrl("mac-x64/chrome-mac-x64.zip"), + "mac10.15": cftUrl("mac-x64/chrome-mac-x64.zip"), + "mac11": cftUrl("mac-x64/chrome-mac-x64.zip"), + "mac11-arm64": cftUrl("mac-arm64/chrome-mac-arm64.zip"), + "mac12": cftUrl("mac-x64/chrome-mac-x64.zip"), + "mac12-arm64": cftUrl("mac-arm64/chrome-mac-arm64.zip"), + "mac13": cftUrl("mac-x64/chrome-mac-x64.zip"), + "mac13-arm64": cftUrl("mac-arm64/chrome-mac-arm64.zip"), + "mac14": cftUrl("mac-x64/chrome-mac-x64.zip"), + "mac14-arm64": cftUrl("mac-arm64/chrome-mac-arm64.zip"), + "mac15": cftUrl("mac-x64/chrome-mac-x64.zip"), + "mac15-arm64": cftUrl("mac-arm64/chrome-mac-arm64.zip"), + "mac26": cftUrl("mac-x64/chrome-mac-x64.zip"), + "mac26-arm64": cftUrl("mac-arm64/chrome-mac-arm64.zip"), + "win64": cftUrl("win64/chrome-win64.zip") + }, + "chromium-headless-shell": { + "": void 0, + "ubuntu18.04-x64": void 0, + "ubuntu20.04-x64": cftUrl("linux64/chrome-headless-shell-linux64.zip"), + "ubuntu22.04-x64": cftUrl("linux64/chrome-headless-shell-linux64.zip"), + "ubuntu24.04-x64": cftUrl("linux64/chrome-headless-shell-linux64.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": cftUrl("linux64/chrome-headless-shell-linux64.zip"), + "debian11-arm64": "builds/chromium/%s/chromium-headless-shell-linux-arm64.zip", + "debian12-x64": cftUrl("linux64/chrome-headless-shell-linux64.zip"), + "debian12-arm64": "builds/chromium/%s/chromium-headless-shell-linux-arm64.zip", + "debian13-x64": cftUrl("linux64/chrome-headless-shell-linux64.zip"), + "debian13-arm64": "builds/chromium/%s/chromium-headless-shell-linux-arm64.zip", + "mac10.13": void 0, + "mac10.14": void 0, + "mac10.15": void 0, + "mac11": cftUrl("mac-x64/chrome-headless-shell-mac-x64.zip"), + "mac11-arm64": cftUrl("mac-arm64/chrome-headless-shell-mac-arm64.zip"), + "mac12": cftUrl("mac-x64/chrome-headless-shell-mac-x64.zip"), + "mac12-arm64": cftUrl("mac-arm64/chrome-headless-shell-mac-arm64.zip"), + "mac13": cftUrl("mac-x64/chrome-headless-shell-mac-x64.zip"), + "mac13-arm64": cftUrl("mac-arm64/chrome-headless-shell-mac-arm64.zip"), + "mac14": cftUrl("mac-x64/chrome-headless-shell-mac-x64.zip"), + "mac14-arm64": cftUrl("mac-arm64/chrome-headless-shell-mac-arm64.zip"), + "mac15": cftUrl("mac-x64/chrome-headless-shell-mac-x64.zip"), + "mac15-arm64": cftUrl("mac-arm64/chrome-headless-shell-mac-arm64.zip"), + "mac26": cftUrl("mac-x64/chrome-headless-shell-mac-x64.zip"), + "mac26-arm64": cftUrl("mac-arm64/chrome-headless-shell-mac-arm64.zip"), + "win64": cftUrl("win64/chrome-headless-shell-win64.zip") + }, + "chromium-tip-of-tree": { + "": void 0, + "ubuntu18.04-x64": void 0, + "ubuntu20.04-x64": cftUrl("linux64/chrome-linux64.zip"), + "ubuntu22.04-x64": cftUrl("linux64/chrome-linux64.zip"), + "ubuntu24.04-x64": cftUrl("linux64/chrome-linux64.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": cftUrl("linux64/chrome-linux64.zip"), + "debian11-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-linux-arm64.zip", + "debian12-x64": cftUrl("linux64/chrome-linux64.zip"), + "debian12-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-linux-arm64.zip", + "debian13-x64": cftUrl("linux64/chrome-linux64.zip"), + "debian13-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-linux-arm64.zip", + "mac10.13": cftUrl("mac-x64/chrome-mac-x64.zip"), + "mac10.14": cftUrl("mac-x64/chrome-mac-x64.zip"), + "mac10.15": cftUrl("mac-x64/chrome-mac-x64.zip"), + "mac11": cftUrl("mac-x64/chrome-mac-x64.zip"), + "mac11-arm64": cftUrl("mac-arm64/chrome-mac-arm64.zip"), + "mac12": cftUrl("mac-x64/chrome-mac-x64.zip"), + "mac12-arm64": cftUrl("mac-arm64/chrome-mac-arm64.zip"), + "mac13": cftUrl("mac-x64/chrome-mac-x64.zip"), + "mac13-arm64": cftUrl("mac-arm64/chrome-mac-arm64.zip"), + "mac14": cftUrl("mac-x64/chrome-mac-x64.zip"), + "mac14-arm64": cftUrl("mac-arm64/chrome-mac-arm64.zip"), + "mac15": cftUrl("mac-x64/chrome-mac-x64.zip"), + "mac15-arm64": cftUrl("mac-arm64/chrome-mac-arm64.zip"), + "mac26": cftUrl("mac-x64/chrome-mac-x64.zip"), + "mac26-arm64": cftUrl("mac-arm64/chrome-mac-arm64.zip"), + "win64": cftUrl("win64/chrome-win64.zip") + }, + "chromium-tip-of-tree-headless-shell": { + "": void 0, + "ubuntu18.04-x64": void 0, + "ubuntu20.04-x64": cftUrl("linux64/chrome-headless-shell-linux64.zip"), + "ubuntu22.04-x64": cftUrl("linux64/chrome-headless-shell-linux64.zip"), + "ubuntu24.04-x64": cftUrl("linux64/chrome-headless-shell-linux64.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": cftUrl("linux64/chrome-headless-shell-linux64.zip"), + "debian11-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-linux-arm64.zip", + "debian12-x64": cftUrl("linux64/chrome-headless-shell-linux64.zip"), + "debian12-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-linux-arm64.zip", + "debian13-x64": cftUrl("linux64/chrome-headless-shell-linux64.zip"), + "debian13-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": cftUrl("mac-x64/chrome-headless-shell-mac-x64.zip"), + "mac11-arm64": cftUrl("mac-arm64/chrome-headless-shell-mac-arm64.zip"), + "mac12": cftUrl("mac-x64/chrome-headless-shell-mac-x64.zip"), + "mac12-arm64": cftUrl("mac-arm64/chrome-headless-shell-mac-arm64.zip"), + "mac13": cftUrl("mac-x64/chrome-headless-shell-mac-x64.zip"), + "mac13-arm64": cftUrl("mac-arm64/chrome-headless-shell-mac-arm64.zip"), + "mac14": cftUrl("mac-x64/chrome-headless-shell-mac-x64.zip"), + "mac14-arm64": cftUrl("mac-arm64/chrome-headless-shell-mac-arm64.zip"), + "mac15": cftUrl("mac-x64/chrome-headless-shell-mac-x64.zip"), + "mac15-arm64": cftUrl("mac-arm64/chrome-headless-shell-mac-arm64.zip"), + "mac26": cftUrl("mac-x64/chrome-headless-shell-mac-x64.zip"), + "mac26-arm64": cftUrl("mac-arm64/chrome-headless-shell-mac-arm64.zip"), + "win64": cftUrl("win64/chrome-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", + "debian13-x64": "builds/firefox/%s/firefox-debian-13.zip", + "debian13-arm64": "builds/firefox/%s/firefox-debian-13-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", + "mac26": "builds/firefox/%s/firefox-mac.zip", + "mac26-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", + "debian13-x64": "builds/firefox-beta/%s/firefox-beta-debian-12.zip", + "debian13-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", + "mac26": "builds/firefox-beta/%s/firefox-beta-mac.zip", + "mac26-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", + "debian13-x64": "builds/webkit/%s/webkit-debian-13.zip", + "debian13-arm64": "builds/webkit/%s/webkit-debian-13-arm64.zip", + "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": "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", + "mac26": "builds/webkit/%s/webkit-mac-15.zip", + "mac26-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", + "debian13-x64": "builds/ffmpeg/%s/ffmpeg-linux.zip", + "debian13-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", + "mac26": "builds/ffmpeg/%s/ffmpeg-mac.zip", + "mac26-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, + "debian13-x64": void 0, + "debian13-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, + "mac26": void 0, + "mac26-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", + "debian13-x64": "builds/android/%s/android.zip", + "debian13-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", + "mac26": "builds/android/%s/android.zip", + "mac26-arm64": "builds/android/%s/android.zip", + "win64": "builds/android/%s/android.zip" + } + }; + defaultCacheDirectory = (() => { + if (process.platform === "linux") + return process.env.XDG_CACHE_HOME || import_path19.default.join(import_os8.default.homedir(), ".cache"); + if (process.platform === "darwin") + return import_path19.default.join(import_os8.default.homedir(), "Library", "Caches"); + if (process.platform === "win32") + return process.env.LOCALAPPDATA || import_path19.default.join(import_os8.default.homedir(), "AppData", "Local"); + throw new Error("Unsupported platform: " + process.platform); + })(); + defaultRegistryDirectory = import_path19.default.join(defaultCacheDirectory, "ms-playwright"); + registryDirectory = (() => { + let result2; + const envDefined = getFromENV("PLAYWRIGHT_BROWSERS_PATH"); + if (envDefined === "0") + result2 = import_path19.default.join(packageRoot, ".local-browsers"); + else if (envDefined) + result2 = envDefined; + else + result2 = defaultRegistryDirectory; + if (!import_path19.default.isAbsolute(result2)) { + result2 = import_path19.default.resolve(getFromENV("INIT_CWD") || process.cwd(), result2); + } + return result2; + })(); + allDownloadableDirectoriesThatEverExisted = ["android", "chromium", "firefox", "webkit", "ffmpeg", "firefox-beta", "chromium-tip-of-tree", "chromium-headless-shell", "chromium-tip-of-tree-headless-shell", "winldd"]; + chromiumAliases = ["chrome-for-testing"]; + Registry = class { + constructor(browsersJSON) { + const descriptors = readDescriptors(browsersJSON); + const findExecutablePath = (dir, name) => { + const tokens = EXECUTABLE_PATHS[name][shortPlatform]; + return tokens ? import_path19.default.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 isFfmpeg = name === "ffmpeg"; + let prettyMessage; + if (isOutdatedDockerImage) { + prettyMessage = [ + `Looks like Playwright was just updated to ${preferredDockerVersion.driverVersion}.`, + `Please update docker image as well.`, + `- current: ${currentDockerVersion.dockerImageName}`, + `- required: ${preferredDockerVersion.dockerImageName}`, + ``, + `<3 Playwright Team` + ].join("\n"); + } else if (isFfmpeg) { + prettyMessage = [ + `Video rendering requires ffmpeg binary.`, + `Downloading it will not affect any of the system-wide settings.`, + `Please run the following command:`, + ``, + ` ${buildPlaywrightCLICommand(sdkLanguage, "install ffmpeg")}`, + ``, + `<3 Playwright Team` + ].join("\n"); + } else { + prettyMessage = [ + `Looks like 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({ + 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), + title: chromium.title, + revision: chromium.revision, + browserVersion: chromium.browserVersion, + _install: (force) => this._downloadExecutable(chromium, force, 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({ + 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), + title: chromiumHeadlessShell.title, + revision: chromiumHeadlessShell.revision, + browserVersion: chromiumHeadlessShell.browserVersion, + _install: (force) => this._downloadExecutable(chromiumHeadlessShell, force, chromiumHeadlessShellExecutable), + _dependencyGroup: "chromium", + _isHermeticInstallation: true + }); + const chromiumTipOfTreeHeadlessShell = descriptors.find((d) => d.name === "chromium-tip-of-tree-headless-shell"); + const chromiumTipOfTreeHeadlessShellExecutable = findExecutablePath(chromiumTipOfTreeHeadlessShell.dir, "chromium-tip-of-tree-headless-shell"); + this._executables.push({ + 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), + title: chromiumTipOfTreeHeadlessShell.title, + revision: chromiumTipOfTreeHeadlessShell.revision, + browserVersion: chromiumTipOfTreeHeadlessShell.browserVersion, + _install: (force) => this._downloadExecutable(chromiumTipOfTreeHeadlessShell, force, chromiumTipOfTreeHeadlessShellExecutable), + _dependencyGroup: "chromium", + _isHermeticInstallation: true + }); + const chromiumTipOfTree = descriptors.find((d) => d.name === "chromium-tip-of-tree"); + const chromiumTipOfTreeExecutable = findExecutablePath(chromiumTipOfTree.dir, "chromium-tip-of-tree"); + this._executables.push({ + 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), + title: chromiumTipOfTree.title, + revision: chromiumTipOfTree.revision, + browserVersion: chromiumTipOfTree.browserVersion, + _install: (force) => this._downloadExecutable(chromiumTipOfTree, force, 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": "/opt/google/chrome-canary/chrome", + "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" + })); + const firefox = descriptors.find((d) => d.name === "firefox"); + const firefoxExecutable = findExecutablePath(firefox.dir, "firefox"); + this._executables.push({ + 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), + title: firefox.title, + revision: firefox.revision, + browserVersion: firefox.browserVersion, + _install: (force) => this._downloadExecutable(firefox, force, firefoxExecutable), + _dependencyGroup: "firefox", + _isHermeticInstallation: true + }); + const firefoxBeta = descriptors.find((d) => d.name === "firefox-beta"); + const firefoxBetaExecutable = findExecutablePath(firefoxBeta.dir, "firefox"); + this._executables.push({ + 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), + title: firefoxBeta.title, + revision: firefoxBeta.revision, + browserVersion: firefoxBeta.browserVersion, + _install: (force) => this._downloadExecutable(firefoxBeta, force, firefoxBetaExecutable), + _dependencyGroup: "firefox", + _isHermeticInstallation: true + }); + const webkit = descriptors.find((d) => d.name === "webkit"); + const webkitExecutable = findExecutablePath(webkit.dir, "webkit"); + const webkitLinuxLddDirectories = [ + import_path19.default.join("minibrowser-gtk"), + import_path19.default.join("minibrowser-gtk", "bin"), + import_path19.default.join("minibrowser-gtk", "lib"), + import_path19.default.join("minibrowser-gtk", "sys", "lib"), + import_path19.default.join("minibrowser-wpe"), + import_path19.default.join("minibrowser-wpe", "bin"), + import_path19.default.join("minibrowser-wpe", "lib"), + import_path19.default.join("minibrowser-wpe", "sys", "lib") + ]; + this._executables.push({ + 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), + title: webkit.title, + revision: webkit.revision, + browserVersion: webkit.browserVersion, + _install: (force) => this._downloadExecutable(webkit, force, webkitExecutable), + _dependencyGroup: "webkit", + _isHermeticInstallation: true + }); + this._executables.push({ + name: "webkit-wsl", + browserName: "webkit", + directory: webkit.dir, + executablePath: () => webkitExecutable, + executablePathOrDie: (sdkLanguage) => executablePathOrDie("webkit", webkitExecutable, webkit.installByDefault, sdkLanguage), + installType: "download-on-demand", + title: "Webkit in WSL", + _validateHostRequirements: (sdkLanguage) => Promise.resolve(), + _isHermeticInstallation: true, + _install: async () => { + if (process.platform !== "win32") + throw new Error(`WebKit via WSL is only supported on Windows`); + const script = import_path19.default.join(BIN_PATH, "install_webkit_wsl.ps1"); + const { code } = await spawnAsync("powershell.exe", [ + "-ExecutionPolicy", + "Bypass", + "-File", + script + ], { + stdio: "inherit" + }); + if (code !== 0) + throw new Error(`Failed to install WebKit via WSL`); + } + }); + const ffmpeg = descriptors.find((d) => d.name === "ffmpeg"); + const ffmpegExecutable = findExecutablePath(ffmpeg.dir, "ffmpeg"); + this._executables.push({ + 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), + title: ffmpeg.title, + revision: ffmpeg.revision, + _install: (force) => this._downloadExecutable(ffmpeg, force, ffmpegExecutable), + _dependencyGroup: "tools", + _isHermeticInstallation: true + }); + const winldd = descriptors.find((d) => d.name === "winldd"); + const winlddExecutable = findExecutablePath(winldd.dir, "winldd"); + this._executables.push({ + 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), + title: winldd.title, + revision: winldd.revision, + _install: (force) => this._downloadExecutable(winldd, force, winlddExecutable), + _dependencyGroup: "tools", + _isHermeticInstallation: true + }); + const android = descriptors.find((d) => d.name === "android"); + this._executables.push({ + name: "android", + browserName: void 0, + directory: android.dir, + executablePath: () => void 0, + executablePathOrDie: () => "", + installType: "download-on-demand", + _validateHostRequirements: () => Promise.resolve(), + downloadURLs: this._downloadURLs(android), + title: android.title, + revision: android.revision, + _install: (force) => this._downloadExecutable(android, force), + _dependencyGroup: "tools", + _isHermeticInstallation: true + }); + } + _createChromiumChannel(name, lookAt, install2) { + 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" ? [ + process.env.LOCALAPPDATA, + process.env.PROGRAMFILES, + process.env["PROGRAMFILES(X86)"], + // In some cases there is no PROGRAMFILES/(86) env var set but HOMEDRIVE is set. + process.env.HOMEDRIVE + "\\Program Files", + process.env.HOMEDRIVE + "\\Program Files (x86)" + ].filter(Boolean) : [""]; + for (const prefix of prefixes) { + const executablePath2 = import_path19.default.join(prefix, suffix); + if (canAccessFile(executablePath2)) + return executablePath2; + } + if (!shouldThrow) + return void 0; + const location2 = prefixes.length ? ` at ${import_path19.default.join(prefixes[0], suffix)}` : ``; + const installation = install2 ? ` +Run "${buildPlaywrightCLICommand(sdkLanguage, "install " + name)}"` : ""; + throw new Error(`Chromium distribution '${name}' is not found${location2}${installation}`); + }; + return { + name, + browserName: "chromium", + directory: void 0, + executablePath: () => executablePath("", false), + executablePathOrDie: (sdkLanguage) => executablePath(sdkLanguage, true), + installType: install2 ? "install-script" : "none", + _validateHostRequirements: () => Promise.resolve(), + _isHermeticInstallation: false, + _install: install2 + }; + } + _createBidiFirefoxChannel(name, lookAt, install2) { + 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" ? [ + process.env.LOCALAPPDATA, + process.env.PROGRAMFILES, + process.env["PROGRAMFILES(X86)"], + // In some cases there is no PROGRAMFILES/(86) env var set but HOMEDRIVE is set. + process.env.HOMEDRIVE + "\\Program Files", + process.env.HOMEDRIVE + "\\Program Files (x86)" + ].filter(Boolean) : [""]; + for (const prefix of prefixes) { + const executablePath2 = import_path19.default.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. ${`Tried paths: + ${prefixes.map((p) => import_path19.default.join(p, suffix)).join("\n ")}`}`); + return void 0; + }; + return { + name, + browserName: "firefox", + directory: void 0, + executablePath: () => executablePath("", false), + executablePathOrDie: (sdkLanguage) => executablePath(sdkLanguage, true), + installType: "none", + _validateHostRequirements: () => Promise.resolve(), + _isHermeticInstallation: true, + _install: install2 + }; + } + 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 (import_os8.default.platform() === "linux") + return await validateDependenciesLinux(sdkLanguage, linuxLddDirectories.map((d) => import_path19.default.join(browserDirectory, d)), dlOpenLibraries); + if (import_os8.default.platform() === "win32" && import_os8.default.arch() === "x64") + return await validateDependenciesWindows(sdkLanguage, windowsExeAndDllDirectories.map((d) => import_path19.default.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 (import_os8.default.platform() === "win32") + return await installDependenciesWindows(targets, dryRun); + if (import_os8.default.platform() === "linux") + return await installDependenciesLinux(targets, dryRun); + } + async install(executablesToInstall, options2) { + const executables = this._dedupe(executablesToInstall); + await import_fs19.default.promises.mkdir(registryDirectory, { recursive: true }); + const lockfilePath = import_path19.default.join(registryDirectory, "__dirlock"); + const linksDir = import_path19.default.join(registryDirectory, ".links"); + let releaseLock; + try { + releaseLock = await 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 import_fs19.default.promises.mkdir(linksDir, { recursive: true }); + await import_fs19.default.promises.writeFile(import_path19.default.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}`); + if (!getAsBooleanFromENV("CI") && !executable._isHermeticInstallation && !options2?.force && executable.executablePath()) { + const { embedderName } = getEmbedderName(); + const command = 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:`, + ``, + ` ${command}`, + ``, + `<3 Playwright Team` + ].join("\n"), 1) + "\n\n"); + return; + } + await executable._install(!!options2?.force); + } + } 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 = import_path19.default.join(registryDirectory, ".links"); + if (all) { + const links = await import_fs19.default.promises.readdir(linksDir).catch(() => []); + for (const link of links) + await import_fs19.default.promises.unlink(import_path19.default.join(linksDir, link)); + } else { + await import_fs19.default.promises.unlink(import_path19.default.join(linksDir, calculateSha1(PACKAGE_PATH))).catch(() => { + }); + } + await this._validateInstallationCache(linksDir); + return { + numberOfBrowsersLeft: (await import_fs19.default.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 = import_path19.default.join(executable.directory, "DEPENDENCIES_VALIDATED"); + if (await import_fs19.default.promises.stat(markerFile).then((stat) => Date.now() - stat.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 (error) { + debugLogger.log("install", `validation failed for ${executable.name}`); + throw error; + } + await import_fs19.default.promises.writeFile(markerFile, "").catch(() => { + }); + } + _downloadURLs(descriptor) { + const paths = DOWNLOAD_PATHS[descriptor.name]; + const downloadPathTemplate = paths[hostPlatform] || paths[""]; + if (!downloadPathTemplate) + return []; + let downloadPath; + let mirrors; + if (typeof downloadPathTemplate === "function") { + const result2 = downloadPathTemplate(descriptor); + downloadPath = result2.path; + mirrors = result2.mirrors; + } else { + downloadPath = util2.format(downloadPathTemplate, descriptor.revision); + mirrors = PLAYWRIGHT_CDN_MIRRORS; + } + 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) + mirrors = [customHostOverride]; + return mirrors.map((mirror) => `${mirror}/${downloadPath}`); + } + async _downloadExecutable(descriptor, force, 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 (process.env.GITHUB_ACTIONS) + console.log(`::warning title=Playwright::${message}`); + else + logPolitely(message); + } + const title = this.calculateDownloadTitle(descriptor); + 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, force).catch((e) => { + throw new Error(`Failed to download ${title}, caused by +${e.stack}`); + }); + } + calculateDownloadTitle(descriptor) { + const title = descriptor.title ?? descriptor.name.split("-").map((word) => { + return word === "ffmpeg" ? "FFmpeg" : word.charAt(0).toUpperCase() + word.slice(1); + }).join(" "); + const version3 = descriptor.browserVersion ? " " + descriptor.browserVersion : ""; + return `${title}${version3} (playwright ${descriptor.name} v${descriptor.revision})`; + } + async _installMSEdgeChannel(channel, scripts) { + const scriptArgs = []; + if (process.platform !== "linux") { + const products = lowercaseAllKeys(JSON.parse(await fetchData(void 0, { 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", + import_path19.default.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 shellArgs = scriptArgs.map((a) => `'${a.replace(/'/g, `'\\''`)}'`).join(" "); + const { command, args, elevatedPermissions } = await transformCommandsForRoot([`bash "${import_path19.default.join(BIN_PATH, scriptName)}" ${shellArgs}`]); + if (elevatedPermissions) + console.log("Switching to root user to install dependencies..."); + const { code } = await spawnAsync(command, args, { cwd, stdio: "inherit" }); + if (code !== 0) + throw new Error(`Failed to install ${channel}`); + } + } + async listInstalledBrowsers() { + const linksDir = import_path19.default.join(registryDirectory, ".links"); + const { browsers } = await this._traverseBrowserInstallations(linksDir); + return browsers.filter((browser) => import_fs19.default.existsSync(browser.browserPath)); + } + async _validateInstallationCache(linksDir) { + const { browsers, brokenLinks } = await this._traverseBrowserInstallations(linksDir); + await this._deleteStaleBrowsers(browsers); + await this._deleteBrokenInstallations(brokenLinks); + } + async _traverseBrowserInstallations(linksDir) { + const browserList = []; + const brokenLinks = []; + for (const fileName of await import_fs19.default.promises.readdir(linksDir)) { + const linkPath = import_path19.default.join(linksDir, fileName); + let linkTarget = ""; + try { + linkTarget = (await import_fs19.default.promises.readFile(linkPath)).toString(); + const browsersJSON = require(import_path19.default.join(linkTarget, "browsers.json")); + const descriptors = readDescriptors(browsersJSON); + for (const browserName of allDownloadableDirectoriesThatEverExisted) { + 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 browser of browserList) { + const { browserName, browserVersion, browserPath } = browser; + 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 import_fs19.default.promises.readdir(registryDirectory)).map((file) => import_path19.default.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 import_fs19.default.promises.unlink(linkPath).catch((e) => { + }); + } + _defaultBrowsersToInstall(options2) { + let executables = this.defaultExecutables(); + if (options2.shell === "no") + executables = executables.filter((e) => e.name !== "chromium-headless-shell" && e.name !== "chromium-tip-of-tree-headless-shell"); + if (options2.shell === "only") + executables = executables.filter((e) => e.name !== "chromium" && e.name !== "chromium-tip-of-tree"); + return executables; + } + suggestedBrowsersToInstall() { + const names = this.executables().filter((e) => e.installType !== "none").map((e) => e.name); + names.push(...chromiumAliases); + return names.sort().join(", "); + } + isChromiumAlias(name) { + return chromiumAliases.includes(name); + } + resolveBrowsers(aliases2, options2) { + if (aliases2.length === 0) + return this._defaultBrowsersToInstall(options2); + const faultyArguments = []; + const executables = []; + const handleArgument = (arg) => { + const executable = this.findExecutable(arg); + if (!executable || executable.installType === "none") + faultyArguments.push(arg); + else + executables.push(executable); + if (executable?.browserName) + executables.push(this.findExecutable("ffmpeg")); + }; + for (const alias of aliases2) { + if (alias === "chromium" || chromiumAliases.includes(alias)) { + if (options2.shell !== "only") + handleArgument("chromium"); + if (options2.shell !== "no") + handleArgument("chromium-headless-shell"); + } else if (alias === "chromium-tip-of-tree") { + if (options2.shell !== "only") + handleArgument("chromium-tip-of-tree"); + if (options2.shell !== "no") + handleArgument("chromium-tip-of-tree-headless-shell"); + } else { + handleArgument(alias); + } + } + if (process.platform === "win32") + executables.push(this.findExecutable("winldd")); + if (faultyArguments.length) + throw new Error(`Invalid installation targets: ${faultyArguments.map((name) => `'${name}'`).join(", ")}. Expecting one of: ${this.suggestedBrowsersToInstall()}`); + return executables; + } + }; + registry = new Registry(require(import_path19.default.join(packageRoot, "browsers.json"))); + } +}); + +// packages/playwright-core/src/server/launchApp.ts +async function launchApp(browserType, options2) { + const args = [...options2.persistentContextOptions?.args ?? []]; + let channel = options2.persistentContextOptions?.channel; + if (browserType.name() === "chromium") { + args.push( + "--app=data:text/html,", + `--window-size=${options2.windowSize.width},${options2.windowSize.height}`, + ...options2.windowPosition ? [`--window-position=${options2.windowPosition.x},${options2.windowPosition.y}`] : [], + "--test-type=" + ); + if (!channel && !options2.persistentContextOptions?.executablePath) + channel = findChromiumChannelBestEffort(options2.sdkLanguage); + } + const controller = new ProgressController(); + let context2; + try { + context2 = await controller.run((progress2) => browserType.launchPersistentContext(progress2, "", { + ignoreDefaultArgs: ["--enable-automation"], + ...options2?.persistentContextOptions, + channel, + noDefaultViewport: options2.persistentContextOptions?.noDefaultViewport ?? true, + acceptDownloads: options2?.persistentContextOptions?.acceptDownloads ?? (isUnderTest() ? "accept" : "internal-browser-default"), + colorScheme: options2?.persistentContextOptions?.colorScheme ?? "no-override", + args + }), 0); + } catch (error) { + if (channel) { + error = rewriteErrorMessage(error, [ + `Failed to launch "${channel}" channel.`, + "Using custom channels could lead to unexpected behavior due to Enterprise policies (chrome://policy).", + "Install the default browser instead:", + wrapInASCIIBox(`${buildPlaywrightCLICommand(options2.sdkLanguage, "install")}`, 2) + ].join("\n")); + } + throw error; + } + const [page] = context2.pages(); + if (browserType.name() === "chromium" && process.platform === "darwin") { + context2.on("page", async (newPage) => { + if (newPage.mainFrame().url() === "chrome://new-tab-page/") { + await page.bringToFront(nullProgress); + await newPage.close(nullProgress); + } + }); + } + if (browserType.name() === "chromium") + await installAppIcon(page); + return { context: context2, page }; +} +async function installAppIcon(page) { + const icon = await import_fs20.default.promises.readFile(libPath("server", "chromium", "appIcon.png")); + const crPage = page.delegate; + await crPage._mainFrameSession._client.send("Browser.setDockTile", { + image: icon.toString("base64") + }); +} +async function syncLocalStorageWithSettings(page, appName) { + if (isUnderTest()) + return; + const settingsFile = import_path20.default.join(registryDirectory, ".settings", `${appName}.json`); + const controller = new ProgressController(); + await controller.run(async (progress2) => { + await page.exposeBinding(progress2, "_saveSerializedSettings", (_, settings2) => { + import_fs20.default.mkdirSync(import_path20.default.dirname(settingsFile), { recursive: true }); + import_fs20.default.writeFileSync(settingsFile, settings2); + }); + const settings = await progress2.race(import_fs20.default.promises.readFile(settingsFile, "utf-8").catch(() => "{}")); + await page.addInitScript( + progress2, + `(${String((settings2) => { + if (location && location.protocol === "data:") + return; + if (window.top !== window) + return; + Object.entries(settings2).map(([k, v]) => localStorage[k] = v); + window.saveSettings = () => { + window._saveSerializedSettings(JSON.stringify({ ...localStorage })); + }; + })})(${settings}); + ` + ); + }); +} +var import_fs20, import_path20; +var init_launchApp = __esm({ + "packages/playwright-core/src/server/launchApp.ts"() { + "use strict"; + import_fs20 = __toESM(require("fs")); + import_path20 = __toESM(require("path")); + init_debug(); + init_stackTrace(); + init_ascii(); + init_package(); + init_registry(); + init_registry(); + init_progress(); + } +}); + +// packages/playwright-core/src/server/recorder/throttledFile.ts +var import_fs21, ThrottledFile; +var init_throttledFile = __esm({ + "packages/playwright-core/src/server/recorder/throttledFile.ts"() { + "use strict"; + import_fs21 = __toESM(require("fs")); + ThrottledFile = class { + constructor(file) { + this._file = file; + } + setContent(text2) { + this._text = text2; + if (!this._timer) + this._timer = setTimeout(() => this.flush(), 250); + } + flush() { + if (this._timer) { + clearTimeout(this._timer); + this._timer = void 0; + } + if (this._text) + import_fs21.default.writeFileSync(this._file, this._text); + this._text = void 0; + } + }; + } +}); + +// packages/playwright-core/src/server/codegen/language.ts +function generateCode(actions, languageGenerator, options2) { + const header = languageGenerator.generateHeader(options2); + const footer = languageGenerator.generateFooter(options2.saveStorage); + const actionTexts = actions.map((a) => generateActionText(languageGenerator, a, !!options2.generateAutoExpect)).filter(Boolean); + const text2 = [header, ...actionTexts, footer].join("\n"); + return { header, footer, actionTexts, text: text2 }; +} +function generateActionText(generator, action, generateAutoExpect) { + let text2 = generator.generateAction(action); + if (!text2) + return; + if (generateAutoExpect && action.action.preconditionSelector) { + const expectAction = { + frame: action.frame, + startTime: action.startTime, + endTime: action.startTime, + action: { + name: "assertVisible", + selector: action.action.preconditionSelector, + signals: [] + } + }; + const expectText = generator.generateAction(expectAction); + if (expectText) + text2 = expectText + "\n\n" + text2; + } + return text2; +} +function sanitizeDeviceOptions(device, options2) { + const cleanedOptions = {}; + for (const property in options2) { + if (JSON.stringify(device[property]) !== JSON.stringify(options2[property])) + cleanedOptions[property] = options2[property]; + } + return cleanedOptions; +} +function toSignalMap(action) { + let popup; + let download; + let dialog; + for (const signal of action.signals) { + if (signal.name === "popup") + popup = signal; + else if (signal.name === "download") + download = signal; + else if (signal.name === "dialog") + dialog = signal; + } + return { + popup, + download, + dialog + }; +} +function toKeyboardModifiers(modifiers) { + const result2 = []; + if (modifiers & 1) + result2.push("Alt"); + if (modifiers & 2) + result2.push("ControlOrMeta"); + if (modifiers & 4) + result2.push("ControlOrMeta"); + if (modifiers & 8) + result2.push("Shift"); + return result2; +} +function toClickOptionsForSourceCode(action) { + const modifiers = toKeyboardModifiers(action.modifiers); + const options2 = {}; + if (action.button !== "left") + options2.button = action.button; + if (modifiers.length) + options2.modifiers = modifiers; + if (action.clickCount > 2) + options2.clickCount = action.clickCount; + if (action.position) + options2.position = action.position; + return options2; +} +var init_language = __esm({ + "packages/playwright-core/src/server/codegen/language.ts"() { + "use strict"; + } +}); + +// packages/playwright-core/src/server/deviceDescriptorsSource.json +var deviceDescriptorsSource_default; +var init_deviceDescriptorsSource = __esm({ + "packages/playwright-core/src/server/deviceDescriptorsSource.json"() { + deviceDescriptorsSource_default = { + "Blackberry PlayBook": { + userAgent: "Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/26.4 Safari/536.2+", + viewport: { + width: 600, + height: 1024 + }, + deviceScaleFactor: 1, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "Blackberry PlayBook landscape": { + userAgent: "Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/26.4 Safari/536.2+", + viewport: { + width: 1024, + height: 600 + }, + deviceScaleFactor: 1, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "BlackBerry Z30": { + userAgent: "Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/26.4 Mobile Safari/537.10+", + viewport: { + width: 360, + height: 640 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "BlackBerry Z30 landscape": { + userAgent: "Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/26.4 Mobile Safari/537.10+", + viewport: { + width: 640, + height: 360 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "Galaxy Note 3": { + userAgent: "Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/26.4 Mobile Safari/534.30", + viewport: { + width: 360, + height: 640 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "Galaxy Note 3 landscape": { + userAgent: "Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/26.4 Mobile Safari/534.30", + viewport: { + width: 640, + height: 360 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "Galaxy Note II": { + userAgent: "Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/26.4 Mobile Safari/534.30", + viewport: { + width: 360, + height: 640 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "Galaxy Note II landscape": { + userAgent: "Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/26.4 Mobile Safari/534.30", + viewport: { + width: 640, + height: 360 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "Galaxy S III": { + userAgent: "Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/26.4 Mobile Safari/534.30", + viewport: { + width: 360, + height: 640 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "Galaxy S III landscape": { + userAgent: "Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/26.4 Mobile Safari/534.30", + viewport: { + width: 640, + height: 360 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "Galaxy S5": { + userAgent: "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 360, + height: 640 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Galaxy S5 landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 640, + height: 360 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Galaxy S8": { + userAgent: "Mozilla/5.0 (Linux; Android 7.0; SM-G950U Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 360, + height: 740 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Galaxy S8 landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 7.0; SM-G950U Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 740, + height: 360 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Galaxy S9+": { + userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; SM-G965U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 320, + height: 658 + }, + deviceScaleFactor: 4.5, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Galaxy S9+ landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; SM-G965U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 658, + height: 320 + }, + deviceScaleFactor: 4.5, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Galaxy S24": { + userAgent: "Mozilla/5.0 (Linux; Android 14; SM-S921U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 360, + height: 780 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Galaxy S24 landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 14; SM-S921U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 780, + height: 360 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Galaxy A55": { + userAgent: "Mozilla/5.0 (Linux; Android 14; SM-A556B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 480, + height: 1040 + }, + deviceScaleFactor: 2.25, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Galaxy A55 landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 14; SM-A556B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 1040, + height: 480 + }, + deviceScaleFactor: 2.25, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Galaxy Tab S4": { + userAgent: "Mozilla/5.0 (Linux; Android 8.1.0; SM-T837A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Safari/537.36", + viewport: { + width: 712, + height: 1138 + }, + deviceScaleFactor: 2.25, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Galaxy Tab S4 landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 8.1.0; SM-T837A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Safari/537.36", + viewport: { + width: 1138, + height: 712 + }, + deviceScaleFactor: 2.25, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Galaxy Tab S9": { + userAgent: "Mozilla/5.0 (Linux; Android 14; SM-X710) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Safari/537.36", + viewport: { + width: 640, + height: 1024 + }, + deviceScaleFactor: 2.5, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Galaxy Tab S9 landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 14; SM-X710) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Safari/537.36", + viewport: { + width: 1024, + height: 640 + }, + deviceScaleFactor: 2.5, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "iPad (gen 5)": { + userAgent: "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + viewport: { + width: 768, + height: 1024 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPad (gen 5) landscape": { + userAgent: "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + viewport: { + width: 1024, + height: 768 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPad (gen 6)": { + userAgent: "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + viewport: { + width: 768, + height: 1024 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPad (gen 6) landscape": { + userAgent: "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + viewport: { + width: 1024, + height: 768 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPad (gen 7)": { + userAgent: "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + viewport: { + width: 810, + height: 1080 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPad (gen 7) landscape": { + userAgent: "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + viewport: { + width: 1080, + height: 810 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPad (gen 11)": { + userAgent: "Mozilla/5.0 (iPad; CPU OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/19E241 Safari/604.1", + viewport: { + width: 656, + height: 944 + }, + deviceScaleFactor: 2.5, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPad (gen 11) landscape": { + userAgent: "Mozilla/5.0 (iPad; CPU OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/19E241 Safari/604.1", + viewport: { + width: 944, + height: 656 + }, + deviceScaleFactor: 2.5, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPad Mini": { + userAgent: "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + viewport: { + width: 768, + height: 1024 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPad Mini landscape": { + userAgent: "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + viewport: { + width: 1024, + height: 768 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPad Pro 11": { + userAgent: "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + viewport: { + width: 834, + height: 1194 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPad Pro 11 landscape": { + userAgent: "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + viewport: { + width: 1194, + height: 834 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 6": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.4 Mobile/15A372 Safari/604.1", + viewport: { + width: 375, + height: 667 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 6 landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.4 Mobile/15A372 Safari/604.1", + viewport: { + width: 667, + height: 375 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 6 Plus": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.4 Mobile/15A372 Safari/604.1", + viewport: { + width: 414, + height: 736 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 6 Plus landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.4 Mobile/15A372 Safari/604.1", + viewport: { + width: 736, + height: 414 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 7": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.4 Mobile/15A372 Safari/604.1", + viewport: { + width: 375, + height: 667 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 7 landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.4 Mobile/15A372 Safari/604.1", + viewport: { + width: 667, + height: 375 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 7 Plus": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.4 Mobile/15A372 Safari/604.1", + viewport: { + width: 414, + height: 736 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 7 Plus landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.4 Mobile/15A372 Safari/604.1", + viewport: { + width: 736, + height: 414 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 8": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.4 Mobile/15A372 Safari/604.1", + viewport: { + width: 375, + height: 667 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 8 landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.4 Mobile/15A372 Safari/604.1", + viewport: { + width: 667, + height: 375 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 8 Plus": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.4 Mobile/15A372 Safari/604.1", + viewport: { + width: 414, + height: 736 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 8 Plus landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.4 Mobile/15A372 Safari/604.1", + viewport: { + width: 736, + height: 414 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone SE": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/26.4 Mobile/14E304 Safari/602.1", + viewport: { + width: 320, + height: 568 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone SE landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/26.4 Mobile/14E304 Safari/602.1", + viewport: { + width: 568, + height: 320 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone SE (3rd gen)": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/26.4 Mobile/19E241 Safari/602.1", + viewport: { + width: 375, + height: 667 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone SE (3rd gen) landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/26.4 Mobile/19E241 Safari/602.1", + viewport: { + width: 667, + height: 375 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone X": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.4 Mobile/15A372 Safari/604.1", + viewport: { + width: 375, + height: 812 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone X landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.4 Mobile/15A372 Safari/604.1", + viewport: { + width: 812, + height: 375 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone XR": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + viewport: { + width: 414, + height: 896 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone XR landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + viewport: { + width: 896, + height: 414 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 11": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 414, + height: 896 + }, + viewport: { + width: 414, + height: 715 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 11 landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 414, + height: 896 + }, + viewport: { + width: 800, + height: 364 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 11 Pro": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 375, + height: 812 + }, + viewport: { + width: 375, + height: 635 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 11 Pro landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 375, + height: 812 + }, + viewport: { + width: 724, + height: 325 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 11 Pro Max": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 414, + height: 896 + }, + viewport: { + width: 414, + height: 715 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 11 Pro Max landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 414, + height: 896 + }, + viewport: { + width: 808, + height: 364 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 12": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 390, + height: 844 + }, + viewport: { + width: 390, + height: 664 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 12 landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 390, + height: 844 + }, + viewport: { + width: 750, + height: 340 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 12 Pro": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 390, + height: 844 + }, + viewport: { + width: 390, + height: 664 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 12 Pro landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 390, + height: 844 + }, + viewport: { + width: 750, + height: 340 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 12 Pro Max": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 428, + height: 926 + }, + viewport: { + width: 428, + height: 746 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 12 Pro Max landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 428, + height: 926 + }, + viewport: { + width: 832, + height: 378 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 12 Mini": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 375, + height: 812 + }, + viewport: { + width: 375, + height: 629 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 12 Mini landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 375, + height: 812 + }, + viewport: { + width: 712, + height: 325 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 13": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 390, + height: 844 + }, + viewport: { + width: 390, + height: 664 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 13 landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 390, + height: 844 + }, + viewport: { + width: 750, + height: 342 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 13 Pro": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 390, + height: 844 + }, + viewport: { + width: 390, + height: 664 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 13 Pro landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 390, + height: 844 + }, + viewport: { + width: 750, + height: 342 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 13 Pro Max": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 428, + height: 926 + }, + viewport: { + width: 428, + height: 746 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 13 Pro Max landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 428, + height: 926 + }, + viewport: { + width: 832, + height: 380 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 13 Mini": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 375, + height: 812 + }, + viewport: { + width: 375, + height: 629 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 13 Mini landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 375, + height: 812 + }, + viewport: { + width: 712, + height: 327 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 14": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 390, + height: 844 + }, + viewport: { + width: 390, + height: 664 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 14 landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 390, + height: 844 + }, + viewport: { + width: 750, + height: 340 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 14 Plus": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 428, + height: 926 + }, + viewport: { + width: 428, + height: 746 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 14 Plus landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 428, + height: 926 + }, + viewport: { + width: 832, + height: 378 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 14 Pro": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 393, + height: 852 + }, + viewport: { + width: 393, + height: 660 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 14 Pro landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 393, + height: 852 + }, + viewport: { + width: 734, + height: 343 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 14 Pro Max": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 430, + height: 932 + }, + viewport: { + width: 430, + height: 740 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 14 Pro Max landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 430, + height: 932 + }, + viewport: { + width: 814, + height: 380 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 15": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 393, + height: 852 + }, + viewport: { + width: 393, + height: 659 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 15 landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 393, + height: 852 + }, + viewport: { + width: 734, + height: 343 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 15 Plus": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 430, + height: 932 + }, + viewport: { + width: 430, + height: 739 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 15 Plus landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 430, + height: 932 + }, + viewport: { + width: 814, + height: 380 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 15 Pro": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 393, + height: 852 + }, + viewport: { + width: 393, + height: 659 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 15 Pro landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 393, + height: 852 + }, + viewport: { + width: 734, + height: 343 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 15 Pro Max": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 430, + height: 932 + }, + viewport: { + width: 430, + height: 739 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "iPhone 15 Pro Max landscape": { + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1", + screen: { + width: 430, + height: 932 + }, + viewport: { + width: 814, + height: 380 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "Kindle Fire HDX": { + userAgent: "Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true", + viewport: { + width: 800, + height: 1280 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "Kindle Fire HDX landscape": { + userAgent: "Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true", + viewport: { + width: 1280, + height: 800 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "LG Optimus L70": { + userAgent: "Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 384, + height: 640 + }, + deviceScaleFactor: 1.25, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "LG Optimus L70 landscape": { + userAgent: "Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 640, + height: 384 + }, + deviceScaleFactor: 1.25, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Microsoft Lumia 550": { + userAgent: "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 550) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36 Edge/14.14263", + viewport: { + width: 360, + height: 640 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Microsoft Lumia 550 landscape": { + userAgent: "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 550) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36 Edge/14.14263", + viewport: { + width: 640, + height: 360 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Microsoft Lumia 950": { + userAgent: "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36 Edge/14.14263", + viewport: { + width: 360, + height: 640 + }, + deviceScaleFactor: 4, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Microsoft Lumia 950 landscape": { + userAgent: "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36 Edge/14.14263", + viewport: { + width: 640, + height: 360 + }, + deviceScaleFactor: 4, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Nexus 10": { + userAgent: "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Safari/537.36", + viewport: { + width: 800, + height: 1280 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Nexus 10 landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Safari/537.36", + viewport: { + width: 1280, + height: 800 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Nexus 4": { + userAgent: "Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 384, + height: 640 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Nexus 4 landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 640, + height: 384 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Nexus 5": { + userAgent: "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 360, + height: 640 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Nexus 5 landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 640, + height: 360 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Nexus 5X": { + userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 412, + height: 732 + }, + deviceScaleFactor: 2.625, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Nexus 5X landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 732, + height: 412 + }, + deviceScaleFactor: 2.625, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Nexus 6": { + userAgent: "Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 412, + height: 732 + }, + deviceScaleFactor: 3.5, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Nexus 6 landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 732, + height: 412 + }, + deviceScaleFactor: 3.5, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Nexus 6P": { + userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 412, + height: 732 + }, + deviceScaleFactor: 3.5, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Nexus 6P landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 732, + height: 412 + }, + deviceScaleFactor: 3.5, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Nexus 7": { + userAgent: "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Safari/537.36", + viewport: { + width: 600, + height: 960 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Nexus 7 landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Safari/537.36", + viewport: { + width: 960, + height: 600 + }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Nokia Lumia 520": { + userAgent: "Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)", + viewport: { + width: 320, + height: 533 + }, + deviceScaleFactor: 1.5, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Nokia Lumia 520 landscape": { + userAgent: "Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)", + viewport: { + width: 533, + height: 320 + }, + deviceScaleFactor: 1.5, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Nokia N9": { + userAgent: "Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13", + viewport: { + width: 480, + height: 854 + }, + deviceScaleFactor: 1, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "Nokia N9 landscape": { + userAgent: "Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13", + viewport: { + width: 854, + height: 480 + }, + deviceScaleFactor: 1, + isMobile: true, + hasTouch: true, + defaultBrowserType: "webkit" + }, + "Pixel 2": { + userAgent: "Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 411, + height: 731 + }, + deviceScaleFactor: 2.625, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Pixel 2 landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 731, + height: 411 + }, + deviceScaleFactor: 2.625, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Pixel 2 XL": { + userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 411, + height: 823 + }, + deviceScaleFactor: 3.5, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Pixel 2 XL landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 823, + height: 411 + }, + deviceScaleFactor: 3.5, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Pixel 3": { + userAgent: "Mozilla/5.0 (Linux; Android 9; Pixel 3 Build/PQ1A.181105.017.A1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 393, + height: 786 + }, + deviceScaleFactor: 2.75, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Pixel 3 landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 9; Pixel 3 Build/PQ1A.181105.017.A1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 786, + height: 393 + }, + deviceScaleFactor: 2.75, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Pixel 4": { + userAgent: "Mozilla/5.0 (Linux; Android 10; Pixel 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 353, + height: 745 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Pixel 4 landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 10; Pixel 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 745, + height: 353 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Pixel 4a (5G)": { + userAgent: "Mozilla/5.0 (Linux; Android 11; Pixel 4a (5G)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + screen: { + width: 412, + height: 892 + }, + viewport: { + width: 412, + height: 765 + }, + deviceScaleFactor: 2.63, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Pixel 4a (5G) landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 11; Pixel 4a (5G)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + screen: { + height: 892, + width: 412 + }, + viewport: { + width: 840, + height: 312 + }, + deviceScaleFactor: 2.63, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Pixel 5": { + userAgent: "Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + screen: { + width: 393, + height: 851 + }, + viewport: { + width: 393, + height: 727 + }, + deviceScaleFactor: 2.75, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Pixel 5 landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + screen: { + width: 851, + height: 393 + }, + viewport: { + width: 802, + height: 293 + }, + deviceScaleFactor: 2.75, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Pixel 7": { + userAgent: "Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + screen: { + width: 412, + height: 915 + }, + viewport: { + width: 412, + height: 839 + }, + deviceScaleFactor: 2.625, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Pixel 7 landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + screen: { + width: 915, + height: 412 + }, + viewport: { + width: 863, + height: 360 + }, + deviceScaleFactor: 2.625, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Moto G4": { + userAgent: "Mozilla/5.0 (Linux; Android 7.0; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 360, + height: 640 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Moto G4 landscape": { + userAgent: "Mozilla/5.0 (Linux; Android 7.0; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Mobile Safari/537.36", + viewport: { + width: 640, + height: 360 + }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + defaultBrowserType: "chromium" + }, + "Desktop Chrome HiDPI": { + userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Safari/537.36", + screen: { + width: 1792, + height: 1120 + }, + viewport: { + width: 1280, + height: 720 + }, + deviceScaleFactor: 2, + isMobile: false, + hasTouch: false, + defaultBrowserType: "chromium" + }, + "Desktop Edge HiDPI": { + userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Safari/537.36 Edg/148.0.7778.96", + screen: { + width: 1792, + height: 1120 + }, + viewport: { + width: 1280, + height: 720 + }, + deviceScaleFactor: 2, + isMobile: false, + hasTouch: false, + defaultBrowserType: "chromium" + }, + "Desktop Firefox HiDPI": { + userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:150.0.2) Gecko/20100101 Firefox/150.0.2", + screen: { + width: 1792, + height: 1120 + }, + viewport: { + width: 1280, + height: 720 + }, + deviceScaleFactor: 2, + isMobile: false, + hasTouch: false, + defaultBrowserType: "firefox" + }, + "Desktop Safari": { + userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Safari/605.1.15", + screen: { + width: 1792, + height: 1120 + }, + viewport: { + width: 1280, + height: 720 + }, + deviceScaleFactor: 2, + isMobile: false, + hasTouch: false, + defaultBrowserType: "webkit" + }, + "Desktop Chrome": { + userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Safari/537.36", + screen: { + width: 1920, + height: 1080 + }, + viewport: { + width: 1280, + height: 720 + }, + deviceScaleFactor: 1, + isMobile: false, + hasTouch: false, + defaultBrowserType: "chromium" + }, + "Desktop Edge": { + userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.96 Safari/537.36 Edg/148.0.7778.96", + screen: { + width: 1920, + height: 1080 + }, + viewport: { + width: 1280, + height: 720 + }, + deviceScaleFactor: 1, + isMobile: false, + hasTouch: false, + defaultBrowserType: "chromium" + }, + "Desktop Firefox": { + userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:150.0.2) Gecko/20100101 Firefox/150.0.2", + screen: { + width: 1920, + height: 1080 + }, + viewport: { + width: 1280, + height: 720 + }, + deviceScaleFactor: 1, + isMobile: false, + hasTouch: false, + defaultBrowserType: "firefox" + } + }; + } +}); + +// packages/playwright-core/src/server/deviceDescriptors.ts +var deviceDescriptors; +var init_deviceDescriptors = __esm({ + "packages/playwright-core/src/server/deviceDescriptors.ts"() { + "use strict"; + init_deviceDescriptorsSource(); + deviceDescriptors = deviceDescriptorsSource_default; + } +}); + +// packages/playwright-core/src/server/codegen/csharp.ts +function formatObject2(value2, indent = " ", name = "") { + if (typeof value2 === "string") { + if (["colorScheme", "modifiers", "button", "recordHarContent", "recordHarMode", "serviceWorkers"].includes(name)) + return `${getEnumName(name)}.${toPascal(value2)}`; + return quote(value2); + } + if (Array.isArray(value2)) + return `new[] { ${value2.map((o) => formatObject2(o, indent, name)).join(", ")} }`; + if (typeof value2 === "object") { + const keys = Object.keys(value2).filter((key) => value2[key] !== void 0).sort(); + if (!keys.length) + return `new()`; + const tokens = []; + for (const key of keys) { + const property = getPropertyName(key); + tokens.push(`${property} = ${formatObject2(value2[key], indent, key)},`); + } + return `new() +{ +${indent}${tokens.join(` +${indent}`)} +${indent}}`; + } + if (name === "latitude" || name === "longitude") + return String(value2) + "m"; + return String(value2); +} +function getEnumName(value2) { + switch (value2) { + case "modifiers": + return "KeyboardModifier"; + case "button": + return "MouseButton"; + case "recordHarMode": + return "HarMode"; + case "recordHarContent": + return "HarContentPolicy"; + case "serviceWorkers": + return "ServiceWorkerPolicy"; + default: + return toPascal(value2); + } +} +function getPropertyName(key) { + switch (key) { + case "storageState": + return "StorageStatePath"; + case "viewport": + return "ViewportSize"; + default: + return toPascal(key); + } +} +function toPascal(value2) { + return value2[0].toUpperCase() + value2.slice(1); +} +function formatContextOptions(contextOptions, deviceName) { + const options2 = { ...contextOptions }; + delete options2.recordHar; + const device = deviceName && deviceDescriptors[deviceName]; + if (!device) { + if (!Object.entries(options2).length) + return ""; + return formatObject2(options2, " "); + } + if (!Object.entries(sanitizeDeviceOptions(device, options2)).length) + return `playwright.Devices[${quote(deviceName)}]`; + delete options2["defaultBrowserType"]; + return formatObject2(options2, " "); +} +function quote(text2) { + return escapeWithQuotes(text2, '"'); +} +var CSharpLanguageGenerator, CSharpFormatter; +var init_csharp = __esm({ + "packages/playwright-core/src/server/codegen/csharp.ts"() { + "use strict"; + init_locatorGenerators(); + init_stringUtils(); + init_language(); + init_deviceDescriptors(); + CSharpLanguageGenerator = class { + constructor(mode) { + this.groupName = ".NET C#"; + this.highlighter = "csharp"; + if (mode === "library") { + this.name = "Library"; + this.id = "csharp"; + } else if (mode === "mstest") { + this.name = "MSTest"; + this.id = "csharp-mstest"; + } else if (mode === "nunit") { + this.name = "NUnit"; + this.id = "csharp-nunit"; + } else if (mode === "xunit") { + this.name = "xUnit"; + this.id = "csharp-xunit"; + } else { + throw new Error(`Unknown C# language mode: ${mode}`); + } + this._mode = mode; + } + generateAction(actionInContext) { + const action = this._generateActionInner(actionInContext); + if (action) + return action; + return ""; + } + _generateActionInner(actionInContext) { + const action = actionInContext.action; + if (this._mode !== "library" && (action.name === "openPage" || action.name === "closePage")) + return ""; + const pageAlias = this._formatPageAlias(actionInContext.frame.pageAlias); + const formatter = new CSharpFormatter(this._mode === "library" ? 0 : 8); + if (action.name === "openPage") { + formatter.add(`var ${pageAlias} = await context.NewPageAsync();`); + if (action.url && action.url !== "about:blank" && action.url !== "chrome://newtab/") + formatter.add(`await ${pageAlias}.GotoAsync(${quote(action.url)});`); + return formatter.format(); + } + const locators = actionInContext.frame.framePath.map((selector) => `.${this._asLocator(selector)}.ContentFrame`); + const subject = `${pageAlias}${locators.join("")}`; + const signals = toSignalMap(action); + if (signals.dialog) { + formatter.add(` void ${pageAlias}_Dialog${signals.dialog.dialogAlias}_EventHandler(object sender, IDialog dialog) + { + Console.WriteLine($"Dialog message: {dialog.Message}"); + dialog.DismissAsync(); + ${pageAlias}.Dialog -= ${pageAlias}_Dialog${signals.dialog.dialogAlias}_EventHandler; + } + ${pageAlias}.Dialog += ${pageAlias}_Dialog${signals.dialog.dialogAlias}_EventHandler;`); + } + const lines = []; + lines.push(this._generateActionCall(subject, actionInContext)); + if (signals.download) { + lines.unshift(`var download${signals.download.downloadAlias} = await ${pageAlias}.RunAndWaitForDownloadAsync(async () => +{`); + lines.push(`});`); + } + if (signals.popup) { + lines.unshift(`var ${this._formatPageAlias(signals.popup.popupAlias)} = await ${pageAlias}.RunAndWaitForPopupAsync(async () => +{`); + lines.push(`});`); + } + for (const line of lines) + formatter.add(line); + return formatter.format(); + } + _formatPageAlias(pageAlias) { + if (this._mode === "library") + return pageAlias; + if (pageAlias === "page") + return "Page"; + return pageAlias; + } + _generateActionCall(subject, actionInContext) { + const action = actionInContext.action; + switch (action.name) { + case "openPage": + throw Error("Not reached"); + case "closePage": + return `await ${subject}.CloseAsync();`; + case "click": { + let method = "Click"; + if (action.clickCount === 2) + method = "DblClick"; + const options2 = toClickOptionsForSourceCode(action); + if (!Object.entries(options2).length) + return `await ${subject}.${this._asLocator(action.selector)}.${method}Async();`; + const optionsString = formatObject2(options2, " "); + return `await ${subject}.${this._asLocator(action.selector)}.${method}Async(${optionsString});`; + } + case "hover": { + const optionsString = action.position ? formatObject2({ position: action.position }, " ") : ""; + return `await ${subject}.${this._asLocator(action.selector)}.HoverAsync(${optionsString});`; + } + case "check": + return `await ${subject}.${this._asLocator(action.selector)}.CheckAsync();`; + case "uncheck": + return `await ${subject}.${this._asLocator(action.selector)}.UncheckAsync();`; + case "fill": + return `await ${subject}.${this._asLocator(action.selector)}.FillAsync(${quote(action.text)});`; + case "setInputFiles": + return `await ${subject}.${this._asLocator(action.selector)}.SetInputFilesAsync(${formatObject2(action.files)});`; + case "press": { + const modifiers = toKeyboardModifiers(action.modifiers); + const shortcut = [...modifiers, action.key].join("+"); + return `await ${subject}.${this._asLocator(action.selector)}.PressAsync(${quote(shortcut)});`; + } + case "navigate": + return `await ${subject}.GotoAsync(${quote(action.url)});`; + case "select": + return `await ${subject}.${this._asLocator(action.selector)}.SelectOptionAsync(${formatObject2(action.options)});`; + case "assertText": + return `await Expect(${subject}.${this._asLocator(action.selector)}).${action.substring ? "ToContainTextAsync" : "ToHaveTextAsync"}(${quote(action.text)});`; + case "assertChecked": + return `await Expect(${subject}.${this._asLocator(action.selector)})${action.checked ? "" : ".Not"}.ToBeCheckedAsync();`; + case "assertVisible": + return `await Expect(${subject}.${this._asLocator(action.selector)}).ToBeVisibleAsync();`; + case "assertValue": { + const assertion = action.value ? `ToHaveValueAsync(${quote(action.value)})` : `ToBeEmptyAsync()`; + return `await Expect(${subject}.${this._asLocator(action.selector)}).${assertion};`; + } + case "assertSnapshot": + return `await Expect(${subject}.${this._asLocator(action.selector)}).ToMatchAriaSnapshotAsync(${quote(action.ariaSnapshot)});`; + } + } + _asLocator(selector) { + return asLocator("csharp", selector); + } + generateHeader(options2) { + if (this._mode === "library") + return this.generateStandaloneHeader(options2); + return this.generateTestRunnerHeader(options2); + } + generateStandaloneHeader(options2) { + const formatter = new CSharpFormatter(0); + formatter.add(` + using Microsoft.Playwright; + using System; + using System.Threading.Tasks; + + using var playwright = await Playwright.CreateAsync(); + await using var browser = await playwright.${toPascal(options2.browserName)}.LaunchAsync(${formatObject2(options2.launchOptions, " ")}); + var context = await browser.NewContextAsync(${formatContextOptions(options2.contextOptions, options2.deviceName)});`); + if (options2.contextOptions.recordHar) { + const url2 = options2.contextOptions.recordHar.urlFilter; + formatter.add(` await context.RouteFromHARAsync(${quote(options2.contextOptions.recordHar.path)}${url2 ? `, ${formatObject2({ url: url2 }, " ")}` : ""});`); + } + formatter.newLine(); + return formatter.format(); + } + generateTestRunnerHeader(options2) { + const formatter = new CSharpFormatter(0); + const playwrightNamespace = this._mode === "nunit" ? "NUnit" : this._mode === "xunit" ? "Xunit" : "MSTest"; + const classAttributes = this._mode === "nunit" ? `[Parallelizable(ParallelScope.Self)] + [TestFixture] + ` : this._mode === "mstest" ? `[TestClass] + ` : ""; + formatter.add(` + using Microsoft.Playwright.${playwrightNamespace}; + using Microsoft.Playwright;${this._mode === "xunit" ? ` + using Xunit;` : ""} + + ${classAttributes}public class Tests : PageTest + {`); + const formattedContextOptions = formatContextOptions(options2.contextOptions, options2.deviceName); + if (formattedContextOptions) { + formatter.add(`public override BrowserNewContextOptions ContextOptions() + { + return ${formattedContextOptions}; + }`); + formatter.newLine(); + } + const testAttribute = this._mode === "nunit" ? "Test" : this._mode === "xunit" ? "Fact" : "TestMethod"; + formatter.add(` [${testAttribute}] + public async Task MyTest() + {`); + if (options2.contextOptions.recordHar) { + const url2 = options2.contextOptions.recordHar.urlFilter; + formatter.add(` await Context.RouteFromHARAsync(${quote(options2.contextOptions.recordHar.path)}${url2 ? `, ${formatObject2({ url: url2 }, " ")}` : ""});`); + } + return formatter.format(); + } + generateFooter(saveStorage) { + const offset = this._mode === "library" ? "" : " "; + let storageStateLine = saveStorage ? ` +${offset}await context.StorageStateAsync(new() +${offset}{ +${offset} Path = ${quote(saveStorage)} +${offset}}); +` : ""; + if (this._mode !== "library") + storageStateLine += ` } +} +`; + return storageStateLine; + } + }; + CSharpFormatter = class { + constructor(offset = 0) { + this._lines = []; + this._baseIndent = " ".repeat(4); + this._baseOffset = " ".repeat(offset); + } + prepend(text2) { + this._lines = text2.trim().split("\n").map((line) => line.trim()).concat(this._lines); + } + add(text2) { + this._lines.push(...text2.trim().split("\n").map((line) => line.trim())); + } + newLine() { + this._lines.push(""); + } + format() { + let spaces = ""; + let previousLine = ""; + return this._lines.map((line) => { + if (line === "") + return line; + if (line.startsWith("}") || line.startsWith("]") || line.includes("});") || line === ");") + spaces = spaces.substring(this._baseIndent.length); + const extraSpaces = /^(for|while|if).*\(.*\)$/.test(previousLine) ? this._baseIndent : ""; + previousLine = line; + line = spaces + extraSpaces + line; + if (line.endsWith("{") || line.endsWith("[") || line.endsWith("(")) + spaces += this._baseIndent; + if (line.endsWith("));")) + spaces = spaces.substring(this._baseIndent.length); + return this._baseOffset + line; + }).join("\n"); + } + }; + } +}); + +// packages/playwright-core/src/server/codegen/javascript.ts +function formatOptions(value2, hasArguments) { + const keys = Object.keys(value2).filter((key) => value2[key] !== void 0); + if (!keys.length) + return ""; + return (hasArguments ? ", " : "") + formatObject(value2); +} +function formatContextOptions2(options2, deviceName, isTest) { + const device = deviceName && deviceDescriptors[deviceName]; + options2 = { ...options2, recordHar: void 0 }; + if (!device) + return formatObjectOrVoid(options2); + let serializedObject = formatObjectOrVoid(sanitizeDeviceOptions(device, options2)); + if (!serializedObject) + serializedObject = "{\n}"; + const lines = serializedObject.split("\n"); + lines.splice(1, 0, `...devices[${quote2(deviceName)}],`); + return lines.join("\n"); +} +function quote2(text2) { + return escapeWithQuotes(text2, "'"); +} +function wrapWithStep(description, body) { + return description ? `await test.step(\`${description}\`, async () => { +${body} +});` : body; +} +function quoteMultiline(text2, indent = " ") { + const escape = (text3) => text3.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/g, "\\${"); + const lines = text2.split("\n"); + if (lines.length === 1) + return "`" + escape(text2) + "`"; + return "`\n" + lines.map((line) => indent + escape(line).replace(/\${/g, "\\${")).join("\n") + ` +${indent}\``; +} +function isMultilineString(text2) { + return text2.match(/`[\S\s]*`/)?.[0].includes("\n"); +} +var JavaScriptLanguageGenerator, JavaScriptFormatter; +var init_javascript2 = __esm({ + "packages/playwright-core/src/server/codegen/javascript.ts"() { + "use strict"; + init_locatorGenerators(); + init_stringUtils(); + init_language(); + init_deviceDescriptors(); + JavaScriptLanguageGenerator = class { + constructor(isTest) { + this.groupName = "Node.js"; + this.highlighter = "javascript"; + this.id = isTest ? "playwright-test" : "javascript"; + this.name = isTest ? "Test Runner" : "Library"; + this._isTest = isTest; + } + generateAction(actionInContext) { + const action = actionInContext.action; + if (this._isTest && (action.name === "openPage" || action.name === "closePage")) + return ""; + const pageAlias = actionInContext.frame.pageAlias; + const formatter = new JavaScriptFormatter(2); + if (action.name === "openPage") { + formatter.add(`const ${pageAlias} = await context.newPage();`); + if (action.url && action.url !== "about:blank" && action.url !== "chrome://newtab/") + formatter.add(`await ${pageAlias}.goto(${quote2(action.url)});`); + return formatter.format(); + } + const locators = actionInContext.frame.framePath.map((selector) => `.${this._asLocator(selector)}.contentFrame()`); + const subject = `${pageAlias}${locators.join("")}`; + const signals = toSignalMap(action); + if (signals.dialog) { + formatter.add(` ${pageAlias}.once('dialog', dialog => { + console.log(\`Dialog message: \${dialog.message()}\`); + dialog.dismiss().catch(() => {}); + });`); + } + if (signals.popup) + formatter.add(`const ${signals.popup.popupAlias}Promise = ${pageAlias}.waitForEvent('popup');`); + if (signals.download) + formatter.add(`const download${signals.download.downloadAlias}Promise = ${pageAlias}.waitForEvent('download');`); + formatter.add(wrapWithStep(actionInContext.description, this._generateActionCall(subject, actionInContext))); + if (signals.popup) + formatter.add(`const ${signals.popup.popupAlias} = await ${signals.popup.popupAlias}Promise;`); + if (signals.download) + formatter.add(`const download${signals.download.downloadAlias} = await download${signals.download.downloadAlias}Promise;`); + return formatter.format(); + } + _generateActionCall(subject, actionInContext) { + const action = actionInContext.action; + switch (action.name) { + case "openPage": + throw Error("Not reached"); + case "closePage": + return `await ${subject}.close();`; + case "click": { + let method = "click"; + if (action.clickCount === 2) + method = "dblclick"; + const options2 = toClickOptionsForSourceCode(action); + const optionsString = formatOptions(options2, false); + return `await ${subject}.${this._asLocator(action.selector)}.${method}(${optionsString});`; + } + case "hover": + return `await ${subject}.${this._asLocator(action.selector)}.hover(${formatOptions({ position: action.position }, false)});`; + case "check": + return `await ${subject}.${this._asLocator(action.selector)}.check();`; + case "uncheck": + return `await ${subject}.${this._asLocator(action.selector)}.uncheck();`; + case "fill": + return `await ${subject}.${this._asLocator(action.selector)}.fill(${quote2(action.text)});`; + case "setInputFiles": + return `await ${subject}.${this._asLocator(action.selector)}.setInputFiles(${formatObject(action.files.length === 1 ? action.files[0] : action.files)});`; + case "press": { + const modifiers = toKeyboardModifiers(action.modifiers); + const shortcut = [...modifiers, action.key].join("+"); + return `await ${subject}.${this._asLocator(action.selector)}.press(${quote2(shortcut)});`; + } + case "navigate": + return `await ${subject}.goto(${quote2(action.url)});`; + case "select": + return `await ${subject}.${this._asLocator(action.selector)}.selectOption(${formatObject(action.options.length === 1 ? action.options[0] : action.options)});`; + case "assertText": + return `${this._isTest ? "" : "// "}await expect(${subject}.${this._asLocator(action.selector)}).${action.substring ? "toContainText" : "toHaveText"}(${quote2(action.text)});`; + case "assertChecked": + return `${this._isTest ? "" : "// "}await expect(${subject}.${this._asLocator(action.selector)})${action.checked ? "" : ".not"}.toBeChecked();`; + case "assertVisible": + return `${this._isTest ? "" : "// "}await expect(${subject}.${this._asLocator(action.selector)}).toBeVisible();`; + case "assertValue": { + const assertion = action.value ? `toHaveValue(${quote2(action.value)})` : `toBeEmpty()`; + return `${this._isTest ? "" : "// "}await expect(${subject}.${this._asLocator(action.selector)}).${assertion};`; + } + case "assertSnapshot": { + const commentIfNeeded = this._isTest ? "" : "// "; + return `${commentIfNeeded}await expect(${subject}.${this._asLocator(action.selector)}).toMatchAriaSnapshot(${quoteMultiline(action.ariaSnapshot, `${commentIfNeeded} `)});`; + } + } + } + _asLocator(selector) { + return asLocator("javascript", selector); + } + generateHeader(options2) { + if (this._isTest) + return this.generateTestHeader(options2); + return this.generateStandaloneHeader(options2); + } + generateFooter(saveStorage) { + if (this._isTest) + return this.generateTestFooter(saveStorage); + return this.generateStandaloneFooter(saveStorage); + } + generateTestHeader(options2) { + const formatter = new JavaScriptFormatter(); + const useText = formatContextOptions2(options2.contextOptions, options2.deviceName, this._isTest); + formatter.add(` + import { test, expect${options2.deviceName ? ", devices" : ""} } from '@playwright/test'; +${useText ? "\ntest.use(" + useText + ");\n" : ""} + test('test', async ({ page }) => {`); + if (options2.contextOptions.recordHar) { + const url2 = options2.contextOptions.recordHar.urlFilter; + formatter.add(` await page.routeFromHAR(${quote2(options2.contextOptions.recordHar.path)}${url2 ? `, ${formatOptions({ url: url2 }, false)}` : ""});`); + } + return formatter.format(); + } + generateTestFooter(saveStorage) { + return `});`; + } + generateStandaloneHeader(options2) { + const formatter = new JavaScriptFormatter(); + formatter.add(` + const { ${options2.browserName}${options2.deviceName ? ", devices" : ""} } = require('playwright'); + + (async () => { + const browser = await ${options2.browserName}.launch(${formatObjectOrVoid(options2.launchOptions)}); + const context = await browser.newContext(${formatContextOptions2(options2.contextOptions, options2.deviceName, false)});`); + if (options2.contextOptions.recordHar) + formatter.add(` await context.routeFromHAR(${quote2(options2.contextOptions.recordHar.path)});`); + return formatter.format(); + } + generateStandaloneFooter(saveStorage) { + const storageStateLine = saveStorage ? ` + await context.storageState({ path: ${quote2(saveStorage)} });` : ""; + return ` + // ---------------------${storageStateLine} + await context.close(); + await browser.close(); +})();`; + } + }; + JavaScriptFormatter = class { + constructor(offset = 0) { + this._lines = []; + this._baseIndent = " ".repeat(2); + this._baseOffset = " ".repeat(offset); + } + prepend(text2) { + const trim = isMultilineString(text2) ? (line) => line : (line) => line.trim(); + this._lines = text2.trim().split("\n").map(trim).concat(this._lines); + } + add(text2) { + const trim = isMultilineString(text2) ? (line) => line : (line) => line.trim(); + this._lines.push(...text2.trim().split("\n").map(trim)); + } + newLine() { + this._lines.push(""); + } + format() { + let spaces = ""; + let previousLine = ""; + return this._lines.map((line) => { + if (line === "") + return line; + if (line.startsWith("}") || line.startsWith("]")) + spaces = spaces.substring(this._baseIndent.length); + const extraSpaces = /^(for|while|if|try).*\(.*\)$/.test(previousLine) ? this._baseIndent : ""; + previousLine = line; + const callCarryOver = line.startsWith(".set"); + line = spaces + extraSpaces + (callCarryOver ? this._baseIndent : "") + line; + if (line.endsWith("{") || line.endsWith("[")) + spaces += this._baseIndent; + return this._baseOffset + line; + }).join("\n"); + } + }; + } +}); + +// packages/playwright-core/src/server/codegen/java.ts +function formatPath(files) { + if (Array.isArray(files)) { + if (files.length === 0) + return "new Path[0]"; + return `new Path[] {${files.map((s) => "Paths.get(" + quote3(s) + ")").join(", ")}}`; + } + return `Paths.get(${quote3(files)})`; +} +function formatSelectOption(options2) { + if (Array.isArray(options2)) { + if (options2.length === 0) + return "new String[0]"; + return `new String[] {${options2.map((s) => quote3(s)).join(", ")}}`; + } + return quote3(options2); +} +function formatLaunchOptions(options2) { + const lines = []; + if (!Object.keys(options2).filter((key) => options2[key] !== void 0).length) + return ""; + lines.push("new BrowserType.LaunchOptions()"); + if (options2.channel) + lines.push(` .setChannel(${quote3(options2.channel)})`); + if (typeof options2.headless === "boolean") + lines.push(` .setHeadless(false)`); + return lines.join("\n"); +} +function formatContextOptions3(contextOptions, deviceName) { + const lines = []; + if (!Object.keys(contextOptions).length && !deviceName) + return ""; + const device = deviceName ? deviceDescriptors[deviceName] : {}; + const options2 = { ...device, ...contextOptions }; + lines.push("new Browser.NewContextOptions()"); + if (options2.acceptDownloads) + lines.push(` .setAcceptDownloads(true)`); + if (options2.bypassCSP) + lines.push(` .setBypassCSP(true)`); + if (options2.colorScheme) + lines.push(` .setColorScheme(ColorScheme.${options2.colorScheme.toUpperCase()})`); + if (options2.deviceScaleFactor) + lines.push(` .setDeviceScaleFactor(${options2.deviceScaleFactor})`); + if (options2.geolocation) + lines.push(` .setGeolocation(${options2.geolocation.latitude}, ${options2.geolocation.longitude})`); + if (options2.hasTouch) + lines.push(` .setHasTouch(${options2.hasTouch})`); + if (options2.isMobile) + lines.push(` .setIsMobile(${options2.isMobile})`); + if (options2.locale) + lines.push(` .setLocale(${quote3(options2.locale)})`); + if (options2.proxy) + lines.push(` .setProxy(new Proxy(${quote3(options2.proxy.server)}))`); + if (options2.serviceWorkers) + lines.push(` .setServiceWorkers(ServiceWorkerPolicy.${options2.serviceWorkers.toUpperCase()})`); + if (options2.storageState) + lines.push(` .setStorageStatePath(Paths.get(${quote3(options2.storageState)}))`); + if (options2.timezoneId) + lines.push(` .setTimezoneId(${quote3(options2.timezoneId)})`); + if (options2.userAgent) + lines.push(` .setUserAgent(${quote3(options2.userAgent)})`); + if (options2.viewport) + lines.push(` .setViewportSize(${options2.viewport.width}, ${options2.viewport.height})`); + return lines.join("\n"); +} +function formatClickOptions(options2) { + const lines = []; + if (options2.button) + lines.push(` .setButton(MouseButton.${options2.button.toUpperCase()})`); + if (options2.modifiers) + lines.push(` .setModifiers(Arrays.asList(${options2.modifiers.map((m) => `KeyboardModifier.${m.toUpperCase()}`).join(", ")}))`); + if (options2.clickCount) + lines.push(` .setClickCount(${options2.clickCount})`); + if (options2.position) + lines.push(` .setPosition(${options2.position.x}, ${options2.position.y})`); + if (!lines.length) + return ""; + lines.unshift(`new Locator.ClickOptions()`); + return lines.join("\n"); +} +function quote3(text2) { + return escapeWithQuotes(text2, '"'); +} +var JavaLanguageGenerator; +var init_java = __esm({ + "packages/playwright-core/src/server/codegen/java.ts"() { + "use strict"; + init_locatorGenerators(); + init_stringUtils(); + init_language(); + init_deviceDescriptors(); + init_javascript2(); + JavaLanguageGenerator = class { + constructor(mode) { + this.groupName = "Java"; + this.highlighter = "java"; + if (mode === "library") { + this.name = "Library"; + this.id = "java"; + } else if (mode === "junit") { + this.name = "JUnit"; + this.id = "java-junit"; + } else { + throw new Error(`Unknown Java language mode: ${mode}`); + } + this._mode = mode; + } + generateAction(actionInContext) { + const action = actionInContext.action; + const pageAlias = actionInContext.frame.pageAlias; + const offset = this._mode === "junit" ? 4 : 6; + const formatter = new JavaScriptFormatter(offset); + if (this._mode !== "library" && (action.name === "openPage" || action.name === "closePage")) + return ""; + if (action.name === "openPage") { + formatter.add(`Page ${pageAlias} = context.newPage();`); + if (action.url && action.url !== "about:blank" && action.url !== "chrome://newtab/") + formatter.add(`${pageAlias}.navigate(${quote3(action.url)});`); + return formatter.format(); + } + const locators = actionInContext.frame.framePath.map((selector) => `.${this._asLocator(selector, false)}.contentFrame()`); + const subject = `${pageAlias}${locators.join("")}`; + const signals = toSignalMap(action); + if (signals.dialog) { + formatter.add(` ${pageAlias}.onceDialog(dialog -> { + System.out.println(String.format("Dialog message: %s", dialog.message())); + dialog.dismiss(); + });`); + } + let code = this._generateActionCall(subject, actionInContext, !!actionInContext.frame.framePath.length); + if (signals.popup) { + code = `Page ${signals.popup.popupAlias} = ${pageAlias}.waitForPopup(() -> { + ${code} + });`; + } + if (signals.download) { + code = `Download download${signals.download.downloadAlias} = ${pageAlias}.waitForDownload(() -> { + ${code} + });`; + } + formatter.add(code); + return formatter.format(); + } + _generateActionCall(subject, actionInContext, inFrameLocator) { + const action = actionInContext.action; + switch (action.name) { + case "openPage": + throw Error("Not reached"); + case "closePage": + return `${subject}.close();`; + case "click": { + let method = "click"; + if (action.clickCount === 2) + method = "dblclick"; + const options2 = toClickOptionsForSourceCode(action); + const optionsText = formatClickOptions(options2); + return `${subject}.${this._asLocator(action.selector, inFrameLocator)}.${method}(${optionsText});`; + } + case "hover": { + const optionsText = action.position ? `new Locator.HoverOptions().setPosition(${action.position.x}, ${action.position.y})` : ""; + return `${subject}.${this._asLocator(action.selector, inFrameLocator)}.hover(${optionsText});`; + } + case "check": + return `${subject}.${this._asLocator(action.selector, inFrameLocator)}.check();`; + case "uncheck": + return `${subject}.${this._asLocator(action.selector, inFrameLocator)}.uncheck();`; + case "fill": + return `${subject}.${this._asLocator(action.selector, inFrameLocator)}.fill(${quote3(action.text)});`; + case "setInputFiles": + return `${subject}.${this._asLocator(action.selector, inFrameLocator)}.setInputFiles(${formatPath(action.files.length === 1 ? action.files[0] : action.files)});`; + case "press": { + const modifiers = toKeyboardModifiers(action.modifiers); + const shortcut = [...modifiers, action.key].join("+"); + return `${subject}.${this._asLocator(action.selector, inFrameLocator)}.press(${quote3(shortcut)});`; + } + case "navigate": + return `${subject}.navigate(${quote3(action.url)});`; + case "select": + return `${subject}.${this._asLocator(action.selector, inFrameLocator)}.selectOption(${formatSelectOption(action.options.length === 1 ? action.options[0] : action.options)});`; + case "assertText": + return `assertThat(${subject}.${this._asLocator(action.selector, inFrameLocator)}).${action.substring ? "containsText" : "hasText"}(${quote3(action.text)});`; + case "assertChecked": + return `assertThat(${subject}.${this._asLocator(action.selector, inFrameLocator)})${action.checked ? "" : ".not()"}.isChecked();`; + case "assertVisible": + return `assertThat(${subject}.${this._asLocator(action.selector, inFrameLocator)}).isVisible();`; + case "assertValue": { + const assertion = action.value ? `hasValue(${quote3(action.value)})` : `isEmpty()`; + return `assertThat(${subject}.${this._asLocator(action.selector, inFrameLocator)}).${assertion};`; + } + case "assertSnapshot": + return `assertThat(${subject}.${this._asLocator(action.selector, inFrameLocator)}).matchesAriaSnapshot(${quote3(action.ariaSnapshot)});`; + } + } + _asLocator(selector, inFrameLocator) { + return asLocator("java", selector, inFrameLocator); + } + generateHeader(options2) { + const formatter = new JavaScriptFormatter(); + if (this._mode === "junit") { + formatter.add(` + import com.microsoft.playwright.junit.UsePlaywright; + import com.microsoft.playwright.Page; + import com.microsoft.playwright.options.*; + + ${options2.contextOptions.recordHar ? `import java.nio.file.Paths; +` : ""}import org.junit.jupiter.api.*; + import static com.microsoft.playwright.assertions.PlaywrightAssertions.*; + + @UsePlaywright + public class TestExample { + @Test + void test(Page page) {`); + if (options2.contextOptions.recordHar) { + const url2 = options2.contextOptions.recordHar.urlFilter; + const recordHarOptions = typeof url2 === "string" ? `, new Page.RouteFromHAROptions() + .setUrl(${quote3(url2)})` : ""; + formatter.add(` page.routeFromHAR(Paths.get(${quote3(options2.contextOptions.recordHar.path)})${recordHarOptions});`); + } + return formatter.format(); + } + formatter.add(` + import com.microsoft.playwright.*; + import com.microsoft.playwright.options.*; + import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; + ${options2.contextOptions.recordHar ? `import java.nio.file.Paths; +` : ""}import java.util.*; + + public class Example { + public static void main(String[] args) { + try (Playwright playwright = Playwright.create()) { + Browser browser = playwright.${options2.browserName}().launch(${formatLaunchOptions(options2.launchOptions)}); + BrowserContext context = browser.newContext(${formatContextOptions3(options2.contextOptions, options2.deviceName)});`); + if (options2.contextOptions.recordHar) { + const url2 = options2.contextOptions.recordHar.urlFilter; + const recordHarOptions = typeof url2 === "string" ? `, new BrowserContext.RouteFromHAROptions() + .setUrl(${quote3(url2)})` : ""; + formatter.add(` context.routeFromHAR(Paths.get(${quote3(options2.contextOptions.recordHar.path)})${recordHarOptions});`); + } + return formatter.format(); + } + generateFooter(saveStorage) { + const storageStateLine = saveStorage ? ` + context.storageState(new BrowserContext.StorageStateOptions().setPath(${quote3(saveStorage)})); +` : ""; + if (this._mode === "junit") { + return `${storageStateLine} } +}`; + } + return `${storageStateLine} } + } +}`; + } + }; + } +}); + +// packages/playwright-core/src/server/codegen/jsonl.ts +var JsonlLanguageGenerator; +var init_jsonl = __esm({ + "packages/playwright-core/src/server/codegen/jsonl.ts"() { + "use strict"; + init_locatorGenerators(); + JsonlLanguageGenerator = class { + constructor() { + this.id = "jsonl"; + this.groupName = ""; + this.name = "JSONL"; + this.highlighter = "javascript"; + } + generateAction(actionInContext) { + const locator2 = actionInContext.action.selector ? JSON.parse(asLocator("jsonl", actionInContext.action.selector)) : void 0; + const entry = { + ...actionInContext.action, + ...actionInContext.frame, + locator: locator2, + ariaSnapshot: void 0 + }; + return JSON.stringify(entry); + } + generateHeader(options2) { + return JSON.stringify(options2); + } + generateFooter(saveStorage) { + return ""; + } + }; + } +}); + +// packages/playwright-core/src/server/codegen/python.ts +function formatValue(value2) { + if (value2 === false) + return "False"; + if (value2 === true) + return "True"; + if (value2 === void 0) + return "None"; + if (Array.isArray(value2)) + return `[${value2.map(formatValue).join(", ")}]`; + if (typeof value2 === "string") + return quote4(value2); + if (typeof value2 === "object") + return JSON.stringify(value2); + return String(value2); +} +function formatOptions2(value2, hasArguments, asDict) { + const keys = Object.keys(value2).filter((key) => value2[key] !== void 0).sort(); + if (!keys.length) + return ""; + return (hasArguments ? ", " : "") + keys.map((key) => { + if (asDict) + return `"${toSnakeCase(key)}": ${formatValue(value2[key])}`; + return `${toSnakeCase(key)}=${formatValue(value2[key])}`; + }).join(", "); +} +function formatContextOptions4(options2, deviceName, asDict) { + options2 = { ...options2, recordHar: void 0 }; + const device = deviceName && deviceDescriptors[deviceName]; + if (!device) + return formatOptions2(options2, false, asDict); + return `**playwright.devices[${quote4(deviceName)}]` + formatOptions2(sanitizeDeviceOptions(device, options2), true, asDict); +} +function quote4(text2) { + return escapeWithQuotes(text2, '"'); +} +var PythonLanguageGenerator, PythonFormatter; +var init_python = __esm({ + "packages/playwright-core/src/server/codegen/python.ts"() { + "use strict"; + init_locatorGenerators(); + init_stringUtils(); + init_language(); + init_deviceDescriptors(); + PythonLanguageGenerator = class { + constructor(isAsync, isPyTest) { + this.groupName = "Python"; + this.highlighter = "python"; + this.id = isPyTest ? "python-pytest" : isAsync ? "python-async" : "python"; + this.name = isPyTest ? "Pytest" : isAsync ? "Library Async" : "Library"; + this._isAsync = isAsync; + this._isPyTest = isPyTest; + this._awaitPrefix = isAsync ? "await " : ""; + this._asyncPrefix = isAsync ? "async " : ""; + } + generateAction(actionInContext) { + const action = actionInContext.action; + if (this._isPyTest && (action.name === "openPage" || action.name === "closePage")) + return ""; + const pageAlias = actionInContext.frame.pageAlias; + const formatter = new PythonFormatter(4); + if (action.name === "openPage") { + formatter.add(`${pageAlias} = ${this._awaitPrefix}context.new_page()`); + if (action.url && action.url !== "about:blank" && action.url !== "chrome://newtab/") + formatter.add(`${this._awaitPrefix}${pageAlias}.goto(${quote4(action.url)})`); + return formatter.format(); + } + const locators = actionInContext.frame.framePath.map((selector) => `.${this._asLocator(selector)}.content_frame`); + const subject = `${pageAlias}${locators.join("")}`; + const signals = toSignalMap(action); + if (signals.dialog) + formatter.add(` ${pageAlias}.once("dialog", lambda dialog: dialog.dismiss())`); + let code = `${this._awaitPrefix}${this._generateActionCall(subject, actionInContext)}`; + if (signals.popup) { + code = `${this._asyncPrefix}with ${pageAlias}.expect_popup() as ${signals.popup.popupAlias}_info { + ${code} + } + ${signals.popup.popupAlias} = ${this._awaitPrefix}${signals.popup.popupAlias}_info.value`; + } + if (signals.download) { + code = `${this._asyncPrefix}with ${pageAlias}.expect_download() as download${signals.download.downloadAlias}_info { + ${code} + } + download${signals.download.downloadAlias} = ${this._awaitPrefix}download${signals.download.downloadAlias}_info.value`; + } + formatter.add(code); + return formatter.format(); + } + _generateActionCall(subject, actionInContext) { + const action = actionInContext.action; + switch (action.name) { + case "openPage": + throw Error("Not reached"); + case "closePage": + return `${subject}.close()`; + case "click": { + let method = "click"; + if (action.clickCount === 2) + method = "dblclick"; + const options2 = toClickOptionsForSourceCode(action); + const optionsString = formatOptions2(options2, false); + return `${subject}.${this._asLocator(action.selector)}.${method}(${optionsString})`; + } + case "hover": + return `${subject}.${this._asLocator(action.selector)}.hover(${formatOptions2({ position: action.position }, false)})`; + case "check": + return `${subject}.${this._asLocator(action.selector)}.check()`; + case "uncheck": + return `${subject}.${this._asLocator(action.selector)}.uncheck()`; + case "fill": + return `${subject}.${this._asLocator(action.selector)}.fill(${quote4(action.text)})`; + case "setInputFiles": + return `${subject}.${this._asLocator(action.selector)}.set_input_files(${formatValue(action.files.length === 1 ? action.files[0] : action.files)})`; + case "press": { + const modifiers = toKeyboardModifiers(action.modifiers); + const shortcut = [...modifiers, action.key].join("+"); + return `${subject}.${this._asLocator(action.selector)}.press(${quote4(shortcut)})`; + } + case "navigate": + return `${subject}.goto(${quote4(action.url)})`; + case "select": + return `${subject}.${this._asLocator(action.selector)}.select_option(${formatValue(action.options.length === 1 ? action.options[0] : action.options)})`; + case "assertText": + return `expect(${subject}.${this._asLocator(action.selector)}).${action.substring ? "to_contain_text" : "to_have_text"}(${quote4(action.text)})`; + case "assertChecked": + return `expect(${subject}.${this._asLocator(action.selector)}).${action.checked ? "to_be_checked()" : "not_to_be_checked()"}`; + case "assertVisible": + return `expect(${subject}.${this._asLocator(action.selector)}).to_be_visible()`; + case "assertValue": { + const assertion = action.value ? `to_have_value(${quote4(action.value)})` : `to_be_empty()`; + return `expect(${subject}.${this._asLocator(action.selector)}).${assertion};`; + } + case "assertSnapshot": + return `expect(${subject}.${this._asLocator(action.selector)}).to_match_aria_snapshot(${quote4(action.ariaSnapshot)})`; + } + } + _asLocator(selector) { + return asLocator("python", selector); + } + generateHeader(options2) { + const formatter = new PythonFormatter(); + const recordHar = options2.contextOptions.recordHar; + if (this._isPyTest) { + const contextOptions = formatContextOptions4( + options2.contextOptions, + options2.deviceName, + true + /* asDict */ + ); + const fixture = contextOptions ? ` + +@pytest.fixture(scope="session") +def browser_context_args(browser_context_args, playwright) { + return {${contextOptions}} +} +` : ""; + formatter.add(`${options2.deviceName || contextOptions ? "import pytest\n" : ""}import re +from playwright.sync_api import Page, expect +${fixture} + +def test_example(page: Page) -> None {`); + if (recordHar) + formatter.add(` page.route_from_har(${quote4(recordHar.path)}${typeof recordHar.urlFilter === "string" ? `, url=${quote4(recordHar.urlFilter)}` : ""})`); + } else if (this._isAsync) { + formatter.add(` +import asyncio +import re +from playwright.async_api import Playwright, async_playwright, expect + + +async def run(playwright: Playwright) -> None { + browser = await playwright.${options2.browserName}.launch(${formatOptions2(options2.launchOptions, false)}) + context = await browser.new_context(${formatContextOptions4(options2.contextOptions, options2.deviceName)})`); + if (recordHar) + formatter.add(` await context.route_from_har(${quote4(recordHar.path)}${typeof recordHar.urlFilter === "string" ? `, url=${quote4(recordHar.urlFilter)}` : ""})`); + } else { + formatter.add(` +import re +from playwright.sync_api import Playwright, sync_playwright, expect + + +def run(playwright: Playwright) -> None { + browser = playwright.${options2.browserName}.launch(${formatOptions2(options2.launchOptions, false)}) + context = browser.new_context(${formatContextOptions4(options2.contextOptions, options2.deviceName)})`); + if (recordHar) + formatter.add(` context.route_from_har(${quote4(recordHar.path)}${typeof recordHar.urlFilter === "string" ? `, url=${quote4(recordHar.urlFilter)}` : ""})`); + } + return formatter.format(); + } + generateFooter(saveStorage) { + if (this._isPyTest) { + return ""; + } else if (this._isAsync) { + const storageStateLine = saveStorage ? ` + await context.storage_state(path=${quote4(saveStorage)})` : ""; + return ` + # ---------------------${storageStateLine} + await context.close() + await browser.close() + + +async def main() -> None: + async with async_playwright() as playwright: + await run(playwright) + + +asyncio.run(main()) +`; + } else { + const storageStateLine = saveStorage ? ` + context.storage_state(path=${quote4(saveStorage)})` : ""; + return ` + # ---------------------${storageStateLine} + context.close() + browser.close() + + +with sync_playwright() as playwright: + run(playwright) +`; + } + } + }; + PythonFormatter = class { + constructor(offset = 0) { + this._lines = []; + this._baseIndent = " ".repeat(4); + this._baseOffset = " ".repeat(offset); + } + prepend(text2) { + this._lines = text2.trim().split("\n").map((line) => line.trim()).concat(this._lines); + } + add(text2) { + this._lines.push(...text2.trim().split("\n").map((line) => line.trim())); + } + newLine() { + this._lines.push(""); + } + format() { + let spaces = ""; + const lines = []; + this._lines.forEach((line) => { + if (line === "") + return lines.push(line); + if (line === "}") { + spaces = spaces.substring(this._baseIndent.length); + return; + } + line = spaces + line; + if (line.endsWith("{")) { + spaces += this._baseIndent; + line = line.substring(0, line.length - 1).trimEnd() + ":"; + } + return lines.push(this._baseOffset + line); + }); + return lines.join("\n"); + } + }; + } +}); + +// packages/playwright-core/src/server/codegen/languages.ts +function languageSet() { + return /* @__PURE__ */ new Set([ + new JavaScriptLanguageGenerator( + /* isPlaywrightTest */ + true + ), + new JavaScriptLanguageGenerator( + /* isPlaywrightTest */ + false + ), + new PythonLanguageGenerator( + /* isAsync */ + false, + /* isPytest */ + true + ), + new PythonLanguageGenerator( + /* isAsync */ + false, + /* isPytest */ + false + ), + new PythonLanguageGenerator( + /* isAsync */ + true, + /* isPytest */ + false + ), + new CSharpLanguageGenerator("mstest"), + new CSharpLanguageGenerator("nunit"), + new CSharpLanguageGenerator("xunit"), + new CSharpLanguageGenerator("library"), + new JavaLanguageGenerator("junit"), + new JavaLanguageGenerator("library"), + new JsonlLanguageGenerator() + ]); +} +var init_languages = __esm({ + "packages/playwright-core/src/server/codegen/languages.ts"() { + "use strict"; + init_csharp(); + init_java(); + init_javascript2(); + init_jsonl(); + init_python(); + } +}); + +// packages/playwright-core/src/server/recorder/recorderUtils.ts +function buildFullSelector(framePath, selector) { + return [...framePath, selector].join(" >> internal:control=enter-frame >> "); +} +function metadataToCallLog(metadata, status) { + const title = renderTitleForCall(metadata); + if (metadata.error) + status = "error"; + const params2 = { + url: metadata.params?.url, + selector: metadata.params?.selector + }; + let duration = metadata.endTime ? metadata.endTime - metadata.startTime : void 0; + if (typeof duration === "number" && metadata.pauseStartTime && metadata.pauseEndTime) { + duration -= metadata.pauseEndTime - metadata.pauseStartTime; + duration = Math.max(duration, 0); + } + const callLog = { + id: metadata.id, + messages: metadata.log, + title: title ?? "", + status, + error: metadata.error?.error?.message, + params: params2, + duration + }; + return callLog; +} +function mainFrameForAction(pageAliases, actionInContext) { + const pageAlias = actionInContext.frame.pageAlias; + const page = [...pageAliases.entries()].find(([, alias]) => pageAlias === alias)?.[0]; + if (!page) + throw new Error(`Internal error: page ${pageAlias} not found in [${[...pageAliases.values()]}]`); + return page.mainFrame(); +} +function isSameAction(a, b) { + return a.action.name === b.action.name && a.frame.pageAlias === b.frame.pageAlias && a.frame.framePath.join("|") === b.frame.framePath.join("|"); +} +function isSameSelector(action, lastAction) { + return "selector" in action.action && "selector" in lastAction.action && action.action.selector === lastAction.action.selector; +} +function isShortlyAfter(action, lastAction) { + return action.startTime - lastAction.startTime < 500; +} +function shouldMergeAction(action, lastAction) { + if (!lastAction) + return false; + switch (action.action.name) { + case "fill": + return isSameAction(action, lastAction) && isSameSelector(action, lastAction); + case "navigate": + return isSameAction(action, lastAction); + case "click": + return isSameAction(action, lastAction) && isSameSelector(action, lastAction) && isShortlyAfter(action, lastAction) && action.action.clickCount > lastAction.action.clickCount; + } + return false; +} +function collapseActions(actions) { + const result2 = []; + for (const action of actions) { + const lastAction = result2[result2.length - 1]; + const shouldMerge = shouldMergeAction(action, lastAction); + if (!shouldMerge) { + result2.push(action); + continue; + } + const startTime = result2[result2.length - 1].startTime; + result2[result2.length - 1] = action; + result2[result2.length - 1].startTime = startTime; + } + return result2; +} +async function generateFrameSelector(progress2, frame) { + const selectorPromises = []; + progress2.setAllowConcurrentOrNestedRaces(true); + while (frame) { + const parent = frame.parentFrame(); + if (!parent) + break; + selectorPromises.push(generateFrameSelectorInParent(progress2, parent, frame)); + frame = parent; + } + const result2 = await Promise.all(selectorPromises); + progress2.setAllowConcurrentOrNestedRaces(false); + return result2.reverse(); +} +async function generateFrameSelectorInParent(prgoress, parent, frame) { + const result2 = await raceAgainstDeadline(async () => { + try { + const frameElement = await frame.frameElement(prgoress); + if (!frameElement || !parent) + return; + const utility = await parent.utilityContext(); + const injected = await utility.injectedScript(); + const selector = await injected.evaluate((injected2, element2) => { + return injected2.generateSelectorSimple(element2); + }, frameElement); + return selector; + } catch (e) { + } + }, monotonicTime() + 2e3); + if (!result2.timedOut && result2.result) + return result2.result; + if (frame.name()) + return `iframe[name=${quoteCSSAttributeValue(frame.name())}]`; + return `iframe[src=${quoteCSSAttributeValue(frame.url())}]`; +} +var init_recorderUtils = __esm({ + "packages/playwright-core/src/server/recorder/recorderUtils.ts"() { + "use strict"; + init_protocolFormatter(); + init_timeoutRunner(); + init_time(); + init_stringUtils(); + } +}); + +// packages/playwright-core/src/server/recorder/recorderSignalProcessor.ts +var RecorderSignalProcessor; +var init_recorderSignalProcessor = __esm({ + "packages/playwright-core/src/server/recorder/recorderSignalProcessor.ts"() { + "use strict"; + init_time(); + init_debug(); + init_recorderUtils(); + init_progress(); + RecorderSignalProcessor = class { + constructor(actionSink) { + this._lastAction = null; + this._delegate = actionSink; + } + addAction(actionInContext) { + this._lastAction = actionInContext; + this._delegate.addAction(actionInContext); + } + signal(pageAlias, frame, signal) { + const timestamp = monotonicTime(); + if (signal.name === "navigation" && frame._page.mainFrame() === frame) { + const lastAction = this._lastAction; + const signalThreshold = isUnderTest() ? 500 : 5e3; + let generateGoto = false; + if (!lastAction) + generateGoto = true; + else if (lastAction.action.name !== "click" && lastAction.action.name !== "press" && lastAction.action.name !== "fill") + generateGoto = true; + else if (timestamp - lastAction.startTime > signalThreshold) + generateGoto = true; + if (generateGoto) { + this.addAction({ + frame: { + pageGuid: frame._page.guid, + pageAlias, + framePath: [] + }, + action: { + name: "navigate", + url: frame.url(), + signals: [] + }, + startTime: timestamp, + endTime: timestamp + }); + } + return; + } + generateFrameSelector(nullProgress, frame).then((framePath) => { + const signalInContext = { + frame: { + pageGuid: frame._page.guid, + pageAlias, + framePath + }, + signal, + timestamp + }; + this._delegate.addSignal(signalInContext); + }); + } + }; + } +}); + +// packages/playwright-core/src/generated/pollingRecorderSource.ts +var source5; +var init_pollingRecorderSource = __esm({ + "packages/playwright-core/src/generated/pollingRecorderSource.ts"() { + "use strict"; + source5 = '\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/recorder/pollingRecorder.ts\nvar pollingRecorder_exports = {};\n__export(pollingRecorder_exports, {\n PollingRecorder: () => PollingRecorder,\n default: () => pollingRecorder_default\n});\nmodule.exports = __toCommonJS(pollingRecorder_exports);\n\n// packages/injected/src/recorder/clipPaths.ts\nvar svgJson = { "tagName": "svg", "children": [{ "tagName": "defs", "children": [{ "tagName": "clipPath", "attrs": { "width": "16", "height": "16", "viewBox": "0 0 16 16", "fill": "currentColor", "id": "icon-gripper" }, "children": [{ "tagName": "path", "attrs": { "d": "M5 3h2v2H5zm0 4h2v2H5zm0 4h2v2H5zm4-8h2v2H9zm0 4h2v2H9zm0 4h2v2H9z" } }] }, { "tagName": "clipPath", "attrs": { "width": "16", "height": "16", "viewBox": "0 0 16 16", "fill": "currentColor", "id": "icon-circle-large-filled" }, "children": [{ "tagName": "path", "attrs": { "d": "M8 1a6.8 6.8 0 0 1 1.86.253 6.899 6.899 0 0 1 3.083 1.805 6.903 6.903 0 0 1 1.804 3.083C14.916 6.738 15 7.357 15 8s-.084 1.262-.253 1.86a6.9 6.9 0 0 1-.704 1.674 7.157 7.157 0 0 1-2.516 2.509 6.966 6.966 0 0 1-1.668.71A6.984 6.984 0 0 1 8 15a6.984 6.984 0 0 1-1.86-.246 7.098 7.098 0 0 1-1.674-.711 7.3 7.3 0 0 1-1.415-1.094 7.295 7.295 0 0 1-1.094-1.415 7.098 7.098 0 0 1-.71-1.675A6.985 6.985 0 0 1 1 8c0-.643.082-1.262.246-1.86a6.968 6.968 0 0 1 .711-1.667 7.156 7.156 0 0 1 2.509-2.516 6.895 6.895 0 0 1 1.675-.704A6.808 6.808 0 0 1 8 1z" } }] }, { "tagName": "clipPath", "attrs": { "width": "16", "height": "16", "viewBox": "0 0 16 16", "fill": "currentColor", "id": "icon-stop-circle" }, "children": [{ "tagName": "path", "attrs": { "d": "M6 6h4v4H6z" } }, { "tagName": "path", "attrs": { "fill-rule": "evenodd", "clip-rule": "evenodd", "d": "M8.6 1c1.6.1 3.1.9 4.2 2 1.3 1.4 2 3.1 2 5.1 0 1.6-.6 3.1-1.6 4.4-1 1.2-2.4 2.1-4 2.4-1.6.3-3.2.1-4.6-.7-1.4-.8-2.5-2-3.1-3.5C.9 9.2.8 7.5 1.3 6c.5-1.6 1.4-2.9 2.8-3.8C5.4 1.3 7 .9 8.6 1zm.5 12.9c1.3-.3 2.5-1 3.4-2.1.8-1.1 1.3-2.4 1.2-3.8 0-1.6-.6-3.2-1.7-4.3-1-1-2.2-1.6-3.6-1.7-1.3-.1-2.7.2-3.8 1-1.1.8-1.9 1.9-2.3 3.3-.4 1.3-.4 2.7.2 4 .6 1.3 1.5 2.3 2.7 3 1.2.7 2.6.9 3.9.6z" } }] }, { "tagName": "clipPath", "attrs": { "width": "16", "height": "16", "viewBox": "0 0 16 16", "fill": "currentColor", "id": "icon-inspect" }, "children": [{ "tagName": "path", "attrs": { "fill-rule": "evenodd", "clip-rule": "evenodd", "d": "M1 3l1-1h12l1 1v6h-1V3H2v8h5v1H2l-1-1V3zm14.707 9.707L9 6v9.414l2.707-2.707h4zM10 13V8.414l3.293 3.293h-2L10 13z" } }] }, { "tagName": "clipPath", "attrs": { "width": "16", "height": "16", "viewBox": "0 0 16 16", "fill": "currentColor", "id": "icon-whole-word" }, "children": [{ "tagName": "path", "attrs": { "fill-rule": "evenodd", "clip-rule": "evenodd", "d": "M0 11H1V13H15V11H16V14H15H1H0V11Z" } }, { "tagName": "path", "attrs": { "d": "M6.84048 11H5.95963V10.1406H5.93814C5.555 10.7995 4.99104 11.1289 4.24625 11.1289C3.69839 11.1289 3.26871 10.9839 2.95718 10.6938C2.64924 10.4038 2.49527 10.0189 2.49527 9.53906C2.49527 8.51139 3.10041 7.91341 4.3107 7.74512L5.95963 7.51416C5.95963 6.57959 5.58186 6.1123 4.82632 6.1123C4.16389 6.1123 3.56591 6.33789 3.03238 6.78906V5.88672C3.57307 5.54297 4.19612 5.37109 4.90152 5.37109C6.19416 5.37109 6.84048 6.05501 6.84048 7.42285V11ZM5.95963 8.21777L4.63297 8.40039C4.22476 8.45768 3.91682 8.55973 3.70914 8.70654C3.50145 8.84977 3.39761 9.10579 3.39761 9.47461C3.39761 9.74316 3.4925 9.96338 3.68228 10.1353C3.87564 10.3035 4.13166 10.3877 4.45035 10.3877C4.8872 10.3877 5.24706 10.2355 5.52994 9.93115C5.8164 9.62321 5.95963 9.2347 5.95963 8.76562V8.21777Z" } }, { "tagName": "path", "attrs": { "d": "M9.3475 10.2051H9.32601V11H8.44515V2.85742H9.32601V6.4668H9.3475C9.78076 5.73633 10.4146 5.37109 11.2489 5.37109C11.9543 5.37109 12.5057 5.61816 12.9032 6.1123C13.3042 6.60286 13.5047 7.26172 13.5047 8.08887C13.5047 9.00911 13.2809 9.74674 12.8333 10.3018C12.3857 10.8532 11.7734 11.1289 10.9964 11.1289C10.2695 11.1289 9.71989 10.821 9.3475 10.2051ZM9.32601 7.98682V8.75488C9.32601 9.20964 9.47282 9.59635 9.76644 9.91504C10.0636 10.2301 10.4396 10.3877 10.8944 10.3877C11.4279 10.3877 11.8451 10.1836 12.1458 9.77539C12.4502 9.36719 12.6024 8.79964 12.6024 8.07275C12.6024 7.46045 12.4609 6.98063 12.1781 6.6333C11.8952 6.28597 11.512 6.1123 11.0286 6.1123C10.5166 6.1123 10.1048 6.29134 9.7933 6.64941C9.48177 7.00391 9.32601 7.44971 9.32601 7.98682Z" } }] }, { "tagName": "clipPath", "attrs": { "width": "16", "height": "16", "viewBox": "0 0 16 16", "fill": "currentColor", "id": "icon-eye" }, "children": [{ "tagName": "path", "attrs": { "d": "M7.99993 6.00316C9.47266 6.00316 10.6666 7.19708 10.6666 8.66981C10.6666 10.1426 9.47266 11.3365 7.99993 11.3365C6.52715 11.3365 5.33324 10.1426 5.33324 8.66981C5.33324 7.19708 6.52715 6.00316 7.99993 6.00316ZM7.99993 7.00315C7.07946 7.00315 6.33324 7.74935 6.33324 8.66981C6.33324 9.59028 7.07946 10.3365 7.99993 10.3365C8.9204 10.3365 9.6666 9.59028 9.6666 8.66981C9.6666 7.74935 8.9204 7.00315 7.99993 7.00315ZM7.99993 3.66675C11.0756 3.66675 13.7307 5.76675 14.4673 8.70968C14.5344 8.97755 14.3716 9.24908 14.1037 9.31615C13.8358 9.38315 13.5643 9.22041 13.4973 8.95248C12.8713 6.45205 10.6141 4.66675 7.99993 4.66675C5.38454 4.66675 3.12664 6.45359 2.50182 8.95555C2.43491 9.22341 2.16348 9.38635 1.89557 9.31948C1.62766 9.25255 1.46471 8.98115 1.53162 8.71321C2.26701 5.76856 4.9229 3.66675 7.99993 3.66675Z" } }] }, { "tagName": "clipPath", "attrs": { "width": "16", "height": "16", "viewBox": "0 0 16 16", "fill": "currentColor", "id": "icon-symbol-constant" }, "children": [{ "tagName": "path", "attrs": { "fill-rule": "evenodd", "clip-rule": "evenodd", "d": "M4 6h8v1H4V6zm8 3H4v1h8V9z" } }, { "tagName": "path", "attrs": { "fill-rule": "evenodd", "clip-rule": "evenodd", "d": "M1 4l1-1h12l1 1v8l-1 1H2l-1-1V4zm1 0v8h12V4H2z" } }] }, { "tagName": "clipPath", "attrs": { "width": "16", "height": "16", "viewBox": "0 0 16 16", "fill": "currentColor", "id": "icon-check" }, "children": [{ "tagName": "path", "attrs": { "fill-rule": "evenodd", "clip-rule": "evenodd", "d": "M14.431 3.323l-8.47 10-.79-.036-3.35-4.77.818-.574 2.978 4.24 8.051-9.506.764.646z" } }] }, { "tagName": "clipPath", "attrs": { "width": "16", "height": "16", "viewBox": "0 0 16 16", "fill": "currentColor", "id": "icon-close" }, "children": [{ "tagName": "path", "attrs": { "fill-rule": "evenodd", "clip-rule": "evenodd", "d": "M8 8.707l3.646 3.647.708-.707L8.707 8l3.647-3.646-.707-.708L8 7.293 4.354 3.646l-.707.708L7.293 8l-3.646 3.646.707.708L8 8.707z" } }] }, { "tagName": "clipPath", "attrs": { "width": "16", "height": "16", "viewBox": "0 0 16 16", "fill": "currentColor", "id": "icon-pass" }, "children": [{ "tagName": "path", "attrs": { "d": "M6.27 10.87h.71l4.56-4.56-.71-.71-4.2 4.21-1.92-1.92L4 8.6l2.27 2.27z" } }, { "tagName": "path", "attrs": { "fill-rule": "evenodd", "clip-rule": "evenodd", "d": "M8.6 1c1.6.1 3.1.9 4.2 2 1.3 1.4 2 3.1 2 5.1 0 1.6-.6 3.1-1.6 4.4-1 1.2-2.4 2.1-4 2.4-1.6.3-3.2.1-4.6-.7-1.4-.8-2.5-2-3.1-3.5C.9 9.2.8 7.5 1.3 6c.5-1.6 1.4-2.9 2.8-3.8C5.4 1.3 7 .9 8.6 1zm.5 12.9c1.3-.3 2.5-1 3.4-2.1.8-1.1 1.3-2.4 1.2-3.8 0-1.6-.6-3.2-1.7-4.3-1-1-2.2-1.6-3.6-1.7-1.3-.1-2.7.2-3.8 1-1.1.8-1.9 1.9-2.3 3.3-.4 1.3-.4 2.7.2 4 .6 1.3 1.5 2.3 2.7 3 1.2.7 2.6.9 3.9.6z" } }] }, { "tagName": "clipPath", "attrs": { "width": "16", "height": "16", "viewBox": "0 0 16 16", "fill": "currentColor", "id": "icon-gist" }, "children": [{ "tagName": "path", "attrs": { "fill-rule": "evenodd", "clip-rule": "evenodd", "d": "M10.57 1.14l3.28 3.3.15.36v9.7l-.5.5h-11l-.5-.5v-13l.5-.5h7.72l.35.14zM10 5h3l-3-3v3zM3 2v12h10V6H9.5L9 5.5V2H3zm2.062 7.533l1.817-1.828L6.17 7 4 9.179v.707l2.171 2.174.707-.707-1.816-1.82zM8.8 7.714l.7-.709 2.189 2.175v.709L9.5 12.062l-.705-.709 1.831-1.82L8.8 7.714z" } }] }] }] };\nvar clipPaths_default = svgJson;\n\n// packages/injected/src/recorder/recorder.ts\nvar HighlightColors = {\n multiple: "#f6b26b7f",\n single: "#6fa8dc7f",\n assert: "#8acae480",\n action: "#dc6f6f7f"\n};\nvar NoneTool = class {\n};\nvar InspectTool = class {\n constructor(recorder, assertVisibility) {\n this._hoveredModel = null;\n this._hoveredElement = null;\n this._recorder = recorder;\n this._assertVisibility = assertVisibility;\n }\n cursor() {\n return "pointer";\n }\n uninstall() {\n this._hoveredModel = null;\n this._hoveredElement = null;\n }\n onClick(event) {\n var _a;\n consumeEvent(event);\n if (event.button !== 0)\n return;\n if ((_a = this._hoveredModel) == null ? void 0 : _a.selector)\n this._commit(this._hoveredModel.selector, this._hoveredModel);\n }\n onPointerDown(event) {\n consumeEvent(event);\n }\n onPointerUp(event) {\n consumeEvent(event);\n }\n onMouseDown(event) {\n consumeEvent(event);\n }\n onMouseUp(event) {\n consumeEvent(event);\n }\n onMouseMove(event) {\n var _a;\n consumeEvent(event);\n let target = this._recorder.deepEventTarget(event);\n if (!target.isConnected)\n target = null;\n if (this._hoveredElement === target)\n return;\n this._hoveredElement = target;\n let model = null;\n if (this._hoveredElement) {\n const generated = this._recorder.injectedScript.generateSelector(this._hoveredElement, { testIdAttributeName: this._recorder.state.testIdAttributeName, multiple: false });\n model = {\n selector: generated.selector,\n elements: generated.elements,\n tooltipText: this._recorder.injectedScript.utils.asLocator(this._recorder.state.language, generated.selector),\n color: this._assertVisibility ? HighlightColors.assert : HighlightColors.single\n };\n }\n if (((_a = this._hoveredModel) == null ? void 0 : _a.selector) === (model == null ? void 0 : model.selector))\n return;\n this._hoveredModel = model;\n this._recorder.updateHighlight(model, true);\n }\n onMouseEnter(event) {\n consumeEvent(event);\n }\n onMouseLeave(event) {\n consumeEvent(event);\n const window = this._recorder.injectedScript.window;\n if (window.top !== window && this._recorder.deepEventTarget(event).nodeType === Node.DOCUMENT_NODE)\n this._reset(true);\n }\n onKeyDown(event) {\n consumeEvent(event);\n if (event.key === "Escape") {\n if (this._assertVisibility)\n this._recorder.setMode("recording");\n }\n }\n onKeyUp(event) {\n consumeEvent(event);\n }\n onScroll(event) {\n this._reset(false);\n }\n _commit(selector, model) {\n var _a;\n if (this._assertVisibility) {\n void this._recorder.recordAction({\n name: "assertVisible",\n selector,\n signals: []\n });\n this._recorder.setMode("recording");\n (_a = this._recorder.overlay) == null ? void 0 : _a.flashToolSucceeded("assertingVisibility");\n } else {\n this._recorder.elementPicked(selector, model);\n }\n }\n _reset(userGesture) {\n this._hoveredElement = null;\n this._hoveredModel = null;\n this._recorder.updateHighlight(null, userGesture);\n }\n};\nvar RecordActionTool = class {\n constructor(recorder) {\n this._hoveredModel = null;\n this._hoveredElement = null;\n this._activeModel = null;\n this._expectProgrammaticKeyUp = false;\n this._observer = null;\n this._recorder = recorder;\n this._performingActions = /* @__PURE__ */ new Set();\n this._dialog = new Dialog(recorder);\n }\n cursor() {\n return "pointer";\n }\n _installObserverIfNeeded() {\n var _a;\n if (this._observer)\n return;\n if (!((_a = this._recorder.injectedScript.document) == null ? void 0 : _a.body))\n return;\n this._observer = new MutationObserver((mutations) => {\n if (!this._hoveredElement)\n return;\n for (const mutation of mutations) {\n for (const node of mutation.removedNodes) {\n if (node === this._hoveredElement || node.contains(this._hoveredElement))\n this._resetHoveredModel();\n }\n }\n });\n this._observer.observe(this._recorder.injectedScript.document.body, { childList: true, subtree: true });\n }\n uninstall() {\n var _a;\n (_a = this._observer) == null ? void 0 : _a.disconnect();\n this._observer = null;\n this._hoveredModel = null;\n this._hoveredElement = null;\n this._activeModel = null;\n this._expectProgrammaticKeyUp = false;\n this._dialog.close();\n }\n onClick(event) {\n if (this._dialog.isShowing()) {\n if (event.button === 2 && event.type === "auxclick") {\n consumeEvent(event);\n }\n return;\n }\n if (isRangeInput(this._hoveredElement))\n return;\n if (this._shouldIgnoreMouseEvent(event))\n return;\n if (this._actionInProgress(event))\n return;\n if (this._consumedDueToNoModel(event, this._hoveredModel))\n return;\n if (event.button === 2 && event.type === "auxclick") {\n this._showActionListDialog(this._hoveredModel, event);\n return;\n }\n const checkbox = asCheckbox(this._recorder.deepEventTarget(event));\n if (checkbox && event.detail === 1) {\n this._performAction({\n name: checkbox.checked ? "check" : "uncheck",\n selector: this._hoveredModel.selector,\n signals: []\n });\n return;\n }\n this._cancelPendingClickAction();\n if (event.detail === 1) {\n this._pendingClickAction = {\n action: {\n name: "click",\n selector: this._hoveredModel.selector,\n position: positionForEvent(event),\n signals: [],\n button: buttonForEvent(event),\n modifiers: modifiersForEvent(event),\n clickCount: event.detail\n },\n timeout: this._recorder.injectedScript.utils.builtins.setTimeout(() => this._commitPendingClickAction(), 200)\n };\n }\n }\n onDblClick(event) {\n if (this._dialog.isShowing())\n return;\n if (isRangeInput(this._hoveredElement))\n return;\n if (this._shouldIgnoreMouseEvent(event))\n return;\n if (this._actionInProgress(event))\n return;\n if (this._consumedDueToNoModel(event, this._hoveredModel))\n return;\n this._cancelPendingClickAction();\n this._performAction({\n name: "click",\n selector: this._hoveredModel.selector,\n position: positionForEvent(event),\n signals: [],\n button: buttonForEvent(event),\n modifiers: modifiersForEvent(event),\n clickCount: event.detail\n });\n }\n _commitPendingClickAction() {\n if (this._pendingClickAction)\n this._performAction(this._pendingClickAction.action);\n this._cancelPendingClickAction();\n }\n _cancelPendingClickAction() {\n if (this._pendingClickAction)\n this._recorder.injectedScript.utils.builtins.clearTimeout(this._pendingClickAction.timeout);\n this._pendingClickAction = void 0;\n }\n onContextMenu(event) {\n if (this._dialog.isShowing()) {\n consumeEvent(event);\n return;\n }\n if (this._shouldIgnoreMouseEvent(event))\n return;\n if (this._actionInProgress(event))\n return;\n if (this._consumedDueToNoModel(event, this._hoveredModel))\n return;\n this._showActionListDialog(this._hoveredModel, event);\n }\n onPointerDown(event) {\n if (this._dialog.isShowing())\n return;\n if (this._shouldIgnoreMouseEvent(event))\n return;\n this._consumeWhenAboutToPerform(event);\n }\n onPointerUp(event) {\n if (this._dialog.isShowing())\n return;\n if (this._shouldIgnoreMouseEvent(event))\n return;\n this._consumeWhenAboutToPerform(event);\n }\n onMouseDown(event) {\n if (this._dialog.isShowing())\n return;\n if (this._shouldIgnoreMouseEvent(event))\n return;\n this._consumeWhenAboutToPerform(event);\n this._activeModel = this._hoveredModel;\n }\n onMouseUp(event) {\n if (this._dialog.isShowing())\n return;\n if (this._shouldIgnoreMouseEvent(event))\n return;\n this._consumeWhenAboutToPerform(event);\n }\n onMouseMove(event) {\n if (this._dialog.isShowing())\n return;\n const target = this._recorder.deepEventTarget(event);\n if (this._hoveredElement === target)\n return;\n this._hoveredElement = target;\n this._updateModelForHoveredElement();\n }\n onMouseLeave(event) {\n if (this._dialog.isShowing())\n return;\n const window = this._recorder.injectedScript.window;\n if (window.top !== window && this._recorder.deepEventTarget(event).nodeType === Node.DOCUMENT_NODE) {\n this._hoveredElement = null;\n this._updateModelForHoveredElement();\n }\n }\n onFocus(event) {\n if (this._dialog.isShowing())\n return;\n this._onFocus(true);\n }\n onInput(event) {\n if (this._dialog.isShowing())\n return;\n const target = this._recorder.deepEventTarget(event);\n if (target.nodeName === "INPUT" && target.type.toLowerCase() === "file") {\n this._recordAction({\n name: "setInputFiles",\n selector: this._activeModel.selector,\n signals: [],\n files: [...target.files || []].map((file) => file.name)\n });\n return;\n }\n if (isRangeInput(target)) {\n this._recordAction({\n name: "fill",\n // must use hoveredModel instead of activeModel for it to work in webkit\n selector: this._hoveredModel.selector,\n signals: [],\n text: target.value\n });\n return;\n }\n if (["INPUT", "TEXTAREA"].includes(target.nodeName) || target.isContentEditable) {\n if (target.nodeName === "INPUT" && ["checkbox", "radio"].includes(target.type.toLowerCase())) {\n return;\n }\n if (this._consumedDueWrongTarget(event))\n return;\n this._recordAction({\n name: "fill",\n selector: this._activeModel.selector,\n signals: [],\n text: target.isContentEditable ? target.innerText : target.value\n });\n }\n if (target.nodeName === "SELECT") {\n const selectElement = target;\n this._recordAction({\n name: "select",\n selector: this._activeModel.selector,\n options: [...selectElement.selectedOptions].map((option) => option.value),\n signals: []\n });\n }\n }\n onKeyDown(event) {\n if (this._dialog.isShowing())\n return;\n if (!this._shouldGenerateKeyPressFor(event))\n return;\n if (this._actionInProgress(event)) {\n this._expectProgrammaticKeyUp = true;\n return;\n }\n if (this._consumedDueWrongTarget(event))\n return;\n if (event.key === " ") {\n const checkbox = asCheckbox(this._recorder.deepEventTarget(event));\n if (checkbox && event.detail === 0) {\n this._performAction({\n name: checkbox.checked ? "uncheck" : "check",\n selector: this._activeModel.selector,\n signals: []\n });\n return;\n }\n }\n this._performAction({\n name: "press",\n selector: this._activeModel.selector,\n signals: [],\n key: event.key,\n modifiers: modifiersForEvent(event)\n });\n }\n onKeyUp(event) {\n if (this._dialog.isShowing())\n return;\n if (!this._shouldGenerateKeyPressFor(event))\n return;\n if (!this._expectProgrammaticKeyUp) {\n consumeEvent(event);\n return;\n }\n this._expectProgrammaticKeyUp = false;\n }\n onScroll(event) {\n if (this._dialog.isShowing())\n return;\n this._resetHoveredModel();\n }\n _showActionListDialog(model, event) {\n consumeEvent(event);\n const actionPosition = positionForEvent(event);\n const actions = [\n {\n title: "Click",\n cb: () => this._performAction({\n name: "click",\n selector: model.selector,\n position: actionPosition,\n signals: [],\n button: "left",\n modifiers: 0,\n clickCount: 0\n })\n },\n {\n title: "Right click",\n cb: () => this._performAction({\n name: "click",\n selector: model.selector,\n position: actionPosition,\n signals: [],\n button: "right",\n modifiers: 0,\n clickCount: 0\n })\n },\n {\n title: "Double click",\n cb: () => this._performAction({\n name: "click",\n selector: model.selector,\n position: actionPosition,\n signals: [],\n button: "left",\n modifiers: 0,\n clickCount: 2\n })\n },\n {\n title: "Hover",\n cb: () => this._performAction({\n name: "hover",\n selector: model.selector,\n position: actionPosition,\n signals: []\n })\n },\n {\n title: "Pick locator",\n cb: () => this._recorder.elementPicked(model.selector, model)\n }\n ];\n const listElement = this._recorder.document.createElement("x-pw-action-list");\n listElement.setAttribute("role", "list");\n listElement.setAttribute("aria-label", "Choose action");\n for (const action of actions) {\n const actionElement = this._recorder.document.createElement("x-pw-action-item");\n actionElement.setAttribute("role", "listitem");\n actionElement.textContent = action.title;\n actionElement.setAttribute("aria-label", action.title);\n actionElement.addEventListener("click", () => {\n this._dialog.close();\n action.cb();\n });\n listElement.appendChild(actionElement);\n }\n const dialogElement = this._dialog.show({\n label: "Choose action",\n body: listElement,\n autosize: true\n });\n const anchorBox = this._recorder.highlight.firstTooltipBox() || model.elements[0].getBoundingClientRect();\n const dialogPosition = this._recorder.highlight.tooltipPosition(anchorBox, dialogElement);\n this._dialog.moveTo(dialogPosition.anchorTop, dialogPosition.anchorLeft);\n }\n _resetHoveredModel() {\n this._hoveredModel = null;\n this._hoveredElement = null;\n this._updateHighlight(false);\n }\n _onFocus(userGesture) {\n const activeElement = deepActiveElement(this._recorder.document);\n if (userGesture && activeElement === this._recorder.document.body)\n return;\n const result = activeElement ? this._recorder.injectedScript.generateSelector(activeElement, { testIdAttributeName: this._recorder.state.testIdAttributeName }) : null;\n this._activeModel = result && result.selector ? { ...result, color: HighlightColors.action } : null;\n if (userGesture) {\n this._hoveredElement = activeElement;\n this._updateModelForHoveredElement();\n }\n }\n _shouldIgnoreMouseEvent(event) {\n const target = this._recorder.deepEventTarget(event);\n const nodeName = target.nodeName;\n if (nodeName === "SELECT" || nodeName === "OPTION")\n return true;\n if (nodeName === "INPUT" && ["date", "range"].includes(target.type))\n return true;\n return false;\n }\n _actionInProgress(event) {\n const isKeyEvent = event instanceof KeyboardEvent;\n const isMouseOrPointerEvent = event instanceof MouseEvent || event instanceof PointerEvent;\n for (const action of this._performingActions) {\n if (isKeyEvent && action.name === "press" && event.key === action.key)\n return true;\n if (isMouseOrPointerEvent && (action.name === "click" || action.name === "hover" || action.name === "check" || action.name === "uncheck"))\n return true;\n }\n consumeEvent(event);\n return false;\n }\n _consumedDueToNoModel(event, model) {\n if (model)\n return false;\n consumeEvent(event);\n return true;\n }\n _consumedDueWrongTarget(event) {\n if (this._activeModel && this._activeModel.elements[0] === this._recorder.deepEventTarget(event))\n return false;\n consumeEvent(event);\n return true;\n }\n _consumeWhenAboutToPerform(event) {\n if (!this._performingActions.size)\n consumeEvent(event);\n }\n _reportPerformedActionForTests() {\n if (!this._recorder.injectedScript.isUnderTest)\n return;\n console.error("Action performed for test: " + JSON.stringify({\n // eslint-disable-line no-console\n hovered: this._hoveredModel ? this._hoveredModel.selector : null,\n active: this._activeModel ? this._activeModel.selector : null\n }));\n }\n _recordAction(action) {\n void this._recorder.recordAction(action).then(() => this._reportPerformedActionForTests());\n }\n _performAction(action) {\n this._recorder.updateHighlight(null, false);\n this._performingActions.add(action);\n void this._recorder.performAction(action).finally(() => {\n this._performingActions.delete(action);\n this._onFocus(false);\n }).then(() => this._reportPerformedActionForTests());\n }\n _shouldGenerateKeyPressFor(event) {\n if (typeof event.key !== "string")\n return false;\n if (event.key === "Enter" && (this._recorder.deepEventTarget(event).nodeName === "TEXTAREA" || this._recorder.deepEventTarget(event).isContentEditable))\n return false;\n if (["Backspace", "Delete", "AltGraph"].includes(event.key))\n return false;\n if (event.key === "@" && event.code === "KeyL")\n return false;\n if (navigator.platform.includes("Mac")) {\n if (event.key === "v" && event.metaKey)\n return false;\n } else {\n if (event.key === "v" && event.ctrlKey)\n return false;\n if (event.key === "Insert" && event.shiftKey)\n return false;\n }\n if (["Shift", "Control", "Meta", "Alt", "Process"].includes(event.key))\n return false;\n const hasModifier = event.ctrlKey || event.altKey || event.metaKey;\n if (event.key.length === 1 && !hasModifier)\n return !!asCheckbox(this._recorder.deepEventTarget(event));\n return true;\n }\n _updateModelForHoveredElement() {\n this._installObserverIfNeeded();\n if (this._performingActions.size)\n return;\n if (!this._hoveredElement || !this._hoveredElement.isConnected) {\n this._hoveredModel = null;\n this._hoveredElement = null;\n this._updateHighlight(true);\n return;\n }\n const { selector, elements } = this._recorder.injectedScript.generateSelector(this._hoveredElement, { testIdAttributeName: this._recorder.state.testIdAttributeName });\n if (this._hoveredModel && this._hoveredModel.selector === selector)\n return;\n this._hoveredModel = selector ? { selector, elements, color: HighlightColors.action } : null;\n this._updateHighlight(true);\n }\n _updateHighlight(userGesture) {\n this._recorder.updateHighlight(this._hoveredModel, userGesture);\n }\n};\nvar JsonRecordActionTool = class {\n constructor(recorder) {\n this._recorder = recorder;\n }\n install() {\n this._recorder.highlight.uninstall();\n }\n uninstall() {\n this._recorder.highlight.install();\n }\n onClick(event) {\n const element = this._recorder.deepEventTarget(event);\n if (isRangeInput(element))\n return;\n if (event.button === 2 && event.type === "auxclick")\n return;\n if (this._shouldIgnoreMouseEvent(event))\n return;\n const checkbox = asCheckbox(element);\n const { ariaSnapshot, selector, ref } = this._ariaSnapshot(element);\n if (checkbox && event.detail === 1) {\n void this._recorder.recordAction({\n name: checkbox.checked ? "check" : "uncheck",\n selector,\n ref,\n signals: [],\n ariaSnapshot\n });\n return;\n }\n void this._recorder.recordAction({\n name: "click",\n selector,\n ref,\n ariaSnapshot,\n position: positionForEvent(event),\n signals: [],\n button: buttonForEvent(event),\n modifiers: modifiersForEvent(event),\n clickCount: event.detail\n });\n }\n onContextMenu(event) {\n const element = this._recorder.deepEventTarget(event);\n const { ariaSnapshot, selector, ref } = this._ariaSnapshot(element);\n void this._recorder.recordAction({\n name: "click",\n selector,\n ref,\n ariaSnapshot,\n position: positionForEvent(event),\n signals: [],\n button: "right",\n modifiers: modifiersForEvent(event),\n clickCount: 1\n });\n }\n onInput(event) {\n const element = this._recorder.deepEventTarget(event);\n const { ariaSnapshot, selector, ref } = this._ariaSnapshot(element);\n if (isRangeInput(element)) {\n void this._recorder.recordAction({\n name: "fill",\n selector,\n ref,\n ariaSnapshot,\n signals: [],\n text: element.value\n });\n return;\n }\n if (["INPUT", "TEXTAREA"].includes(element.nodeName) || element.isContentEditable) {\n if (element.nodeName === "INPUT" && ["checkbox", "radio"].includes(element.type.toLowerCase())) {\n return;\n }\n void this._recorder.recordAction({\n name: "fill",\n ref,\n selector,\n ariaSnapshot,\n signals: [],\n text: element.isContentEditable ? element.innerText : element.value\n });\n return;\n }\n if (element.nodeName === "SELECT") {\n const selectElement = element;\n void this._recorder.recordAction({\n name: "select",\n selector,\n ref,\n ariaSnapshot,\n options: [...selectElement.selectedOptions].map((option) => option.value),\n signals: []\n });\n return;\n }\n }\n onKeyDown(event) {\n if (!this._shouldGenerateKeyPressFor(event))\n return;\n const element = this._recorder.deepEventTarget(event);\n const { ariaSnapshot, selector, ref } = this._ariaSnapshot(element);\n if (event.key === " ") {\n const checkbox = asCheckbox(element);\n if (checkbox && event.detail === 0) {\n void this._recorder.recordAction({\n name: checkbox.checked ? "uncheck" : "check",\n selector,\n ref,\n ariaSnapshot,\n signals: []\n });\n return;\n }\n }\n void this._recorder.recordAction({\n name: "press",\n selector,\n ref,\n ariaSnapshot,\n signals: [],\n key: event.key,\n modifiers: modifiersForEvent(event)\n });\n }\n _shouldIgnoreMouseEvent(event) {\n const target = this._recorder.deepEventTarget(event);\n const nodeName = target.nodeName;\n if (nodeName === "SELECT" || nodeName === "OPTION")\n return true;\n if (nodeName === "INPUT" && ["date", "range"].includes(target.type))\n return true;\n return false;\n }\n _shouldGenerateKeyPressFor(event) {\n if (typeof event.key !== "string")\n return false;\n if (event.key === "Enter" && (this._recorder.deepEventTarget(event).nodeName === "TEXTAREA" || this._recorder.deepEventTarget(event).isContentEditable))\n return false;\n if (["Backspace", "Delete", "AltGraph"].includes(event.key))\n return false;\n if (event.key === "@" && event.code === "KeyL")\n return false;\n if (navigator.platform.includes("Mac")) {\n if (event.key === "v" && event.metaKey)\n return false;\n } else {\n if (event.key === "v" && event.ctrlKey)\n return false;\n if (event.key === "Insert" && event.shiftKey)\n return false;\n }\n if (["Shift", "Control", "Meta", "Alt", "Process"].includes(event.key))\n return false;\n const hasModifier = event.ctrlKey || event.altKey || event.metaKey;\n if (event.key.length === 1 && !hasModifier)\n return !this._isEditable(this._recorder.deepEventTarget(event));\n return true;\n }\n _isEditable(element) {\n if (element.nodeName === "TEXTAREA" || element.nodeName === "INPUT")\n return true;\n if (element.isContentEditable)\n return true;\n return false;\n }\n _ariaSnapshot(element) {\n const { ariaSnapshot, refs } = this._recorder.injectedScript.ariaSnapshotForRecorder();\n const ref = element ? refs.get(element) : void 0;\n const elementInfo = element ? this._recorder.injectedScript.generateSelector(element, { testIdAttributeName: this._recorder.state.testIdAttributeName }) : void 0;\n return { ariaSnapshot, selector: elementInfo == null ? void 0 : elementInfo.selector, ref };\n }\n};\nvar TextAssertionTool = class {\n constructor(recorder, kind) {\n this._hoverHighlight = null;\n this._action = null;\n this._recorder = recorder;\n this._textCache = /* @__PURE__ */ new Map();\n this._kind = kind;\n this._dialog = new Dialog(recorder);\n }\n cursor() {\n return "pointer";\n }\n uninstall() {\n this._dialog.close();\n this._hoverHighlight = null;\n }\n onClick(event) {\n consumeEvent(event);\n if (this._kind === "value") {\n this._commitAssertValue();\n } else {\n if (!this._dialog.isShowing())\n this._showDialog();\n }\n }\n onMouseDown(event) {\n const target = this._recorder.deepEventTarget(event);\n if (this._elementHasValue(target))\n event.preventDefault();\n }\n onPointerUp(event) {\n var _a;\n const target = (_a = this._hoverHighlight) == null ? void 0 : _a.elements[0];\n if (this._kind === "value" && target && (target.nodeName === "INPUT" || target.nodeName === "SELECT") && target.disabled) {\n this._commitAssertValue();\n }\n }\n onMouseMove(event) {\n var _a;\n if (this._dialog.isShowing())\n return;\n const target = this._recorder.deepEventTarget(event);\n if (((_a = this._hoverHighlight) == null ? void 0 : _a.elements[0]) === target)\n return;\n if (this._kind === "text" || this._kind === "snapshot") {\n this._hoverHighlight = this._recorder.injectedScript.utils.elementText(this._textCache, target).full ? { elements: [target], selector: "", color: HighlightColors.assert } : null;\n } else if (this._elementHasValue(target)) {\n const generated = this._recorder.injectedScript.generateSelector(target, { testIdAttributeName: this._recorder.state.testIdAttributeName });\n this._hoverHighlight = { selector: generated.selector, elements: generated.elements, color: HighlightColors.assert };\n } else {\n this._hoverHighlight = null;\n }\n this._recorder.updateHighlight(this._hoverHighlight, true);\n }\n onKeyDown(event) {\n if (event.key === "Escape")\n this._recorder.setMode("recording");\n consumeEvent(event);\n }\n onScroll(event) {\n this._recorder.updateHighlight(this._hoverHighlight, false);\n }\n _elementHasValue(element) {\n return element.nodeName === "TEXTAREA" || element.nodeName === "SELECT" || element.nodeName === "INPUT" && !["button", "image", "reset", "submit"].includes(element.type);\n }\n _generateAction() {\n var _a;\n this._textCache.clear();\n const target = (_a = this._hoverHighlight) == null ? void 0 : _a.elements[0];\n if (!target)\n return null;\n if (this._kind === "value") {\n if (!this._elementHasValue(target))\n return null;\n const { selector } = this._recorder.injectedScript.generateSelector(target, { testIdAttributeName: this._recorder.state.testIdAttributeName });\n if (target.nodeName === "INPUT" && ["checkbox", "radio"].includes(target.type.toLowerCase())) {\n return {\n name: "assertChecked",\n selector,\n signals: [],\n // Interestingly, inputElement.checked is reversed inside this event handler.\n checked: !target.checked\n };\n } else {\n return {\n name: "assertValue",\n selector,\n signals: [],\n value: target.value\n };\n }\n } else if (this._kind === "snapshot") {\n const generated = this._recorder.injectedScript.generateSelector(target, { testIdAttributeName: this._recorder.state.testIdAttributeName, forTextExpect: true });\n this._hoverHighlight = { selector: generated.selector, elements: generated.elements, color: HighlightColors.assert };\n this._recorder.updateHighlight(this._hoverHighlight, true);\n return {\n name: "assertSnapshot",\n selector: this._hoverHighlight.selector,\n signals: [],\n ariaSnapshot: this._recorder.injectedScript.ariaSnapshot(target, { mode: "codegen" })\n };\n } else {\n const generated = this._recorder.injectedScript.generateSelector(target, { testIdAttributeName: this._recorder.state.testIdAttributeName, forTextExpect: true });\n this._hoverHighlight = { selector: generated.selector, elements: generated.elements, color: HighlightColors.assert };\n this._recorder.updateHighlight(this._hoverHighlight, true);\n return {\n name: "assertText",\n selector: this._hoverHighlight.selector,\n signals: [],\n text: this._recorder.injectedScript.utils.elementText(this._textCache, target).normalized,\n substring: true\n };\n }\n }\n _renderValue(action) {\n if ((action == null ? void 0 : action.name) === "assertText")\n return this._recorder.injectedScript.utils.normalizeWhiteSpace(action.text);\n if ((action == null ? void 0 : action.name) === "assertChecked")\n return String(action.checked);\n if ((action == null ? void 0 : action.name) === "assertValue")\n return action.value;\n if ((action == null ? void 0 : action.name) === "assertSnapshot")\n return action.ariaSnapshot;\n return "";\n }\n _commit() {\n if (!this._action || !this._dialog.isShowing())\n return;\n this._dialog.close();\n void this._recorder.recordAction(this._action);\n this._recorder.setMode("recording");\n }\n _showDialog() {\n var _a, _b, _c, _d;\n if (!((_a = this._hoverHighlight) == null ? void 0 : _a.elements[0]))\n return;\n this._action = this._generateAction();\n if (((_b = this._action) == null ? void 0 : _b.name) === "assertText") {\n this._showTextDialog(this._action);\n } else if (((_c = this._action) == null ? void 0 : _c.name) === "assertSnapshot") {\n void this._recorder.recordAction(this._action);\n this._recorder.setMode("recording");\n (_d = this._recorder.overlay) == null ? void 0 : _d.flashToolSucceeded("assertingSnapshot");\n }\n }\n _showTextDialog(action) {\n const textElement = this._recorder.document.createElement("textarea");\n textElement.setAttribute("spellcheck", "false");\n textElement.value = this._renderValue(action);\n textElement.classList.add("text-editor");\n const updateAndValidate = () => {\n var _a;\n const newValue = this._recorder.injectedScript.utils.normalizeWhiteSpace(textElement.value);\n const target = (_a = this._hoverHighlight) == null ? void 0 : _a.elements[0];\n if (!target)\n return;\n action.text = newValue;\n const targetText = this._recorder.injectedScript.utils.elementText(this._textCache, target).normalized;\n const matches = newValue && targetText.includes(newValue);\n textElement.classList.toggle("does-not-match", !matches);\n };\n textElement.addEventListener("input", updateAndValidate);\n const label = "Assert that element contains text";\n const dialogElement = this._dialog.show({\n label,\n body: textElement,\n onCommit: () => this._commit()\n });\n const position = this._recorder.highlight.tooltipPosition(this._recorder.highlight.firstBox(), dialogElement);\n this._dialog.moveTo(position.anchorTop, position.anchorLeft);\n textElement.focus();\n }\n _commitAssertValue() {\n var _a;\n if (this._kind !== "value")\n return;\n const action = this._generateAction();\n if (!action)\n return;\n void this._recorder.recordAction(action);\n this._recorder.setMode("recording");\n (_a = this._recorder.overlay) == null ? void 0 : _a.flashToolSucceeded("assertingValue");\n }\n};\nvar Overlay = class {\n constructor(recorder) {\n this._listeners = [];\n this._offsetX = 0;\n this._measure = { width: 0, height: 0 };\n this._recorder = recorder;\n const document = this._recorder.document;\n this._overlayElement = document.createElement("x-pw-overlay");\n const toolsListElement = document.createElement("x-pw-tools-list");\n this._overlayElement.appendChild(toolsListElement);\n this._dragHandle = document.createElement("x-pw-tool-gripper");\n this._dragHandle.appendChild(document.createElement("x-div"));\n toolsListElement.appendChild(this._dragHandle);\n this._recordToggle = this._recorder.document.createElement("x-pw-tool-item");\n this._recordToggle.title = "Record";\n this._recordToggle.classList.add("record");\n this._recordToggle.appendChild(this._recorder.document.createElement("x-div"));\n toolsListElement.appendChild(this._recordToggle);\n this._pickLocatorToggle = this._recorder.document.createElement("x-pw-tool-item");\n this._pickLocatorToggle.title = "Pick locator";\n this._pickLocatorToggle.classList.add("pick-locator");\n this._pickLocatorToggle.appendChild(this._recorder.document.createElement("x-div"));\n toolsListElement.appendChild(this._pickLocatorToggle);\n this._assertVisibilityToggle = this._recorder.document.createElement("x-pw-tool-item");\n this._assertVisibilityToggle.title = "Assert visibility";\n this._assertVisibilityToggle.classList.add("visibility");\n this._assertVisibilityToggle.appendChild(this._recorder.document.createElement("x-div"));\n toolsListElement.appendChild(this._assertVisibilityToggle);\n this._assertTextToggle = this._recorder.document.createElement("x-pw-tool-item");\n this._assertTextToggle.title = "Assert text";\n this._assertTextToggle.classList.add("text");\n this._assertTextToggle.appendChild(this._recorder.document.createElement("x-div"));\n toolsListElement.appendChild(this._assertTextToggle);\n this._assertValuesToggle = this._recorder.document.createElement("x-pw-tool-item");\n this._assertValuesToggle.title = "Assert value";\n this._assertValuesToggle.classList.add("value");\n this._assertValuesToggle.appendChild(this._recorder.document.createElement("x-div"));\n toolsListElement.appendChild(this._assertValuesToggle);\n this._assertSnapshotToggle = this._recorder.document.createElement("x-pw-tool-item");\n this._assertSnapshotToggle.title = "Assert snapshot";\n this._assertSnapshotToggle.classList.add("snapshot");\n this._assertSnapshotToggle.appendChild(this._recorder.document.createElement("x-div"));\n toolsListElement.appendChild(this._assertSnapshotToggle);\n this._updateVisualPosition();\n this._refreshListeners();\n }\n _refreshListeners() {\n removeEventListeners(this._listeners);\n this._listeners = [\n addEventListener(this._dragHandle, "mousedown", (event) => {\n this._dragState = { offsetX: this._offsetX, dragStart: { x: event.clientX, y: 0 } };\n }),\n addEventListener(this._recordToggle, "click", () => {\n if (this._recordToggle.classList.contains("disabled"))\n return;\n this._recorder.setMode(this._recorder.state.mode === "none" || this._recorder.state.mode === "standby" || this._recorder.state.mode === "inspecting" ? "recording" : "standby");\n }),\n addEventListener(this._pickLocatorToggle, "click", () => {\n if (this._pickLocatorToggle.classList.contains("disabled"))\n return;\n const newMode = {\n "inspecting": "standby",\n "none": "inspecting",\n "standby": "inspecting",\n "recording": "recording-inspecting",\n "recording-inspecting": "recording",\n "assertingText": "recording-inspecting",\n "assertingVisibility": "recording-inspecting",\n "assertingValue": "recording-inspecting",\n "assertingSnapshot": "recording-inspecting"\n };\n this._recorder.setMode(newMode[this._recorder.state.mode]);\n }),\n addEventListener(this._assertVisibilityToggle, "click", () => {\n if (!this._assertVisibilityToggle.classList.contains("disabled"))\n this._recorder.setMode(this._recorder.state.mode === "assertingVisibility" ? "recording" : "assertingVisibility");\n }),\n addEventListener(this._assertTextToggle, "click", () => {\n if (!this._assertTextToggle.classList.contains("disabled"))\n this._recorder.setMode(this._recorder.state.mode === "assertingText" ? "recording" : "assertingText");\n }),\n addEventListener(this._assertValuesToggle, "click", () => {\n if (!this._assertValuesToggle.classList.contains("disabled"))\n this._recorder.setMode(this._recorder.state.mode === "assertingValue" ? "recording" : "assertingValue");\n }),\n addEventListener(this._assertSnapshotToggle, "click", () => {\n if (!this._assertSnapshotToggle.classList.contains("disabled"))\n this._recorder.setMode(this._recorder.state.mode === "assertingSnapshot" ? "recording" : "assertingSnapshot");\n })\n ];\n }\n install() {\n this._recorder.highlight.appendChild(this._overlayElement);\n this._refreshListeners();\n this._updateVisualPosition();\n }\n contains(element) {\n return this._recorder.injectedScript.utils.isInsideScope(this._overlayElement, element);\n }\n setUIState(state) {\n const isRecording = state.mode === "recording" || state.mode === "assertingText" || state.mode === "assertingVisibility" || state.mode === "assertingValue" || state.mode === "assertingSnapshot" || state.mode === "recording-inspecting";\n this._recordToggle.classList.toggle("toggled", isRecording);\n this._recordToggle.title = isRecording ? "Stop Recording" : "Start Recording";\n this._pickLocatorToggle.classList.toggle("toggled", state.mode === "inspecting" || state.mode === "recording-inspecting");\n this._assertVisibilityToggle.classList.toggle("toggled", state.mode === "assertingVisibility");\n this._assertVisibilityToggle.classList.toggle("disabled", state.mode === "none" || state.mode === "standby" || state.mode === "inspecting");\n this._assertTextToggle.classList.toggle("toggled", state.mode === "assertingText");\n this._assertTextToggle.classList.toggle("disabled", state.mode === "none" || state.mode === "standby" || state.mode === "inspecting");\n this._assertValuesToggle.classList.toggle("toggled", state.mode === "assertingValue");\n this._assertValuesToggle.classList.toggle("disabled", state.mode === "none" || state.mode === "standby" || state.mode === "inspecting");\n this._assertSnapshotToggle.classList.toggle("toggled", state.mode === "assertingSnapshot");\n this._assertSnapshotToggle.classList.toggle("disabled", state.mode === "none" || state.mode === "standby" || state.mode === "inspecting");\n if (this._offsetX !== state.overlay.offsetX) {\n this._offsetX = state.overlay.offsetX;\n this._updateVisualPosition();\n }\n if (state.mode === "none")\n this._hideOverlay();\n else\n this._showOverlay();\n }\n flashToolSucceeded(tool) {\n let element;\n if (tool === "assertingVisibility")\n element = this._assertVisibilityToggle;\n else if (tool === "assertingSnapshot")\n element = this._assertSnapshotToggle;\n else\n element = this._assertValuesToggle;\n element.classList.add("succeeded");\n this._recorder.injectedScript.utils.builtins.setTimeout(() => element.classList.remove("succeeded"), 2e3);\n }\n _hideOverlay() {\n this._overlayElement.setAttribute("hidden", "true");\n }\n _showOverlay() {\n if (!this._overlayElement.hasAttribute("hidden"))\n return;\n this._overlayElement.removeAttribute("hidden");\n this._updateVisualPosition();\n }\n _updateVisualPosition() {\n this._measure = this._overlayElement.getBoundingClientRect();\n this._overlayElement.style.left = (this._recorder.injectedScript.window.innerWidth - this._measure.width) / 2 + this._offsetX + "px";\n }\n onMouseMove(event) {\n if (!event.buttons) {\n this._dragState = void 0;\n return false;\n }\n if (this._dragState) {\n this._offsetX = this._dragState.offsetX + event.clientX - this._dragState.dragStart.x;\n const halfGapSize = (this._recorder.injectedScript.window.innerWidth - this._measure.width) / 2 - 10;\n this._offsetX = Math.max(-halfGapSize, Math.min(halfGapSize, this._offsetX));\n this._updateVisualPosition();\n this._recorder.setOverlayState({ offsetX: this._offsetX });\n consumeEvent(event);\n return true;\n }\n return false;\n }\n onMouseUp(event) {\n if (this._dragState) {\n consumeEvent(event);\n return true;\n }\n return false;\n }\n onClick(event) {\n if (this._dragState) {\n this._dragState = void 0;\n consumeEvent(event);\n return true;\n }\n return false;\n }\n onDblClick(event) {\n return false;\n }\n};\nvar Recorder = class {\n constructor(injectedScript, options) {\n this._listeners = [];\n this._lastHighlightedSelector = void 0;\n this._lastHighlightedAriaTemplateJSON = "undefined";\n this.state = {\n mode: "none",\n testIdAttributeName: "data-testid",\n language: "javascript",\n overlay: { offsetX: 0 }\n };\n this._delegate = {};\n var _a, _b;\n this.document = injectedScript.document;\n this.injectedScript = injectedScript;\n this.highlight = injectedScript.createHighlight();\n this._tools = {\n "none": new NoneTool(),\n "standby": new NoneTool(),\n "inspecting": new InspectTool(this, false),\n "recording": (options == null ? void 0 : options.recorderMode) === "api" ? new JsonRecordActionTool(this) : new RecordActionTool(this),\n "recording-inspecting": new InspectTool(this, false),\n "assertingText": new TextAssertionTool(this, "text"),\n "assertingVisibility": new InspectTool(this, true),\n "assertingValue": new TextAssertionTool(this, "value"),\n "assertingSnapshot": new TextAssertionTool(this, "snapshot")\n };\n this._currentTool = this._tools.none;\n (_b = (_a = this._currentTool).install) == null ? void 0 : _b.call(_a);\n if (injectedScript.window.top === injectedScript.window && !(options == null ? void 0 : options.hideToolbar)) {\n this.overlay = new Overlay(this);\n this.overlay.setUIState(this.state);\n }\n this._stylesheet = new injectedScript.window.CSSStyleSheet();\n this._stylesheet.replaceSync(`\n body[data-pw-cursor=pointer] *, body[data-pw-cursor=pointer] *::after { cursor: pointer !important; }\n body[data-pw-cursor=text] *, body[data-pw-cursor=text] *::after { cursor: text !important; }\n `);\n this.installListeners();\n injectedScript.utils.cacheNormalizedWhitespaces();\n if (injectedScript.isUnderTest)\n console.error("Recorder script ready for test");\n injectedScript.consoleApi.install();\n }\n installListeners() {\n var _a, _b, _c;\n removeEventListeners(this._listeners);\n this._listeners = [\n addEventListener(this.document, "click", (event) => this._onClick(event), true),\n addEventListener(this.document, "auxclick", (event) => this._onClick(event), true),\n addEventListener(this.document, "dblclick", (event) => this._onDblClick(event), true),\n addEventListener(this.document, "contextmenu", (event) => this._onContextMenu(event), true),\n addEventListener(this.document, "dragstart", (event) => this._onDragStart(event), true),\n addEventListener(this.document, "input", (event) => this._onInput(event), true),\n addEventListener(this.document, "keydown", (event) => this._onKeyDown(event), true),\n addEventListener(this.document, "keyup", (event) => this._onKeyUp(event), true),\n addEventListener(this.document, "pointerdown", (event) => this._onPointerDown(event), true),\n addEventListener(this.document, "pointerup", (event) => this._onPointerUp(event), true),\n addEventListener(this.document, "mousedown", (event) => this._onMouseDown(event), true),\n addEventListener(this.document, "mouseup", (event) => this._onMouseUp(event), true),\n addEventListener(this.document, "mousemove", (event) => this._onMouseMove(event), true),\n addEventListener(this.document, "mouseleave", (event) => this._onMouseLeave(event), true),\n addEventListener(this.document, "mouseenter", (event) => this._onMouseEnter(event), true),\n addEventListener(this.document, "focus", (event) => this._onFocus(event), true),\n addEventListener(this.document, "scroll", (event) => this._onScroll(event), true)\n ];\n this.highlight.install();\n let recreationInterval;\n const recreate = () => {\n this.highlight.install();\n recreationInterval = this.injectedScript.utils.builtins.setTimeout(recreate, 500);\n };\n recreationInterval = this.injectedScript.utils.builtins.setTimeout(recreate, 500);\n this._listeners.push(() => this.injectedScript.utils.builtins.clearTimeout(recreationInterval));\n this.highlight.appendChild(createSvgElement(this.document, clipPaths_default));\n (_a = this.overlay) == null ? void 0 : _a.install();\n (_c = (_b = this._currentTool) == null ? void 0 : _b.install) == null ? void 0 : _c.call(_b);\n this.document.adoptedStyleSheets.push(this._stylesheet);\n }\n _switchCurrentTool() {\n var _a, _b, _c, _d, _e, _f;\n const newTool = this._tools[this.state.mode];\n if (newTool === this._currentTool)\n return;\n (_b = (_a = this._currentTool).uninstall) == null ? void 0 : _b.call(_a);\n this.clearHighlight();\n this._currentTool = newTool;\n (_d = (_c = this._currentTool).install) == null ? void 0 : _d.call(_c);\n const cursor = (_e = newTool.cursor) == null ? void 0 : _e.call(newTool);\n if (cursor)\n (_f = this.injectedScript.document.body) == null ? void 0 : _f.setAttribute("data-pw-cursor", cursor);\n }\n setUIState(state, delegate) {\n var _a;\n this._delegate = delegate;\n if (state.actionPoint && this.state.actionPoint && state.actionPoint.x === this.state.actionPoint.x && state.actionPoint.y === this.state.actionPoint.y) {\n } else if (!state.actionPoint && !this.state.actionPoint) {\n } else {\n if (state.actionPoint)\n this.highlight.showActionPoint(state.actionPoint.x, state.actionPoint.y);\n else\n this.highlight.hideActionPoint();\n }\n this.state = state;\n this.highlight.setLanguage(state.language);\n this._switchCurrentTool();\n (_a = this.overlay) == null ? void 0 : _a.setUIState(state);\n let highlight = "noop";\n if (state.actionSelector !== this._lastHighlightedSelector) {\n const entries = state.actionSelector ? entriesForSelectorHighlight(this.injectedScript, state.language, state.actionSelector, this.document) : null;\n highlight = (entries == null ? void 0 : entries.length) ? entries : "clear";\n this._lastHighlightedSelector = (entries == null ? void 0 : entries.length) ? state.actionSelector : void 0;\n }\n const ariaTemplateJSON = JSON.stringify(state.ariaTemplate);\n if (this._lastHighlightedAriaTemplateJSON !== ariaTemplateJSON) {\n const elements = state.ariaTemplate ? this.injectedScript.getAllElementsMatchingExpectAriaTemplate(this.document, state.ariaTemplate) : [];\n if (elements.length) {\n const color = elements.length > 1 ? HighlightColors.multiple : HighlightColors.single;\n highlight = elements.map((element) => ({ element, color }));\n this._lastHighlightedAriaTemplateJSON = ariaTemplateJSON;\n } else {\n if (!this._lastHighlightedSelector)\n highlight = "clear";\n this._lastHighlightedAriaTemplateJSON = "undefined";\n }\n }\n if (highlight === "clear")\n this.highlight.clearHighlight();\n else if (highlight !== "noop")\n this.highlight.updateHighlight(highlight);\n }\n clearHighlight() {\n this.updateHighlight(null, false);\n }\n _onClick(event) {\n var _a, _b, _c;\n if (!event.isTrusted)\n return;\n if ((_a = this.overlay) == null ? void 0 : _a.onClick(event))\n return;\n if (this._ignoreOverlayEvent(event))\n return;\n (_c = (_b = this._currentTool).onClick) == null ? void 0 : _c.call(_b, event);\n }\n _onDblClick(event) {\n var _a, _b, _c;\n if (!event.isTrusted)\n return;\n if ((_a = this.overlay) == null ? void 0 : _a.onDblClick(event))\n return;\n if (this._ignoreOverlayEvent(event))\n return;\n (_c = (_b = this._currentTool).onDblClick) == null ? void 0 : _c.call(_b, event);\n }\n _onContextMenu(event) {\n var _a, _b;\n if (!event.isTrusted)\n return;\n (_b = (_a = this._currentTool).onContextMenu) == null ? void 0 : _b.call(_a, event);\n }\n _onDragStart(event) {\n var _a, _b;\n if (!event.isTrusted)\n return;\n if (this._ignoreOverlayEvent(event))\n return;\n (_b = (_a = this._currentTool).onDragStart) == null ? void 0 : _b.call(_a, event);\n }\n _onPointerDown(event) {\n var _a, _b;\n if (!event.isTrusted)\n return;\n if (this._ignoreOverlayEvent(event))\n return;\n (_b = (_a = this._currentTool).onPointerDown) == null ? void 0 : _b.call(_a, event);\n }\n _onPointerUp(event) {\n var _a, _b;\n if (!event.isTrusted)\n return;\n if (this._ignoreOverlayEvent(event))\n return;\n (_b = (_a = this._currentTool).onPointerUp) == null ? void 0 : _b.call(_a, event);\n }\n _onMouseDown(event) {\n var _a, _b;\n if (!event.isTrusted)\n return;\n if (this._ignoreOverlayEvent(event))\n return;\n (_b = (_a = this._currentTool).onMouseDown) == null ? void 0 : _b.call(_a, event);\n }\n _onMouseUp(event) {\n var _a, _b, _c;\n if (!event.isTrusted)\n return;\n if ((_a = this.overlay) == null ? void 0 : _a.onMouseUp(event))\n return;\n if (this._ignoreOverlayEvent(event))\n return;\n (_c = (_b = this._currentTool).onMouseUp) == null ? void 0 : _c.call(_b, event);\n }\n _onMouseMove(event) {\n var _a, _b, _c;\n if (!event.isTrusted)\n return;\n if ((_a = this.overlay) == null ? void 0 : _a.onMouseMove(event))\n return;\n if (this._ignoreOverlayEvent(event))\n return;\n (_c = (_b = this._currentTool).onMouseMove) == null ? void 0 : _c.call(_b, event);\n }\n _onMouseEnter(event) {\n var _a, _b;\n if (!event.isTrusted)\n return;\n if (this._ignoreOverlayEvent(event))\n return;\n (_b = (_a = this._currentTool).onMouseEnter) == null ? void 0 : _b.call(_a, event);\n }\n _onMouseLeave(event) {\n var _a, _b;\n if (!event.isTrusted)\n return;\n if (this._ignoreOverlayEvent(event))\n return;\n (_b = (_a = this._currentTool).onMouseLeave) == null ? void 0 : _b.call(_a, event);\n }\n _onFocus(event) {\n var _a, _b;\n if (!event.isTrusted)\n return;\n if (this._ignoreOverlayEvent(event))\n return;\n (_b = (_a = this._currentTool).onFocus) == null ? void 0 : _b.call(_a, event);\n }\n _onScroll(event) {\n var _a, _b;\n if (!event.isTrusted)\n return;\n this._lastHighlightedSelector = void 0;\n this._lastHighlightedAriaTemplateJSON = "undefined";\n this.highlight.hideActionPoint();\n (_b = (_a = this._currentTool).onScroll) == null ? void 0 : _b.call(_a, event);\n }\n _onInput(event) {\n var _a, _b;\n if (this._ignoreOverlayEvent(event))\n return;\n (_b = (_a = this._currentTool).onInput) == null ? void 0 : _b.call(_a, event);\n }\n _onKeyDown(event) {\n var _a, _b;\n if (!event.isTrusted)\n return;\n if (this._ignoreOverlayEvent(event))\n return;\n (_b = (_a = this._currentTool).onKeyDown) == null ? void 0 : _b.call(_a, event);\n }\n _onKeyUp(event) {\n var _a, _b;\n if (!event.isTrusted)\n return;\n if (this._ignoreOverlayEvent(event))\n return;\n (_b = (_a = this._currentTool).onKeyUp) == null ? void 0 : _b.call(_a, event);\n }\n updateHighlight(model, userGesture) {\n this._lastHighlightedSelector = void 0;\n this._lastHighlightedAriaTemplateJSON = "undefined";\n this._updateHighlight(model, userGesture);\n }\n _updateHighlight(model, userGesture) {\n var _a, _b;\n let tooltipText = model == null ? void 0 : model.tooltipText;\n if (tooltipText === void 0 && (model == null ? void 0 : model.selector))\n tooltipText = this.injectedScript.utils.asLocator(this.state.language, model.selector);\n if (model)\n this.highlight.updateHighlight(model.elements.map((element) => ({ element, color: model.color, tooltipText })));\n else\n this.highlight.clearHighlight();\n if (userGesture)\n (_b = (_a = this._delegate).highlightUpdated) == null ? void 0 : _b.call(_a);\n }\n _ignoreOverlayEvent(event) {\n return event.composedPath().some((e) => {\n const nodeName = e.nodeName || "";\n return nodeName.toLowerCase() === "x-pw-glass";\n });\n }\n deepEventTarget(event) {\n var _a;\n for (const element of event.composedPath()) {\n if (!((_a = this.overlay) == null ? void 0 : _a.contains(element)))\n return element;\n }\n return event.composedPath()[0];\n }\n setMode(mode) {\n var _a, _b;\n void ((_b = (_a = this._delegate).setMode) == null ? void 0 : _b.call(_a, mode));\n }\n _captureAutoExpectSnapshot() {\n const documentElement = this.injectedScript.document.documentElement;\n return documentElement ? this.injectedScript.utils.generateAriaTree(documentElement, { mode: "autoexpect" }) : void 0;\n }\n async performAction(action) {\n var _a, _b, _c;\n const previousSnapshot = this._lastActionAutoexpectSnapshot;\n this._lastActionAutoexpectSnapshot = this._captureAutoExpectSnapshot();\n if (!isAssertAction(action) && this._lastActionAutoexpectSnapshot) {\n const element = this.injectedScript.utils.findNewElement(previousSnapshot == null ? void 0 : previousSnapshot.root, (_a = this._lastActionAutoexpectSnapshot) == null ? void 0 : _a.root);\n action.preconditionSelector = element ? this.injectedScript.generateSelector(element, { testIdAttributeName: this.state.testIdAttributeName }).selector : void 0;\n if (action.preconditionSelector === action.selector)\n action.preconditionSelector = void 0;\n }\n await ((_c = (_b = this._delegate).performAction) == null ? void 0 : _c.call(_b, action).catch(() => {\n }));\n }\n async recordAction(action) {\n var _a, _b;\n this._lastActionAutoexpectSnapshot = this._captureAutoExpectSnapshot();\n await ((_b = (_a = this._delegate).recordAction) == null ? void 0 : _b.call(_a, action));\n }\n setOverlayState(state) {\n var _a, _b;\n void ((_b = (_a = this._delegate).setOverlayState) == null ? void 0 : _b.call(_a, state));\n }\n elementPicked(selector, model) {\n var _a, _b;\n const ariaSnapshot = this.injectedScript.ariaSnapshot(model.elements[0], { mode: "default" });\n void ((_b = (_a = this._delegate).elementPicked) == null ? void 0 : _b.call(_a, { selector, ariaSnapshot }));\n }\n};\nvar Dialog = class {\n constructor(recorder) {\n this._dialogElement = null;\n this._recorder = recorder;\n }\n isShowing() {\n return !!this._dialogElement;\n }\n show(options) {\n const acceptButton = this._recorder.document.createElement("x-pw-tool-item");\n acceptButton.title = "Accept";\n acceptButton.classList.add("accept");\n acceptButton.appendChild(this._recorder.document.createElement("x-div"));\n acceptButton.addEventListener("click", () => {\n var _a;\n return (_a = options.onCommit) == null ? void 0 : _a.call(options);\n });\n const cancelButton = this._recorder.document.createElement("x-pw-tool-item");\n cancelButton.title = "Close";\n cancelButton.classList.add("cancel");\n cancelButton.appendChild(this._recorder.document.createElement("x-div"));\n cancelButton.addEventListener("click", () => {\n var _a;\n this.close();\n (_a = options.onCancel) == null ? void 0 : _a.call(options);\n });\n this._dialogElement = this._recorder.document.createElement("x-pw-dialog");\n if (options.autosize)\n this._dialogElement.classList.add("autosize");\n this._keyboardListener = (event) => {\n var _a;\n if (event.key === "Escape") {\n this.close();\n (_a = options.onCancel) == null ? void 0 : _a.call(options);\n return;\n }\n if (options.onCommit && event.key === "Enter" && (event.ctrlKey || event.metaKey)) {\n if (this._dialogElement)\n options.onCommit();\n return;\n }\n };\n this._onGlassPaneClickHandler = (event) => {\n var _a;\n this.close();\n (_a = options.onCancel) == null ? void 0 : _a.call(options);\n };\n this._dialogElement.addEventListener("click", (event) => event.stopPropagation());\n const toolbarElement = this._recorder.document.createElement("x-pw-tools-list");\n const labelElement = this._recorder.document.createElement("label");\n labelElement.textContent = options.label;\n toolbarElement.appendChild(labelElement);\n toolbarElement.appendChild(this._recorder.document.createElement("x-spacer"));\n if (options.onCommit)\n toolbarElement.appendChild(acceptButton);\n toolbarElement.appendChild(cancelButton);\n this._dialogElement.appendChild(toolbarElement);\n const bodyElement = this._recorder.document.createElement("x-pw-dialog-body");\n bodyElement.appendChild(options.body);\n this._dialogElement.appendChild(bodyElement);\n this._recorder.highlight.appendChild(this._dialogElement);\n this._recorder.highlight.onGlassPaneClick(this._onGlassPaneClickHandler);\n this._recorder.document.addEventListener("keydown", this._keyboardListener, true);\n return this._dialogElement;\n }\n moveTo(top, left) {\n if (!this._dialogElement)\n return;\n this._dialogElement.style.top = top + "px";\n this._dialogElement.style.left = left + "px";\n }\n close() {\n if (!this._dialogElement)\n return;\n this._dialogElement.remove();\n this._recorder.highlight.offGlassPaneClick(this._onGlassPaneClickHandler);\n this._recorder.document.removeEventListener("keydown", this._keyboardListener);\n this._dialogElement = null;\n }\n};\nfunction deepActiveElement(document) {\n let activeElement = document.activeElement;\n while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)\n activeElement = activeElement.shadowRoot.activeElement;\n return activeElement;\n}\nfunction modifiersForEvent(event) {\n return (event.altKey ? 1 : 0) | (event.ctrlKey ? 2 : 0) | (event.metaKey ? 4 : 0) | (event.shiftKey ? 8 : 0);\n}\nfunction buttonForEvent(event) {\n switch (event.which) {\n case 1:\n return "left";\n case 2:\n return "middle";\n case 3:\n return "right";\n }\n return "left";\n}\nfunction positionForEvent(event) {\n const targetElement = event.target;\n if (targetElement.nodeName !== "CANVAS")\n return;\n return {\n x: event.offsetX,\n y: event.offsetY\n };\n}\nfunction consumeEvent(e) {\n e.preventDefault();\n e.stopPropagation();\n e.stopImmediatePropagation();\n}\nfunction asCheckbox(node) {\n if (!node || node.nodeName !== "INPUT")\n return null;\n const inputElement = node;\n return ["checkbox", "radio"].includes(inputElement.type) ? inputElement : null;\n}\nfunction isRangeInput(node) {\n if (!node || node.nodeName !== "INPUT")\n return false;\n const inputElement = node;\n return inputElement.type.toLowerCase() === "range";\n}\nfunction addEventListener(target, eventName, listener, useCapture) {\n target.addEventListener(eventName, listener, useCapture);\n const remove = () => {\n target.removeEventListener(eventName, listener, useCapture);\n };\n return remove;\n}\nfunction removeEventListeners(listeners) {\n for (const listener of listeners)\n listener();\n listeners.splice(0, listeners.length);\n}\nfunction entriesForSelectorHighlight(injectedScript, language, selector, ownerDocument) {\n try {\n const parsedSelector = injectedScript.parseSelector(selector);\n const elements = injectedScript.querySelectorAll(parsedSelector, ownerDocument);\n const color = elements.length > 1 ? HighlightColors.multiple : HighlightColors.single;\n const locator = injectedScript.utils.asLocator(language, selector);\n return elements.map((element, index) => {\n const suffix = elements.length > 1 ? ` [${index + 1} of ${elements.length}]` : "";\n return { element, color, tooltipText: locator + suffix };\n });\n } catch (e) {\n return [];\n }\n}\nfunction createSvgElement(doc, { tagName, attrs, children }) {\n const elem = doc.createElementNS("http://www.w3.org/2000/svg", tagName);\n if (attrs) {\n for (const [k, v] of Object.entries(attrs))\n elem.setAttribute(k, v);\n }\n if (children) {\n for (const c of children)\n elem.appendChild(createSvgElement(doc, c));\n }\n return elem;\n}\nfunction isAssertAction(action) {\n return action.name.startsWith("assert");\n}\n\n// packages/injected/src/recorder/pollingRecorder.ts\nvar PollingRecorder = class {\n constructor(injectedScript, options) {\n this._recorder = new Recorder(injectedScript, options);\n this._embedder = injectedScript.window;\n injectedScript.onGlobalListenersRemoved.add(() => this._recorder.installListeners());\n const refreshOverlay = () => {\n this._lastStateJSON = void 0;\n this._pollRecorderMode().catch((e) => console.log(e));\n };\n this._embedder.__pw_refreshOverlay = refreshOverlay;\n refreshOverlay();\n }\n async _pollRecorderMode() {\n const pollPeriod = 1e3;\n if (this._pollRecorderModeTimer)\n this._recorder.injectedScript.utils.builtins.clearTimeout(this._pollRecorderModeTimer);\n const state = await this._embedder.__pw_recorderState().catch(() => null);\n if (!state) {\n this._pollRecorderModeTimer = this._recorder.injectedScript.utils.builtins.setTimeout(() => this._pollRecorderMode(), pollPeriod);\n return;\n }\n const stringifiedState = JSON.stringify(state);\n if (this._lastStateJSON !== stringifiedState) {\n this._lastStateJSON = stringifiedState;\n const win = this._recorder.document.defaultView;\n if (win.top !== win) {\n state.actionPoint = void 0;\n }\n this._recorder.setUIState(state, this);\n }\n this._pollRecorderModeTimer = this._recorder.injectedScript.utils.builtins.setTimeout(() => this._pollRecorderMode(), pollPeriod);\n }\n async performAction(action) {\n await this._embedder.__pw_recorderPerformAction(action);\n }\n async recordAction(action) {\n await this._embedder.__pw_recorderRecordAction(action);\n }\n async elementPicked(elementInfo) {\n await this._embedder.__pw_recorderElementPicked(elementInfo);\n }\n async setMode(mode) {\n await this._embedder.__pw_recorderSetMode(mode);\n }\n async setOverlayState(state) {\n await this._embedder.__pw_recorderSetOverlayState(state);\n }\n};\nvar pollingRecorder_default = PollingRecorder;\n'; + } +}); + +// packages/playwright-core/src/server/recorder/recorderRunner.ts +async function performAction(progress2, pageAliases, actionInContext) { + const mainFrame = mainFrameForAction(pageAliases, actionInContext); + return await performActionImpl(progress2, mainFrame, actionInContext); +} +async function performActionImpl(progress2, mainFrame, actionInContext) { + const { action } = actionInContext; + if (action.name === "navigate") { + await mainFrame.goto(progress2, action.url); + return; + } + if (action.name === "openPage") + throw Error("Not reached"); + if (action.name === "closePage") { + await mainFrame._page.close(progress2); + return; + } + const selector = buildFullSelector(actionInContext.frame.framePath, action.selector); + if (action.name === "click") { + const options2 = toClickOptions(action); + await mainFrame.click(progress2, selector, { ...options2, strict: true }); + return; + } + if (action.name === "hover") { + await mainFrame.hover(progress2, selector, { position: action.position, strict: true }); + return; + } + if (action.name === "press") { + const modifiers = toKeyboardModifiers(action.modifiers); + const shortcut = [...modifiers, action.key].join("+"); + await mainFrame.press(progress2, selector, shortcut, { strict: true }); + return; + } + if (action.name === "fill") { + await mainFrame.fill(progress2, selector, action.text, { strict: true }); + return; + } + if (action.name === "setInputFiles") { + await mainFrame.setInputFiles(progress2, selector, { selector, payloads: [], strict: true }); + return; + } + if (action.name === "check") { + await mainFrame.check(progress2, selector, { strict: true }); + return; + } + if (action.name === "uncheck") { + await mainFrame.uncheck(progress2, selector, { strict: true }); + return; + } + if (action.name === "select") { + const values = action.options.map((value2) => ({ value: value2 })); + await mainFrame.selectOption(progress2, selector, [], values, { strict: true }); + return; + } + if (action.name === "assertChecked") { + await mainFrame.expect(progress2, selector, { + selector, + expression: "to.be.checked", + expectedValue: { checked: action.checked }, + isNot: !action.checked + }); + return; + } + if (action.name === "assertText") { + await mainFrame.expect(progress2, selector, { + selector, + expression: "to.have.text", + expectedText: serializeExpectedTextValues([action.text], { matchSubstring: true, normalizeWhiteSpace: true }), + isNot: false + }); + return; + } + if (action.name === "assertValue") { + await mainFrame.expect(progress2, selector, { + selector, + expression: "to.have.value", + expectedValue: action.value, + isNot: false + }); + return; + } + if (action.name === "assertVisible") { + await mainFrame.expect(progress2, selector, { + selector, + expression: "to.be.visible", + isNot: false + }); + return; + } + throw new Error("Internal error: unexpected action " + action.name); +} +function toClickOptions(action) { + const modifiers = toKeyboardModifiers(action.modifiers); + const options2 = {}; + if (action.button !== "left") + options2.button = action.button; + if (modifiers.length) + options2.modifiers = modifiers; + if (action.clickCount > 1) + options2.clickCount = action.clickCount; + if (action.position) + options2.position = action.position; + return options2; +} +var init_recorderRunner = __esm({ + "packages/playwright-core/src/server/recorder/recorderRunner.ts"() { + "use strict"; + init_expectUtils(); + init_language(); + init_recorderUtils(); + } +}); + +// packages/playwright-core/src/server/recorder.ts +function isScreenshotCommand(metadata) { + return metadata.method.toLowerCase().includes("screenshot"); +} +function languageForFile(file) { + if (file.endsWith(".py")) + return "python"; + if (file.endsWith(".java")) + return "java"; + if (file.endsWith(".cs")) + return "csharp"; + return "javascript"; +} +var import_events6, import_fs22, recorderSymbol, RecorderEvent, Recorder; +var init_recorder = __esm({ + "packages/playwright-core/src/server/recorder.ts"() { + "use strict"; + import_events6 = __toESM(require("events")); + import_fs22 = __toESM(require("fs")); + init_locatorParser(); + init_selectorParser(); + init_manualPromise(); + init_debug(); + init_eventsHelper(); + init_time(); + init_browserContext(); + init_debugger(); + init_recorderUtils(); + init_progress(); + init_recorderSignalProcessor(); + init_pollingRecorderSource(); + init_frames(); + init_page(); + init_recorderRunner(); + recorderSymbol = Symbol("recorderSymbol"); + RecorderEvent = { + PausedStateChanged: "pausedStateChanged", + ModeChanged: "modeChanged", + ElementPicked: "elementPicked", + CallLogsUpdated: "callLogsUpdated", + UserSourcesChanged: "userSourcesChanged", + ActionAdded: "actionAdded", + SignalAdded: "signalAdded", + PageNavigated: "pageNavigated", + ContextClosed: "contextClosed" + }; + Recorder = class _Recorder extends import_events6.default { + constructor(context2, params2) { + super(); + this._highlightedElement = {}; + this._overlayState = { offsetX: 0 }; + this._currentCallsMetadata = /* @__PURE__ */ new Map(); + this._userSources = /* @__PURE__ */ new Map(); + this._omitCallTracking = false; + this._currentLanguage = "javascript"; + this._pageAliases = /* @__PURE__ */ new Map(); + this._lastPopupOrdinal = 0; + this._lastDialogOrdinal = -1; + this._lastDownloadOrdinal = -1; + this._listeners = []; + this._enabled = false; + this._callLogs = []; + this._context = context2; + this._params = params2; + this._mode = params2.mode || "none"; + this._recorderMode = params2.recorderMode ?? "default"; + this.handleSIGINT = params2.handleSIGINT; + this._signalProcessor = new RecorderSignalProcessor({ + addAction: (actionInContext) => { + if (this._enabled) + this.emit(RecorderEvent.ActionAdded, actionInContext); + }, + addSignal: (signal) => { + if (this._enabled) + this.emit(RecorderEvent.SignalAdded, signal); + } + }); + context2.on(BrowserContext.Events.BeforeClose, () => { + this.emit(RecorderEvent.ContextClosed); + }); + this._listeners.push(eventsHelper.addEventListener(process, "exit", () => { + this.emit(RecorderEvent.ContextClosed); + })); + this._setEnabled(params2.mode === "recording"); + this._omitCallTracking = !!params2.omitCallTracking; + this._debugger = context2.debugger(); + context2.instrumentation.addListener(this, context2); + if (isUnderTest()) { + this._overlayState.offsetX = 200; + } + } + static forContext(context2, params2) { + let recorderPromise = context2[recorderSymbol]; + if (!recorderPromise) { + recorderPromise = _Recorder._create(context2, params2); + context2[recorderSymbol] = recorderPromise; + } + return recorderPromise; + } + static async existingForContext(context2) { + const recorderPromise = context2[recorderSymbol]; + return await recorderPromise; + } + static async _create(context2, params2 = {}) { + const recorder = new _Recorder(context2, params2); + await recorder._install(); + return recorder; + } + async _install() { + this.emit(RecorderEvent.ModeChanged, this._mode); + this.emit(RecorderEvent.PausedStateChanged, this._debugger.isPaused()); + this._context.once(BrowserContext.Events.Close, () => { + eventsHelper.removeEventListeners(this._listeners); + this._context.instrumentation.removeListener(this); + this.emit(RecorderEvent.ContextClosed); + }); + const controller = new ProgressController(); + await controller.run(async (progress2) => { + await this._context.exposeBinding(progress2, "__pw_recorderState", async (source8) => { + let actionSelector; + let actionPoint; + const hasActiveScreenshotCommand = [...this._currentCallsMetadata.keys()].some(isScreenshotCommand); + if (!hasActiveScreenshotCommand) { + actionSelector = await this._scopeHighlightedSelectorToFrame(source8.frame); + for (const [metadata, sdkObject] of this._currentCallsMetadata) { + if (source8.page === sdkObject.attribution.page) { + actionPoint = metadata.point || actionPoint; + actionSelector = actionSelector || metadata.params.selector; + } + } + } + let mode = this._mode; + if (this._pickLocatorPage && source8.page !== this._pickLocatorPage) + mode = "none"; + const uiState = { + mode, + actionPoint, + actionSelector, + ariaTemplate: this._highlightedElement.ariaTemplate, + language: this._currentLanguage, + testIdAttributeName: this._testIdAttributeName(), + overlay: this._overlayState + }; + return uiState; + }); + await this._context.exposeBinding(progress2, "__pw_recorderElementPicked", async ({ frame }, elementInfo) => { + const selectorChain = await generateFrameSelector(progress2, frame); + this.emit(RecorderEvent.ElementPicked, { selector: buildFullSelector(selectorChain, elementInfo.selector), ariaSnapshot: elementInfo.ariaSnapshot }, true); + }); + await this._context.exposeBinding(progress2, "__pw_recorderSetMode", async ({ frame }, mode) => { + if (frame.parentFrame()) + return; + await this.setMode(mode); + }); + await this._context.exposeBinding(progress2, "__pw_recorderSetOverlayState", async ({ frame }, state) => { + if (frame.parentFrame()) + return; + this._overlayState = state; + }); + await this._context.exposeBinding(progress2, "__pw_resume", () => { + this._debugger.resume(); + }); + this._context.on(BrowserContext.Events.Page, (page) => this._onPage(page)); + for (const page of this._context.pages()) + this._onPage(page); + this._context.dialogManager.addDialogHandler((dialog) => { + this._onDialog(dialog.page()); + return false; + }); + await this._context.exposeBinding( + progress2, + "__pw_recorderPerformAction", + (source8, action) => this._performAction(progress2, source8.frame, action) + ); + await this._context.exposeBinding( + progress2, + "__pw_recorderRecordAction", + (source8, action) => this._recordAction(progress2, source8.frame, action) + ); + await progress2.race(this._context.extendInjectedScript(source5, { recorderMode: this._recorderMode, hideToolbar: !!this._params.hideToolbar })); + }); + if (this._debugger.isPaused()) + this._pausedStateChanged(); + this._debugger.on(Debugger.Events.PausedStateChanged, () => this._pausedStateChanged()); + } + _pausedStateChanged() { + const pausedDetails = this._debugger.pausedDetails(); + if (pausedDetails && !this._currentCallsMetadata.has(pausedDetails.metadata)) + this.onBeforeCall(pausedDetails.sdkObject, pausedDetails.metadata); + this.emit(RecorderEvent.PausedStateChanged, this._debugger.isPaused()); + this._updateUserSources(); + this._updateCallLog([...this._currentCallsMetadata.keys()]); + } + mode() { + return this._mode; + } + async setMode(mode) { + if (this._mode === mode) + return; + this._highlightedElement = {}; + this._mode = mode; + this.emit(RecorderEvent.ModeChanged, this._mode); + this._setEnabled(this._isRecording()); + this._debugger.setMuted(this._isRecording()); + if (this._mode !== "none" && this._mode !== "standby") { + let pageToFocus = this._pickLocatorPage; + if (!pageToFocus && this._context.pages().length === 1) + pageToFocus = this._context.pages()[0]; + pageToFocus?.bringToFront(nullProgress).catch(() => { + }); + } + await this._refreshOverlay(); + } + async pickLocator(progress2, page) { + if (this._mode !== "none") + await progress2.race(this.setMode("none")); + const selectorPromise = new ManualPromise(); + let recorderChangedState = false; + const onElementPicked = (elementInfo) => { + selectorPromise.resolve(elementInfo.selector); + }; + const onModeChanged = () => { + if (this._mode === "inspecting") + return; + recorderChangedState = true; + selectorPromise.reject(new Error("Locator picking was cancelled")); + }; + const listeners = [ + eventsHelper.addEventListener(this, RecorderEvent.ElementPicked, onElementPicked), + eventsHelper.addEventListener(this, RecorderEvent.ModeChanged, onModeChanged) + ]; + try { + const doPickLocator = async () => { + selectorPromise.catch(() => { + }); + this._pickLocatorPage = page; + await this.setMode("inspecting"); + return await selectorPromise; + }; + return await progress2.race(doPickLocator()); + } finally { + eventsHelper.removeEventListeners(listeners); + this._pickLocatorPage = void 0; + if (!recorderChangedState) + await progress2.race(this.setMode("none")); + } + } + url() { + const page = this._context.pages()[0]; + return page?.mainFrame().url(); + } + async setHighlightedSelector(selector) { + this._highlightedElement = { selector: locatorOrSelectorAsSelector(this._currentLanguage, selector, this._context.selectors().testIdAttributeName()) }; + await this._refreshOverlay(); + } + async setHighlightedAriaTemplate(ariaTemplate) { + this._highlightedElement = { ariaTemplate }; + await this._refreshOverlay(); + } + step() { + this._debugger.setPauseAt({ next: true }); + this._debugger.resume(); + } + async setLanguage(language) { + this._currentLanguage = language; + await this._refreshOverlay(); + } + resume() { + this._debugger.resume(); + } + pause() { + this._debugger.setPauseAt({ next: true }); + } + paused() { + return this._debugger.isPaused(); + } + close() { + this._debugger.resume(); + } + async hideHighlightedSelector() { + this._highlightedElement = {}; + await this._refreshOverlay(); + } + pausedSourceId() { + const pausedDetails = this._debugger.pausedDetails(); + if (pausedDetails?.metadata.location) { + const source8 = this._userSources.get(pausedDetails.metadata.location.file); + if (source8) + return source8.id; + } + } + userSources() { + return [...this._userSources.values()]; + } + callLog() { + return this._callLogs; + } + async _scopeHighlightedSelectorToFrame(frame) { + if (!this._highlightedElement.selector) + return; + try { + const mainFrame = frame._page.mainFrame(); + const resolved = await mainFrame.selectors.resolveFrameForSelector(this._highlightedElement.selector); + if (!resolved) + return ""; + if (resolved?.frame === mainFrame) + return stringifySelector(resolved.info.parsed); + if (resolved?.frame === frame) + return stringifySelector(resolved.info.parsed); + return ""; + } catch { + return ""; + } + } + async _refreshOverlay() { + await Promise.all(this._context.pages().map( + (page) => page.safeNonStallingEvaluateInAllFrames("window.__pw_refreshOverlay()", "main") + )); + } + async onBeforeCall(sdkObject, metadata) { + if (this._omitCallTracking || this._isRecording()) + return; + this._currentCallsMetadata.set(metadata, sdkObject); + this._updateUserSources(); + this._updateCallLog([metadata]); + if (isScreenshotCommand(metadata)) + this.hideHighlightedSelector(); + else if (metadata.params && metadata.params.selector) + this._highlightedElement = { selector: metadata.params.selector }; + } + async onAfterCall(sdkObject, metadata) { + if (this._omitCallTracking || this._isRecording()) + return; + if (!metadata.error) + this._currentCallsMetadata.delete(metadata); + this._updateUserSources(); + this._updateCallLog([metadata]); + } + _updateUserSources() { + for (const source8 of this._userSources.values()) { + source8.highlight = []; + source8.revealLine = void 0; + } + for (const metadata of this._currentCallsMetadata.keys()) { + if (!metadata.location) + continue; + const { file, line } = metadata.location; + let source8 = this._userSources.get(file); + if (!source8) { + source8 = { isRecorded: false, label: file, id: file, text: this._readSource(file), highlight: [], language: languageForFile(file) }; + this._userSources.set(file, source8); + } + if (line) { + const paused = this._debugger.isPaused(metadata); + source8.highlight.push({ line, type: metadata.error ? "error" : paused ? "paused" : "running" }); + source8.revealLine = line; + } + } + this.emit(RecorderEvent.UserSourcesChanged, this.userSources(), this.pausedSourceId()); + } + async onCallLog(sdkObject, metadata, logName, message) { + this._updateCallLog([metadata]); + } + _updateCallLog(metadatas) { + if (this._isRecording()) + return; + const logs = []; + for (const metadata of metadatas) { + if (!metadata.method || metadata.internal) + continue; + let status = "done"; + if (this._currentCallsMetadata.has(metadata)) + status = "in-progress"; + if (this._debugger.isPaused(metadata)) + status = "paused"; + logs.push(metadataToCallLog(metadata, status)); + } + this._callLogs = logs; + this.emit(RecorderEvent.CallLogsUpdated, logs); + } + _isRecording() { + return ["recording", "assertingText", "assertingVisibility", "assertingValue", "assertingSnapshot"].includes(this._mode); + } + _readSource(fileName) { + try { + return import_fs22.default.readFileSync(fileName, "utf-8"); + } catch (e) { + return "// No source available"; + } + } + _setEnabled(enabled) { + this._enabled = enabled; + } + async _onPage(page) { + const frame = page.mainFrame(); + page.on(Page.Events.Close, () => { + this._signalProcessor.addAction({ + frame: this._describeMainFrame(page), + action: { + name: "closePage", + signals: [] + }, + startTime: monotonicTime() + }); + this._pageAliases.delete(page); + this._filePrimaryURLChanged(); + }); + frame.on(Frame.Events.InternalNavigation, (event) => { + if (event.isPublic && !event.error) { + this._onFrameNavigated(frame, page); + this._filePrimaryURLChanged(); + } + }); + page.on(Page.Events.Download, () => this._onDownload(page)); + const suffix = this._pageAliases.size ? String(++this._lastPopupOrdinal) : ""; + const pageAlias = "page" + suffix; + this._pageAliases.set(page, pageAlias); + if (page.opener()) { + this._onPopup(page.opener(), page); + } else { + this._signalProcessor.addAction({ + frame: this._describeMainFrame(page), + action: { + name: "openPage", + url: page.mainFrame().url(), + signals: [] + }, + startTime: monotonicTime() + }); + } + this._filePrimaryURLChanged(); + } + _filePrimaryURLChanged() { + const page = this._context.pages()[0]; + this.emit(RecorderEvent.PageNavigated, page?.mainFrame().url()); + } + clear() { + if (this._params.mode === "recording") { + for (const page of this._context.pages()) + this._onFrameNavigated(page.mainFrame(), page); + } + } + _describeMainFrame(page) { + return { + pageGuid: page.guid, + pageAlias: this._pageAliases.get(page), + framePath: [] + }; + } + async _describeFrame(progress2, frame) { + return { + pageGuid: frame._page.guid, + pageAlias: this._pageAliases.get(frame._page), + framePath: await generateFrameSelector(progress2, frame) + }; + } + _testIdAttributeName() { + return this._params.testIdAttributeName || this._context.selectors().testIdAttributeName() || "data-testid"; + } + async _createActionInContext(progress2, frame, action) { + const frameDescription = await this._describeFrame(progress2, frame); + const actionInContext = { + frame: frameDescription, + action, + description: void 0, + startTime: monotonicTime() + }; + return actionInContext; + } + async _performAction(progress2, frame, action) { + const actionInContext = await this._createActionInContext(progress2, frame, action); + this._signalProcessor.addAction(actionInContext); + if (actionInContext.action.name !== "openPage" && actionInContext.action.name !== "closePage") + await performAction(progress2, this._pageAliases, actionInContext); + actionInContext.endTime = monotonicTime(); + } + async _recordAction(progress2, frame, action) { + const actionInContext = await this._createActionInContext(progress2, frame, action); + this._signalProcessor.addAction(actionInContext); + } + _onFrameNavigated(frame, page) { + const pageAlias = this._pageAliases.get(page); + this._signalProcessor.signal(pageAlias, frame, { name: "navigation", url: frame.url() }); + } + _onPopup(page, popup) { + const pageAlias = this._pageAliases.get(page); + const popupAlias = this._pageAliases.get(popup); + this._signalProcessor.signal(pageAlias, page.mainFrame(), { name: "popup", popupAlias }); + } + _onDownload(page) { + const pageAlias = this._pageAliases.get(page); + ++this._lastDownloadOrdinal; + this._signalProcessor.signal(pageAlias, page.mainFrame(), { name: "download", downloadAlias: this._lastDownloadOrdinal ? String(this._lastDownloadOrdinal) : "" }); + } + _onDialog(page) { + const pageAlias = this._pageAliases.get(page); + ++this._lastDialogOrdinal; + this._signalProcessor.signal(pageAlias, page.mainFrame(), { name: "dialog", dialogAlias: this._lastDialogOrdinal ? String(this._lastDialogOrdinal) : "" }); + } + }; + } +}); + +// packages/utils/pipeTransport.ts +var PipeTransport; +var init_pipeTransport = __esm({ + "packages/utils/pipeTransport.ts"() { + "use strict"; + init_task(); + PipeTransport = class { + 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", (buffer) => this._dispatch(buffer)); + 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 data = Buffer.from(message, "utf-8"); + const dataLength = Buffer.alloc(4); + if (this._endian === "be") + dataLength.writeUInt32BE(data.length, 0); + else + dataLength.writeUInt32LE(data.length, 0); + this._pipeWrite.write(dataLength); + this._pipeWrite.write(data); + } + close() { + this._closeableStream.close(); + } + _dispatch(buffer) { + this._data = Buffer.concat([this._data, buffer]); + 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")); + }); + } + } + }; + } +}); + +// packages/playwright-core/src/server/chromium/chromiumSwitches.ts +var disabledFeatures, chromiumSwitches; +var init_chromiumSwitches = __esm({ + "packages/playwright-core/src/server/chromium/chromiumSwitches.ts"() { + "use strict"; + disabledFeatures = [ + // See https://github.com/microsoft/playwright/issues/14047 + "AvoidUnnecessaryBeforeUnloadCheckSync", + // See https://github.com/microsoft/playwright/issues/38568 + "BoundaryEventDispatchTracksNodeRemoval", + "DestroyProfileOnBrowserClose", + // See https://github.com/microsoft/playwright/pull/13854 + "DialMediaRouteProvider", + "GlobalMediaControls", + // See https://github.com/microsoft/playwright/pull/27605 + "HttpsUpgrades", + // 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", + // See https://issues.chromium.org/u/1/issues/435410220 + "AutoDeElevate", + // See https://github.com/microsoft/playwright/issues/37714 + "RenderDocument", + // Prevents downloading optimization hints on startup. + "OptimizationHints", + // Disables forced sign-in in Edge. + "msForceBrowserSignIn", + // Disables updating the preferred version in LaunchServices preferences on mac. + "msEdgeUpdateLaunchServicesPreferredVersion" + ].filter(Boolean); + chromiumSwitches = (options2) => [ + "--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-edgeupdater", + // Disables Edge-specific updater on mac. + "--disable-extensions", + "--disable-features=" + disabledFeatures.join(","), + process.env.PLAYWRIGHT_LEGACY_SCREENSHOT ? "" : "--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", + // Edge can potentially restart on Windows (msRelaunchNoCompatLayer) which looses its file descriptors (stdout/stderr) and CDP (3/4). Disable until fixed upstream. + "--edge-skip-compat-layer-relaunch", + // This disables Chrome for Testing infobar that is visible in the persistent context. + // The switch is ignored everywhere else, including Chromium/Chrome/Edge. + "--disable-infobars", + // Less annoying popups. + "--disable-search-engine-choice-screen", + // Prevents the "three dots" menu crash in IdentityManager::HasPrimaryAccount for ephemeral contexts. + options2?.android ? "" : "--disable-sync" + ].filter(Boolean); + } +}); + +// packages/playwright-core/src/server/chromium/crConnection.ts +var ConnectionEvents, kBrowserCloseMessageId, CRConnection, CRSession, CDPSession; +var init_crConnection = __esm({ + "packages/playwright-core/src/server/chromium/crConnection.ts"() { + "use strict"; + init_debugLogger(); + init_assert(); + init_eventsHelper(); + init_helper(); + init_protocolError(); + init_instrumentation(); + ConnectionEvents = { + Disconnected: Symbol("ConnectionEvents.Disconnected") + }; + kBrowserCloseMessageId = -9999; + CRConnection = class extends SdkObject { + constructor(parent, transport, protocolLogger, browserLogsCollector) { + super(parent, "cr-connection"); + 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, params2) { + const id = ++this._lastId; + const message = { id, method, params: params2 }; + 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) + return; + const session2 = this._sessions.get(message.sessionId || ""); + if (session2) + session2._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.Disconnected)); + } + close() { + if (!this._closed) + this._transport.close(); + } + async createBrowserSession() { + const { sessionId } = await this.rootSession.send("Target.attachToBrowserTarget"); + return new CDPSession(this.rootSession, sessionId); + } + }; + CRSession = class _CRSession extends SdkObject { + constructor(connection, parentSession, sessionId, eventListener) { + super(connection, "cr-session"); + 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; + } + _markAsCrashed() { + this._crashed = true; + } + createChildSession(sessionId, eventListener) { + const session2 = new _CRSession(this._connection, this, sessionId, eventListener); + this._connection._sessions.set(sessionId, session2); + return session2; + } + async send(method, params2) { + 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, params2); + return new Promise((resolve, reject) => { + this._callbacks.set(id, { resolve, reject, error: new ProtocolError("error", method) }); + }); + } + _sendMayFail(method, params2) { + return this.send(method, params2).catch((error) => debugLogger.log("error", error)); + } + _onMessage(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?.code === -32001) { + } else { + assert(!object.id, object?.error?.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(); + } + }; + CDPSession = class _CDPSession extends SdkObject { + constructor(parentSession, sessionId) { + super(parentSession, "cdp-session"); + this._listeners = []; + this._session = parentSession.createChildSession(sessionId, (method, params2) => this.emit(_CDPSession.Events.Event, { method, params: params2 })); + this._listeners = [eventsHelper.addEventListener(parentSession, "Target.detachedFromTarget", (event) => { + if (event.sessionId === sessionId) + this._onClose(); + })]; + } + static { + this.Events = { + Event: "event", + Closed: "close" + }; + } + async send(progress2, method, params2) { + return await progress2.race(this._send(method, params2)); + } + async detach(progress2) { + return await progress2.race(this._session.detach()); + } + async _send(method, params2) { + return await this._session.send(method, params2); + } + async attachToTarget(targetId) { + const { sessionId } = await this._send("Target.attachToTarget", { targetId, flatten: true }); + return new _CDPSession(this._session, sessionId); + } + _onClose() { + eventsHelper.removeEventListeners(this._listeners); + this._session.dispose(); + this.emit(_CDPSession.Events.Closed); + } + }; + } +}); + +// packages/playwright-core/src/server/chromium/crCoverage.ts +function convertToDisjointRanges(nestedRanges) { + const points = []; + for (const range of nestedRanges) { + points.push({ offset: range.startOffset, type: 0, range }); + points.push({ offset: range.endOffset, type: 1, range }); + } + 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((range) => range.end - range.start > 1); +} +var CRCoverage, JSCoverage, CSSCoverage; +var init_crCoverage = __esm({ + "packages/playwright-core/src/server/chromium/crCoverage.ts"() { + "use strict"; + init_eventsHelper(); + init_assert(); + init_progress(); + CRCoverage = class { + constructor(client) { + this._jsCoverage = new JSCoverage(client); + this._cssCoverage = new CSSCoverage(client); + } + async startJSCoverage(progress2, options2) { + await raceUncancellableOperationWithCleanup(progress2, () => this._jsCoverage.start(options2), () => this._jsCoverage.stop()); + } + async stopJSCoverage() { + return await this._jsCoverage.stop(); + } + async startCSSCoverage(progress2, options2) { + await raceUncancellableOperationWithCleanup(progress2, () => this._cssCoverage.start(options2), () => this._cssCoverage.stop()); + } + async stopCSSCoverage() { + return await this._cssCoverage.stop(); + } + }; + JSCoverage = class { + 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 source8 = this._scriptSources.get(entry.scriptId); + if (source8) + coverage.entries.push({ ...entry, source: source8 }); + else + coverage.entries.push(entry); + } + return coverage; + } + }; + CSSCoverage = class { + 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 text2 = this._stylesheetSources.get(styleSheetId); + const ranges = convertToDisjointRanges(styleSheetIdToCoverage.get(styleSheetId) || []); + coverage.entries.push({ url: url2, ranges, text: text2 }); + } + return coverage; + } + }; + } +}); + +// packages/playwright-core/src/server/chromium/crProtocolHelper.ts +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((error) => { + }); +} +async function saveProtocolStream(client, handle, path59) { + let eof = false; + await mkdirIfNeeded(path59); + const fd = await import_fs23.default.promises.open(path59, "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 stackTraceToLocation(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) { + 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 = exceptionDetails.exception?.preview?.properties.find((o) => o.name === "name"); + err.name = nameOverride ? nameOverride.value ?? "Error" : name; + return err; +} +function toModifiersMask(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(buttons) { + let mask = 0; + if (buttons.has("left")) + mask |= 1; + if (buttons.has("right")) + mask |= 2; + if (buttons.has("middle")) + mask |= 4; + return mask; +} +var import_fs23; +var init_crProtocolHelper = __esm({ + "packages/playwright-core/src/server/chromium/crProtocolHelper.ts"() { + "use strict"; + import_fs23 = __toESM(require("fs")); + init_stackTrace(); + init_fileUtils(); + } +}); + +// packages/playwright-core/src/server/chromium/crDragDrop.ts +var DragManager; +var init_crDragDrop = __esm({ + "packages/playwright-core/src/server/chromium/crDragDrop.ts"() { + "use strict"; + init_assert(); + init_crProtocolHelper(); + DragManager = class { + 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(progress2, x, y, button, buttons, modifiers, moveCallback) { + this._lastPosition = { x, y }; + if (this._dragState) { + await progress2.race(this._crPage._mainFrameSession._client.send("Input.dispatchDragEvent", { + type: "dragOver", + x, + y, + data: this._dragState, + modifiers: toModifiersMask(modifiers) + })); + return; + } + if (button !== "left") + return moveCallback(progress2); + 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; + }; + } + try { + let expectingDrag = false; + await progress2.race(this._crPage._page.safeNonStallingEvaluateInAllFrames(`(${setupDragListeners.toString()})()`, "utility")); + client.on("Input.dragIntercepted", onDragIntercepted); + await progress2.race(client.send("Input.setInterceptDrags", { enabled: true })); + try { + await moveCallback(progress2); + expectingDrag = (await progress2.race(Promise.all(this._crPage._page.frames().map(async (frame) => { + return frame.nonStallingEvaluateInExistingContext("window.__cleanupDrag?.()", "utility").catch(() => false); + })))).some((x2) => x2); + } finally { + client.off("Input.dragIntercepted", onDragIntercepted); + await progress2.race(client.send("Input.setInterceptDrags", { enabled: false })); + } + this._dragState = expectingDrag ? (await dragInterceptedPromise).data : null; + } catch (error) { + this._crPage._page.safeNonStallingEvaluateInAllFrames("window.__cleanupDrag?.()", "utility").catch(() => { + }); + throw error; + } + if (this._dragState) { + await progress2.race(this._crPage._mainFrameSession._client.send("Input.dispatchDragEvent", { + type: "dragEnter", + x, + y, + data: this._dragState, + modifiers: toModifiersMask(modifiers) + })); + } + } + isDragging() { + return !!this._dragState; + } + async drop(progress2, x, y, modifiers) { + assert(this._dragState, "missing drag state"); + await progress2.race(this._crPage._mainFrameSession._client.send("Input.dispatchDragEvent", { + type: "drop", + x, + y, + data: this._dragState, + modifiers: toModifiersMask(modifiers) + })); + this._dragState = null; + } + }; + } +}); + +// packages/playwright-core/src/server/chromium/crExecutionContext.ts +function rewriteError(error) { + if (error.message.includes("Object reference chain is too long")) + throw new Error("Cannot serialize result: object reference chain is too long."); + if (error.message.includes("Object couldn't be returned by value")) + return { result: { type: "undefined" } }; + if (error instanceof TypeError && error.message.startsWith("Converting circular structure to JSON")) + rewriteErrorMessage(error, error.message + " Are you passing a nested JSHandle?"); + if (!isJavaScriptErrorInEvaluate(error) && !isSessionClosedError(error)) + throw new Error("Execution context was destroyed, most likely because of a navigation."); + throw error; +} +function potentiallyUnserializableValue(remoteObject) { + const value2 = remoteObject.value; + const unserializableValue = remoteObject.unserializableValue; + return unserializableValue ? parseUnserializableValue(unserializableValue) : value2; +} +function renderPreview(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: value2 } of object.preview.properties) + tokens.push(`${name}: ${value2}`); + return `{${tokens.join(", ")}}`; + } + if (object.subtype === "array" && object.preview) + return sparseArrayToString(object.preview.properties); + return object.description; +} +function createHandle(context2, remoteObject) { + if (remoteObject.subtype === "node") { + assert(context2 instanceof FrameExecutionContext); + return new ElementHandle(context2, remoteObject.objectId); + } + return new JSHandle(context2, remoteObject.subtype || remoteObject.type, renderPreview(remoteObject), remoteObject.objectId, potentiallyUnserializableValue(remoteObject)); +} +var CRExecutionContext; +var init_crExecutionContext = __esm({ + "packages/playwright-core/src/server/chromium/crExecutionContext.ts"() { + "use strict"; + init_assert(); + init_stackTrace(); + init_utilityScriptSerializers(); + init_crProtocolHelper(); + init_javascript(); + init_dom(); + init_protocolError(); + CRExecutionContext = class { + constructor(client, contextPayload) { + this._client = client; + this._contextId = contextPayload.id; + } + async rawEvaluateJSON(expression2) { + const { exceptionDetails, result: remoteObject } = await this._client.send("Runtime.evaluate", { + expression: expression2, + contextId: this._contextId, + returnByValue: true + }).catch(rewriteError); + if (exceptionDetails) + throw new JavaScriptErrorInEvaluate(getExceptionMessage(exceptionDetails)); + return remoteObject.value; + } + async rawEvaluateHandle(context2, expression2) { + const { exceptionDetails, result: remoteObject } = await this._client.send("Runtime.evaluate", { + expression: expression2, + contextId: this._contextId + }).catch(rewriteError); + if (exceptionDetails) + throw new JavaScriptErrorInEvaluate(getExceptionMessage(exceptionDetails)); + return createHandle(context2, remoteObject); + } + async evaluateWithArguments(expression2, returnByValue, utilityScript, values, handles) { + const { exceptionDetails, result: remoteObject } = await this._client.send("Runtime.callFunctionOn", { + functionDeclaration: expression2, + objectId: utilityScript._objectId, + arguments: [ + { objectId: utilityScript._objectId }, + ...values.map((value2) => ({ value: value2 })), + ...handles.map((handle) => ({ objectId: handle._objectId })) + ], + returnByValue, + awaitPromise: true, + userGesture: true + }).catch(rewriteError); + if (exceptionDetails) + throw new JavaScriptErrorInEvaluate(getExceptionMessage(exceptionDetails)); + return returnByValue ? parseEvaluationResultValue(remoteObject.value) : createHandle(utilityScript._context, remoteObject); + } + async getProperties(object) { + const response2 = await this._client.send("Runtime.getProperties", { + objectId: object._objectId, + ownProperties: true + }); + const result2 = /* @__PURE__ */ new Map(); + for (const property of response2.result) { + if (!property.enumerable || !property.value) + continue; + result2.set(property.name, createHandle(object._context, property.value)); + } + return result2; + } + async releaseHandle(handle) { + if (!handle._objectId) + return; + await releaseObject(this._client, handle._objectId); + } + shouldPrependErrorPrefix() { + return false; + } + }; + } +}); + +// packages/playwright-core/src/server/macEditingCommands.ts +var macEditingCommands; +var init_macEditingCommands = __esm({ + "packages/playwright-core/src/server/macEditingCommands.ts"() { + "use strict"; + 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:" + }; + } +}); + +// packages/playwright-core/src/server/chromium/crInput.ts +var RawKeyboardImpl, RawMouseImpl, RawTouchscreenImpl; +var init_crInput = __esm({ + "packages/playwright-core/src/server/chromium/crInput.ts"() { + "use strict"; + init_stringUtils(); + init_input(); + init_macEditingCommands(); + init_crProtocolHelper(); + RawKeyboardImpl = class { + 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 commands2 = macEditingCommands[shortcut] || []; + if (isString(commands2)) + commands2 = [commands2]; + commands2 = commands2.filter((x) => !x.startsWith("insert")); + return commands2.map((c) => c.substring(0, c.length - 1)); + } + async keydown(progress2, modifiers, keyName, description, autoRepeat) { + const { code, key, location: location2, text: text2 } = description; + if (code === "Escape" && await progress2.race(this._dragManger.cancelDrag())) + return; + const commands2 = this._commandsForCode(code, modifiers); + await progress2.race(this._client.send("Input.dispatchKeyEvent", { + type: text2 ? "keyDown" : "rawKeyDown", + modifiers: toModifiersMask(modifiers), + windowsVirtualKeyCode: description.keyCodeWithoutLocation, + code, + commands: commands2, + key, + text: text2, + unmodifiedText: text2, + autoRepeat, + location: location2, + isKeypad: location2 === keypadLocation2 + })); + } + async keyup(progress2, modifiers, keyName, description) { + const { code, key, location: location2 } = description; + await progress2.race(this._client.send("Input.dispatchKeyEvent", { + type: "keyUp", + modifiers: toModifiersMask(modifiers), + key, + windowsVirtualKeyCode: description.keyCodeWithoutLocation, + code, + location: location2 + })); + } + async sendText(progress2, text2) { + await progress2.race(this._client.send("Input.insertText", { text: text2 })); + } + }; + RawMouseImpl = class { + constructor(page, client, dragManager) { + this._page = page; + this._client = client; + this._dragManager = dragManager; + } + async move(progress2, x, y, button, buttons, modifiers, forClick) { + const actualMove = async (progress3) => { + await progress3.race(this._client.send("Input.dispatchMouseEvent", { + type: "mouseMoved", + button, + buttons: toButtonsMask(buttons), + x, + y, + modifiers: toModifiersMask(modifiers), + force: buttons.size > 0 ? 0.5 : 0 + })); + }; + if (forClick) { + await actualMove(progress2); + return; + } + await this._dragManager.interceptDragCausedByMove(progress2, x, y, button, buttons, modifiers, actualMove); + } + async down(progress2, x, y, button, buttons, modifiers, clickCount) { + if (this._dragManager.isDragging()) + return; + await progress2.race(this._client.send("Input.dispatchMouseEvent", { + type: "mousePressed", + button, + buttons: toButtonsMask(buttons), + x, + y, + modifiers: toModifiersMask(modifiers), + clickCount, + force: buttons.size > 0 ? 0.5 : 0 + })); + } + async up(progress2, x, y, button, buttons, modifiers, clickCount) { + if (this._dragManager.isDragging()) { + await this._dragManager.drop(progress2, x, y, modifiers); + return; + } + await progress2.race(this._client.send("Input.dispatchMouseEvent", { + type: "mouseReleased", + button, + buttons: toButtonsMask(buttons), + x, + y, + modifiers: toModifiersMask(modifiers), + clickCount + })); + } + async wheel(progress2, x, y, buttons, modifiers, deltaX, deltaY) { + await progress2.race(this._client.send("Input.dispatchMouseEvent", { + type: "mouseWheel", + x, + y, + modifiers: toModifiersMask(modifiers), + deltaX, + deltaY + })); + } + }; + RawTouchscreenImpl = class { + constructor(client) { + this._client = client; + } + async tap(progress2, x, y, modifiers) { + await progress2.race(Promise.all([ + this._client.send("Input.dispatchTouchEvent", { + type: "touchStart", + modifiers: toModifiersMask(modifiers), + touchPoints: [{ + x, + y + }] + }), + this._client.send("Input.dispatchTouchEvent", { + type: "touchEnd", + modifiers: toModifiersMask(modifiers), + touchPoints: [] + }) + ])); + } + }; + } +}); + +// packages/playwright-core/src/server/chromium/crNetworkManager.ts +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 index = headers.findIndex(({ name }) => name.toLowerCase() === "set-cookie"); + if (index === -1) + return headers; + const header = headers[index]; + const values = header.value.split("\n"); + if (values.length === 1) + return headers; + const result2 = headers.slice(); + result2.splice(index, 1, ...values.map((value2) => ({ name: header.name, value: value2 }))); + return result2; +} +function toResourceType(type3) { + switch (type3) { + case "Document": + return "document"; + case "Stylesheet": + return "stylesheet"; + case "Image": + return "image"; + case "Media": + return "media"; + case "Font": + return "font"; + case "Script": + return "script"; + case "TextTrack": + return "texttrack"; + case "XHR": + return "xhr"; + case "Fetch": + return "fetch"; + case "EventSource": + return "eventsource"; + case "WebSocket": + return "websocket"; + case "Manifest": + return "manifest"; + case "Ping": + return "ping"; + case "CSPViolationReport": + return "cspreport"; + case "Prefetch": + case "SignedExchange": + case "Preflight": + case "FedCM": + default: + return "other"; + } +} +var CRNetworkManager, InterceptableRequest, RouteImpl, errorReasons, ResponseExtraInfoTracker; +var init_crNetworkManager = __esm({ + "packages/playwright-core/src/server/chromium/crNetworkManager.ts"() { + "use strict"; + init_eventsHelper(); + init_assert(); + init_headers(); + init_helper(); + init_network2(); + init_protocolError(); + CRNetworkManager = class { + 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(session2, workerFrame, isMain) { + const sessionInfo = { session: session2, isMain, workerFrame, eventListeners: [] }; + sessionInfo.eventListeners = [ + eventsHelper.addEventListener(session2, "Fetch.requestPaused", this._onRequestPaused.bind(this, sessionInfo)), + eventsHelper.addEventListener(session2, "Fetch.authRequired", this._onAuthRequired.bind(this, sessionInfo)), + eventsHelper.addEventListener(session2, "Network.requestWillBeSent", this._onRequestWillBeSent.bind(this, sessionInfo)), + eventsHelper.addEventListener(session2, "Network.requestWillBeSentExtraInfo", this._onRequestWillBeSentExtraInfo.bind(this)), + eventsHelper.addEventListener(session2, "Network.requestServedFromCache", this._onRequestServedFromCache.bind(this)), + eventsHelper.addEventListener(session2, "Network.responseReceived", this._onResponseReceived.bind(this, sessionInfo)), + eventsHelper.addEventListener(session2, "Network.responseReceivedExtraInfo", this._onResponseReceivedExtraInfo.bind(this)), + eventsHelper.addEventListener(session2, "Network.loadingFinished", this._onLoadingFinished.bind(this, sessionInfo)), + eventsHelper.addEventListener(session2, "Network.loadingFailed", this._onLoadingFailed.bind(this, sessionInfo)) + ]; + if (this._page) { + sessionInfo.eventListeners.push(...[ + eventsHelper.addEventListener(session2, "Network.webSocketCreated", (e) => this._page.frameManager.onWebSocketCreated(e.requestId, e.url)), + eventsHelper.addEventListener(session2, "Network.webSocketWillSendHandshakeRequest", (e) => this._page.frameManager.onWebSocketRequest(e.requestId)), + eventsHelper.addEventListener(session2, "Network.webSocketHandshakeResponseReceived", (e) => this._page.frameManager.onWebSocketResponse(e.requestId, e.response.status, e.response.statusText)), + eventsHelper.addEventListener(session2, "Network.webSocketFrameSent", (e) => e.response.payloadData && this._page.frameManager.onWebSocketFrameSent(e.requestId, e.response.opcode, e.response.payloadData)), + eventsHelper.addEventListener(session2, "Network.webSocketFrameReceived", (e) => e.response.payloadData && this._page.frameManager.webSocketFrameReceived(e.requestId, e.response.opcode, e.response.payloadData)), + eventsHelper.addEventListener(session2, "Network.webSocketClosed", (e) => this._page.frameManager.webSocketClosed(e.requestId)), + eventsHelper.addEventListener(session2, "Network.webSocketFrameError", (e) => this._page.frameManager.webSocketError(e.requestId, e.errorMessage)) + ]); + } + this._sessions.set(session2, sessionInfo); + await Promise.all([ + session2.send("Network.enable"), + this._updateProtocolRequestInterceptionForSession( + sessionInfo, + true + /* initial */ + ), + this._setOfflineForSession( + sessionInfo, + true + /* initial */ + ), + this._setExtraHTTPHeadersForSession( + sessionInfo, + true + /* initial */ + ) + ]); + } + removeSession(session2) { + const info = this._sessions.get(session2); + if (info) + eventsHelper.removeEventListeners(info.eventListeners); + this._sessions.delete(session2); + } + 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(value2) { + this._userRequestInterceptionEnabled = value2; + 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) { + 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 = existingRequest?._originalRequestRoute?._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) { + if (requestWillBeSentEvent.request.url.startsWith("data:")) + return; + let redirectedFrom = null; + if (requestWillBeSentEvent.redirectResponse) { + const request3 = this._requestIdToRequest.get(requestWillBeSentEvent.requestId); + if (request3) { + this._handleRequestRedirect(request3, requestWillBeSentEvent.redirectResponse, requestWillBeSentEvent.timestamp, requestWillBeSentEvent.redirectHasExtraInfo); + redirectedFrom = request3; + } + } + let frame = requestWillBeSentEvent.frameId ? this._page?.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 === (this._page?.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 route2 = null; + let headersOverride; + if (requestPausedEvent) { + if (redirectedFrom || !this._userRequestInterceptionEnabled && this._protocolRequestInterceptionEnabled) { + headersOverride = redirectedFrom?._originalRequestRoute?._alreadyContinuedParams?.headers; + if (headersOverride) { + const originalHeaders = Object.entries(requestPausedEvent.request.headers).map(([name, value2]) => ({ name, value: value2 })); + headersOverride = applyHeadersOverrides(originalHeaders, headersOverride); + } + requestPausedSessionInfo.session._sendMayFail("Fetch.continueRequest", { requestId: requestPausedEvent.requestId, headers: headersOverride }); + } else { + route2 = 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({ + session: requestWillBeSentSessionInfo.session, + context: (this._page || this._serviceWorker).browserContext, + frame: frame || null, + serviceWorker: this._serviceWorker || null, + documentId, + route: route2, + requestWillBeSentEvent, + requestPausedEvent, + redirectedFrom, + headersOverride: headersOverride || null + }); + this._requestIdToRequest.set(requestWillBeSentEvent.requestId, request2); + if (route2) { + request2.request.setRawRequestHeaders(headersObjectToArray(requestPausedEvent.request.headers, "\n")); + } + (this._page?.frameManager || this._serviceWorker).requestStarted(request2.request, route2 || void 0); + } + _createResponse(request2, responsePayload, hasExtraInfo) { + const getResponseBody = async () => { + const contentLengthHeader = Object.entries(responsePayload.headers).find((header) => header[0].toLowerCase() === "content-length"); + const expectedLength = contentLengthHeader ? +contentLengthHeader[1] : void 0; + const session2 = request2.session; + const response3 = await session2.send("Network.getResponseBody", { requestId: request2._requestId }); + if (response3.body || !expectedLength) + return Buffer.from(response3.body, response3.base64Encoded ? "base64" : "utf8"); + if (request2._originalRequestRoute?._fulfilled) + return Buffer.from(""); + const resource = await session2.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 session2.send("IO.read", { handle: resource.resource.stream }); + chunks.push(Buffer.from(chunk.data, chunk.base64Encoded ? "base64" : "utf-8")); + if (chunk.eof) { + await session2.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 Response2(request2.request, responsePayload.status, responsePayload.statusText, headersObjectToArray(responsePayload.headers), timing, getResponseBody, !!responsePayload.fromServiceWorker); + response2._setHttpVersion(responsePayload?.protocol ?? null); + if (responsePayload?.remoteIPAddress && typeof responsePayload?.remotePort === "number") { + response2._serverAddrFinished({ + ipAddress: responsePayload.remoteIPAddress, + port: responsePayload.remotePort + }); + } else { + response2._serverAddrFinished(); + } + response2._securityDetailsFinished({ + protocol: responsePayload?.securityDetails?.protocol, + subjectName: responsePayload?.securityDetails?.subjectName, + issuer: responsePayload?.securityDetails?.issuer, + validFrom: responsePayload?.securityDetails?.validFrom, + validTo: responsePayload?.securityDetails?.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, timestamp, hasExtraInfo) { + const response2 = this._createResponse(request2, responsePayload, hasExtraInfo); + response2.setTransferSize(null); + response2.setEncodedBodySize(null); + response2._requestFinished((timestamp - request2._timestamp) * 1e3); + this._deleteRequest(request2); + (this._page?.frameManager || this._serviceWorker).requestReceivedResponse(response2); + (this._page?.frameManager || this._serviceWorker).reportRequestFinished(request2.request, response2); + } + _onResponseReceivedExtraInfo(event) { + this._responseExtraInfoTracker.responseReceivedExtraInfo(event); + } + _onResponseReceived(sessionInfo, event) { + 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); + (this._page?.frameManager || this._serviceWorker).requestReceivedResponse(response2); + } + _onLoadingFinished(sessionInfo, event) { + 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); + (this._page?.frameManager || this._serviceWorker).reportRequestFinished(request2.request, response2); + } + _onLoadingFailed(sessionInfo, event) { + 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 || ""); + (this._page?.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; + } + }; + InterceptableRequest = class { + constructor(options2) { + const { session: session2, context: context2, frame, documentId, route: route2, requestWillBeSentEvent, requestPausedEvent, redirectedFrom, serviceWorker, headersOverride } = options2; + this.session = session2; + this._timestamp = requestWillBeSentEvent.timestamp; + this._wallTime = requestWillBeSentEvent.wallTime; + this._requestId = requestWillBeSentEvent.requestId; + this._interceptionId = requestPausedEvent && requestPausedEvent.requestId; + this._documentId = documentId; + this._originalRequestRoute = route2 ?? redirectedFrom?._originalRequestRoute; + const { + headers, + method, + url: url2, + postDataEntries = null + } = requestPausedEvent ? requestPausedEvent.request : requestWillBeSentEvent.request; + let postDataBuffer = null; + const entries = postDataEntries?.filter((entry) => entry.bytes); + if (entries && entries.length) + postDataBuffer = Buffer.concat(entries.map((entry) => Buffer.from(entry.bytes, "base64"))); + this.request = new Request(context2, frame, serviceWorker, redirectedFrom?.request || null, documentId, url2, toResourceType(requestWillBeSentEvent.type || "Other"), method, postDataBuffer, headersOverride || headersObjectToArray(headers)); + } + }; + RouteImpl = class { + constructor(session2, interceptionId) { + this._fulfilled = false; + this._session = session2; + 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[errorCode]; + assert(errorReason, "Unknown error code: " + errorCode); + await catchDisallowedErrors(async () => { + await this._session.send("Fetch.failRequest", { + requestId: this._interceptionId, + errorReason + }); + }); + } + }; + errorReasons = { + "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" + }; + ResponseExtraInfoTracker = class { + 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?.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?.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, index) { + const response2 = info.responses[index]; + const requestExtraInfo = info.requestWillBeSentExtraInfo[index]; + if (response2 && requestExtraInfo) { + response2.request().setRawRequestHeaders(headersObjectToArray(requestExtraInfo.headers, "\n")); + info.requestWillBeSentExtraInfo[index] = void 0; + } + const responseExtraInfo = info.responseReceivedExtraInfo[index]; + if (response2 && responseExtraInfo) { + response2.setResponseHeadersSize(responseExtraInfo.headersText?.length || 0); + response2.setRawResponseHeaders(headersObjectToArray(responseExtraInfo.headers, "\n")); + info.responseReceivedExtraInfo[index] = 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); + } + }; + } +}); + +// packages/playwright-core/src/server/chromium/crPdf.ts +function convertPrintParameterToInches(text2) { + if (text2 === void 0) + return void 0; + let unit = text2.substring(text2.length - 2).toLowerCase(); + let valueText = ""; + if (unitToPixels.hasOwnProperty(unit)) { + valueText = text2.substring(0, text2.length - 2); + } else { + unit = "px"; + valueText = text2; + } + const value2 = Number(valueText); + assert(!isNaN(value2), "Failed to parse parameter value: " + text2); + const pixels = value2 * unitToPixels[unit]; + return pixels / 96; +} +var PagePaperFormats, unitToPixels, CRPDF; +var init_crPdf = __esm({ + "packages/playwright-core/src/server/chromium/crPdf.ts"() { + "use strict"; + init_assert(); + init_crProtocolHelper(); + 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 } + }; + unitToPixels = { + "px": 1, + "in": 96, + "cm": 37.8, + "mm": 3.78 + }; + CRPDF = class { + 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 format2 = PagePaperFormats[options2.format.toLowerCase()]; + assert(format2, "Unknown paper format: " + options2.format); + paperWidth = format2.width; + paperHeight = format2.height; + } else { + paperWidth = convertPrintParameterToInches(options2.width) || paperWidth; + paperHeight = convertPrintParameterToInches(options2.height) || paperHeight; + } + const marginTop = convertPrintParameterToInches(margin.top) || 0; + const marginLeft = convertPrintParameterToInches(margin.left) || 0; + const marginBottom = convertPrintParameterToInches(margin.bottom) || 0; + const marginRight = convertPrintParameterToInches(margin.right) || 0; + const generateDocumentOutline = outline; + const generateTaggedPDF = tagged; + const result2 = 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, result2.stream); + } + }; + } +}); + +// packages/playwright-core/src/server/chromium/defaultFontFamilies.ts +var platformToFontFamilies; +var init_defaultFontFamilies = __esm({ + "packages/playwright-core/src/server/chromium/defaultFontFamilies.ts"() { + "use strict"; + 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" + } + } + ] + } + }; + } +}); + +// packages/playwright-core/src/server/videoRecorder.ts +function startAutomaticVideoRecording(page) { + const recordVideo = page.browserContext._options.recordVideo; + if (!recordVideo) + return; + const recorder = new VideoRecorder(page.screencast); + if (page.browserContext._options.recordVideo?.showActions) + page.screencast.showActions(page.browserContext._options.recordVideo?.showActions); + const dir = recordVideo.dir ?? page.browserContext._browser.options.artifactsDir; + const artifact = recorder.start({ size: recordVideo.size, fileName: import_path21.default.join(dir, page.guid + ".webm") }); + page.video = artifact; +} +function createWhiteImage(width, height) { + const data = Buffer.alloc(width * height * 4, 255); + return jpegjs2.encode({ data, width, height }, 80).data; +} +var import_path21, jpegjs2, fps, VideoRecorder, FfmpegVideoRecorder; +var init_videoRecorder = __esm({ + "packages/playwright-core/src/server/videoRecorder.ts"() { + "use strict"; + import_path21 = __toESM(require("path")); + init_processLauncher(); + init_assert(); + init_crypto(); + init_debugLogger(); + init_fileUtils(); + init_time(); + init_artifact(); + init_registry(); + jpegjs2 = require("./utilsBundle").jpegjs; + fps = 25; + VideoRecorder = class { + constructor(screencast) { + this._screencast = screencast; + } + start(options2) { + assert(!this._artifact); + const ffmpegPath = registry.findExecutable("ffmpeg").executablePathOrDie(this._screencast.page.browserContext._browser.sdkLanguage()); + const outputFile2 = options2.fileName ?? import_path21.default.join(this._screencast.page.browserContext._browser.options.artifactsDir, createGuid() + ".webm"); + this._client = { + onFrame: (frame) => this._videoRecorder.writeFrame(frame.buffer, frame.frameSwapWallTime / 1e3), + gracefulClose: () => this.stop(), + dispose: () => this.stop().catch((e) => debugLogger.log("error", `Failed to stop video recorder: ${String(e)}`)), + size: options2.size + }; + const { size } = this._screencast.addClient(this._client); + const videoSize = options2.size ?? size; + this._videoRecorder = new FfmpegVideoRecorder(ffmpegPath, videoSize, outputFile2); + this._artifact = new Artifact(this._screencast.page.browserContext, outputFile2); + return this._artifact; + } + async stop() { + if (!this._artifact) + return; + const artifact = this._artifact; + this._artifact = void 0; + const client = this._client; + this._client = void 0; + const videoRecorder = this._videoRecorder; + this._videoRecorder = void 0; + this._screencast.removeClient(client); + await videoRecorder._stop(); + await artifact.reportFinished(); + } + }; + FfmpegVideoRecorder = class { + constructor(ffmpegPath, size, outputFile2) { + this._process = null; + this._gracefullyClose = null; + this._lastWritePromise = Promise.resolve(); + this._firstFrameTimestamp = 0; + this._lastFrame = null; + this._lastWriteNodeTime = 0; + this._frameQueue = []; + this._isStopped = false; + if (!outputFile2.endsWith(".webm")) + throw new Error("File must have .webm extension"); + this._outputFile = outputFile2; + this._ffmpegPath = ffmpegPath; + this._size = size; + this._launchPromise = this._launch().catch((e) => e); + } + async _launch() { + await mkdirIfNeeded(this._outputFile); + const w = this._size.width; + const h = this._size.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(this._outputFile); + const { launchedProcess, gracefullyClose } = await launchProcess({ + command: this._ffmpegPath, + args, + stdio: "stdin", + log: (message) => debugLogger.log("browser", message), + tempDirectories: [], + attemptToGracefullyClose: async () => { + debugLogger.log("browser", "Closing stdin..."); + launchedProcess.stdin.end(); + }, + onExit: (exitCode, signal) => { + debugLogger.log("browser", `ffmpeg onkill exitCode=${exitCode} signal=${signal}`); + } + }); + launchedProcess.stdin.on("finish", () => { + debugLogger.log("browser", "ffmpeg finished input."); + }); + launchedProcess.stdin.on("error", () => { + debugLogger.log("browser", "ffmpeg error."); + }); + this._process = launchedProcess; + this._gracefullyClose = gracefullyClose; + } + writeFrame(frame, timestamp) { + this._launchPromise.then((error) => { + if (error) + return; + this._writeFrame(frame, timestamp); + }); + } + _writeFrame(frame, timestamp) { + assert(this._process); + if (this._isStopped) + return; + if (!this._firstFrameTimestamp) + this._firstFrameTimestamp = timestamp; + const frameNumber = Math.floor((timestamp - this._firstFrameTimestamp) * fps); + if (this._lastFrame) { + const repeatCount = frameNumber - this._lastFrame.frameNumber; + for (let i = 0; i < repeatCount; ++i) + this._frameQueue.push(this._lastFrame.buffer); + this._lastWritePromise = this._lastWritePromise.then(() => this._sendFrames()); + } + this._lastFrame = { buffer: frame, timestamp, frameNumber }; + this._lastWriteNodeTime = 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((error) => { + if (error) + debugLogger.log("browser", `ffmpeg failed to write: ${String(error)}`); + }); + } + async _stop() { + const error = await this._launchPromise; + if (error) + throw error; + if (this._isStopped) + return; + if (!this._lastFrame) { + this._writeFrame(createWhiteImage(this._size.width, this._size.height), monotonicTime()); + } + const addTime = Math.max((monotonicTime() - this._lastWriteNodeTime) / 1e3, 1); + this._writeFrame(Buffer.from([]), this._lastFrame.timestamp + addTime); + this._isStopped = true; + try { + await this._lastWritePromise; + await this._gracefullyClose(); + } catch (e) { + debugLogger.log("error", `ffmpeg failed to stop: ${String(e)}`); + } + } + }; + } +}); + +// packages/playwright-core/src/server/chromium/crPage.ts +async function emulateLocale(session2, locale) { + try { + await session2.send("Emulation.setLocaleOverride", { locale }); + } catch (exception) { + if (exception.message.includes("Another locale override is already in effect")) + return; + throw exception; + } +} +async function emulateTimezone(session2, timezoneId) { + try { + await session2.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; +} +var CRPage, FrameSession; +var init_crPage = __esm({ + "packages/playwright-core/src/server/chromium/crPage.ts"() { + "use strict"; + init_assert(); + init_stackTrace(); + init_eventsHelper(); + init_dialog(); + init_dom(); + init_frames(); + init_helper(); + init_network2(); + init_page(); + init_crCoverage(); + init_crDragDrop(); + init_crExecutionContext(); + init_crInput(); + init_crNetworkManager(); + init_crPdf(); + init_crProtocolHelper(); + init_defaultFontFamilies(); + init_errors(); + init_protocolError(); + init_videoRecorder(); + init_progress(); + CRPage = class { + constructor(client, targetId, browserContext, opener, bits) { + this._sessions = /* @__PURE__ */ new Map(); + // Holds window features for the next popup being opened via window.open, + // until the popup target arrives. This could be racy if two oopifs + // simultaneously call window.open with window features: the order + // of their Page.windowOpen events is not guaranteed to match the order + // of new popup targets. + this._nextWindowOpenPopupFeatures = []; + this._targetId = targetId; + this._opener = opener; + const dragManager = new DragManager(this); + this.rawKeyboard = new RawKeyboardImpl(client, browserContext._browser._platform() === "mac", dragManager); + this.rawMouse = new RawMouseImpl(this, client, dragManager); + this.rawTouchscreen = new RawTouchscreenImpl(client); + this._pdf = new CRPDF(client); + this._coverage = new CRCoverage(client); + this._browserContext = browserContext; + this._page = new Page(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 }); + } + this._mainFrameSession._initialize(bits.hasUIWindow).then( + () => this._page.reportAsNew(this._opener?._page, void 0), + (error) => this._page.reportAsNew(this._opener?._page, error) + ); + } + 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 session2 of this._sessions.values()) + session2.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, format2, documentRect, viewportRect, quality, fitsViewport, scale) { + const { visualViewport, contentSize, cssContentSize } = await progress2.race(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._mainFrameSession._metricsOverride?.deviceScaleFactor || contentSize.width / cssContentSize.width || 1; + clip.scale /= deviceScaleFactor; + } + const result2 = await progress2.race(this._mainFrameSession._client.send("Page.captureScreenshot", { format: format2, quality, clip, captureBeyondViewport: !fitsViewport })); + return Buffer.from(result2.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); + } + startScreencast(options2) { + this._mainFrameSession._client.send("Page.startScreencast", { + format: "jpeg", + quality: options2.quality, + maxWidth: options2.width, + maxHeight: options2.height + }).catch(() => { + }); + } + stopScreencast() { + this._mainFrameSession._client._sendMayFail("Page.stopScreencast").catch(() => { + }); + } + rafCountForStablePosition() { + return 1; + } + async getContentQuads(handle) { + return this._sessionForHandle(handle)._getContentQuads(handle); + } + async setInputFilePaths(progress2, handle, files) { + const frame = await handle.ownerFrame(progress2); + if (!frame) + throw new Error("Cannot set input files to detached input element"); + const parentSession = this._sessionForFrame(frame); + await progress2.race(parentSession._client.send("DOM.setFileInputFiles", { + objectId: handle._objectId, + files + })); + } + async adoptElementHandle(handle, to) { + return this._sessionForHandle(handle)._adoptElementHandle(handle, to); + } + async inputActionEpilogue() { + await this._mainFrameSession._client.send("Page.enable").catch((e) => { + }); + } + async resetForReuse(progress2) { + await this.rawMouse.move(progress2, -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; + } + async setDockTile(image) { + await this._mainFrameSession._client.send("Browser.setDockTile", { image: image.toString("base64") }); + } + }; + FrameSession = class _FrameSession { + constructor(crPage, client, targetId, parentSession) { + this._childSessions = /* @__PURE__ */ new Set(); + this._contextIdToContext = /* @__PURE__ */ new Map(); + this._eventListeners = []; + this._firstNonInitialNavigationCommittedFulfill = () => { + }; + this._firstNonInitialNavigationCommittedReject = (e) => { + }; + // Marks the oopif session that remote -> local transition has happened in the parent. + // See Target.detachedFromTarget handler for details. + this._swappedIn = false; + 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()) + ]); + } + _addBrowserListeners() { + this._eventListeners.push(...[ + eventsHelper.addEventListener(this._client, "Target.attachedToTarget", (event) => this._onAttachedToTarget(event)), + eventsHelper.addEventListener(this._client, "Target.detachedFromTarget", (event) => this._onDetachedFromTarget(event)), + 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) { + if (!this._page.isStorageStatePage && hasUIWindow && !this._crPage._browserContext._browser.isClank() && !this._crPage._browserContext._options.noDefaultViewport) { + try { + const { windowId } = await this._client.send("Browser.getWindowForTarget"); + this._windowId = windowId; + } catch { + } + } + if (this._isMainFrame() && hasUIWindow && !this._page.isStorageStatePage) + startAutomaticVideoRecording(this._crPage._page); + let lifecycleEventsEnabled; + if (!this._isMainFrame()) + this._addRendererListeners(); + this._addBrowserListeners(); + this._bufferedAttachedToTargetEvents = []; + const promises = [ + this._client.send("Page.enable"), + this._client.send("Page.getFrameTree").then(({ frameTree }) => { + if (this._isMainFrame()) { + this._handleFrameTree(frameTree); + this._addRendererListeners(); + } + const attachedToTargetEvents = this._bufferedAttachedToTargetEvents || []; + this._bufferedAttachedToTargetEvents = void 0; + for (const event of attachedToTargetEvents) + this._onAttachedToTarget(event); + 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 (!this._page.isStorageStatePage) { + const skipDefaultOverrides = this._crPage._browserContext._browser.options.noDefaults && this._crPage._browserContext === this._crPage._browserContext._browser._defaultContext; + if (this._crPage._browserContext.needsPlaywrightBinding()) + promises.push(this.exposePlaywrightBinding()); + if (this._isMainFrame() && !skipDefaultOverrides) + promises.push(this._client.send("Emulation.setFocusEmulationEnabled", { enabled: true })); + const options2 = this._crPage._browserContext._options; + if (options2.bypassCSP) + promises.push(this._client.send("Page.setBypassCSP", { enabled: true })); + if (options2.ignoreHTTPSErrors || options2.internalIgnoreHTTPSErrors) + promises.push(this._client.send("Security.setIgnoreCertificateErrors", { ignore: true })); + if (this._isMainFrame()) + promises.push(this._updateViewport()); + if (options2.hasTouch) + promises.push(this._client.send("Emulation.setTouchEmulationEnabled", { enabled: true })); + if (options2.javaScriptEnabled === false) + promises.push(this._client.send("Emulation.setScriptExecutionDisabled", { value: true })); + if (options2.userAgent || options2.locale) + promises.push(this._updateUserAgent()); + if (options2.locale) + promises.push(emulateLocale(this._client, options2.locale)); + if (options2.timezoneId) + promises.push(emulateTimezone(this._client, options2.timezoneId)); + if (!this._crPage._browserContext._browser.options.headful) + promises.push(this._setDefaultFontFamilies(this._client)); + promises.push(this._updateGeolocation(true)); + if (!skipDefaultOverrides) + promises.push(this._updateEmulateMedia()); + promises.push(this._updateFileChooserInterception(true)); + for (const initScript of this._crPage._page.allInitScripts()) + promises.push(this._evaluateOnNewDocument( + initScript, + "main", + true + /* runImmediately */ + )); + } + promises.push(this._client.send("Runtime.runIfWaitingForDebugger")); + promises.push(this._firstNonInitialNavigationCommittedPromise); + await Promise.all(promises); + } + dispose() { + this._firstNonInitialNavigationCommittedReject(new TargetClosedError(this._page.closeReason())); + 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.isDownload) + throw new NavigationAbortedError(response2.loaderId, "Download is starting"); + 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 session2 = this._crPage._sessionForFrame(frame); + return session2 && session2 !== this && !session2._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 context2 = new FrameExecutionContext(delegate, frame, worldName); + if (worldName) + frame.contextCreated(worldName, context2); + this._contextIdToContext.set(contextPayload.id, context2); + } + _onExecutionContextDestroyed(executionContextId) { + const context2 = this._contextIdToContext.get(executionContextId); + if (!context2) + return; + this._contextIdToContext.delete(executionContextId); + context2.frame.contextDestroyed(context2); + } + _onExecutionContextsCleared() { + for (const contextId4 of Array.from(this._contextIdToContext.keys())) + this._onExecutionContextDestroyed(contextId4); + } + _onAttachedToTarget(event) { + if (this._bufferedAttachedToTargetEvents) { + this._bufferedAttachedToTargetEvents.push(event); + return; + } + const session2 = this._client.createChildSession(event.sessionId); + if (event.targetInfo.type === "iframe") { + const targetId = event.targetInfo.targetId; + let frame = this._page.frameManager.frame(targetId); + if (!frame && event.targetInfo.parentFrameId) { + frame = this._page.frameManager.frameAttached(targetId, event.targetInfo.parentFrameId); + } + if (!frame) + return; + this._page.frameManager.removeChildFramesRecursively(frame); + for (const [contextId4, context2] of this._contextIdToContext) { + if (context2.frame === frame) + this._onExecutionContextDestroyed(contextId4); + } + const frameSession = new _FrameSession(this._crPage, session2, targetId, this); + this._crPage._sessions.set(targetId, frameSession); + frameSession._initialize(false).catch((e) => e); + return; + } + if (event.targetInfo.type !== "worker") { + session2.detach().catch(() => { + }); + return; + } + const url2 = event.targetInfo.url; + const worker = new Worker(this._page, url2); + this._page.addWorker(event.sessionId, worker); + this._workerSessions.set(event.sessionId, session2); + session2.once("Runtime.executionContextCreated", async (event2) => { + worker.createExecutionContext(new CRExecutionContext(session2, event2.context)); + }); + if (this._crPage._browserContext._browser.majorVersion() >= 143) + session2.on("Inspector.workerScriptLoaded", () => worker.workerScriptLoaded()); + else + worker.workerScriptLoaded(); + session2._sendMayFail("Runtime.enable"); + this._crPage._networkManager.addSession(session2, this._page.frameManager.frame(this._targetId) ?? void 0).catch(() => { + }); + session2._sendMayFail("Runtime.runIfWaitingForDebugger"); + session2._sendMayFail("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true }); + session2.on("Target.attachedToTarget", (event2) => this._onAttachedToTarget(event2)); + session2.on("Target.detachedFromTarget", (event2) => this._onDetachedFromTarget(event2)); + session2.on("Runtime.consoleAPICalled", (event2) => { + const args = event2.args.map((o) => createHandle(worker.existingExecutionContext, o)); + this._page.addConsoleMessage(worker, event2.type, args, stackTraceToLocation(event2.stackTrace), void 0, event2.timestamp); + }); + session2.on("Runtime.exceptionThrown", (exception) => this._page.addPageError(exceptionToError(exception.exceptionDetails), stackTraceToLocation(exception.exceptionDetails.stackTrace))); + } + _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 context2 = this._contextIdToContext.get(event.executionContextId); + if (!context2) + return; + const values = event.args.map((arg) => createHandle(context2, arg)); + this._page.addConsoleMessage(null, event.type, values, stackTraceToLocation(event.stackTrace), void 0, event.timestamp); + } + async _onBindingCalled(event) { + const pageOrError = await this._crPage._page.waitForInitializedOrError(); + if (!(pageOrError instanceof Error)) { + const context2 = this._contextIdToContext.get(event.executionContextId); + if (context2) + await this._page.onBindingCalled(event.payload, context2); + } + } + _onDialog(event) { + if (!this._page.frameManager.frame(this._targetId)) + return; + this._page.browserContext.dialogManager.dialogDidOpen(new Dialog( + 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.addPageError(exceptionToError(exceptionDetails), stackTraceToLocation(exceptionDetails.stackTrace)); + } + async _onTargetCrashed() { + this._client._markAsCrashed(); + this._page._didCrash(); + } + _onLogEntryAdded(event) { + const { level, text: text2, args, source: source8, url: url2, lineNumber } = event.entry; + if (args) + args.map((arg) => releaseObject(this._client, arg.objectId)); + if (source8 !== "worker") { + const location2 = { + url: url2 || "", + lineNumber: lineNumber || 0, + columnNumber: 0 + }; + this._page.addConsoleMessage(null, level, [], location2, text2, event.entry.timestamp); + } + } + 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) { + const buffer = Buffer.from(payload.data, "base64"); + this._page.screencast.onScreencastFrame({ + buffer, + frameSwapWallTime: payload.metadata.timestamp ? payload.metadata.timestamp * 1e3 : Date.now(), + viewportWidth: payload.metadata.deviceWidth, + viewportHeight: payload.metadata.deviceHeight + }, () => { + this._client._sendMayFail("Page.screencastFrameAck", { sessionId: payload.sessionId }); + }); + } + 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 promises = []; + 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; + } + } + promises.push(this.setWindowBounds({ + width: viewportSize.width + insets.width, + height: viewportSize.height + insets.height + })); + } + promises.push(this._client.send("Emulation.setDeviceMetricsOverride", metricsOverride)); + await Promise.all(promises); + 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(session2) { + const fontFamilies = platformToFontFamilies[this._crPage._browserContext._browser._platform()]; + await session2.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((node) => { + const doc = node; + if (doc.documentElement && doc.documentElement.ownerDocument === doc) + return doc.documentElement; + return node.ownerDocument ? node.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 result2 = await this._client._sendMayFail("DOM.getBoxModel", { + objectId: handle._objectId + }); + if (!result2) + return null; + const quad = result2.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 element2 = await frame.frameElement(nullProgress); + const box = await element2.boundingBox(nullProgress); + 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 result2 = await this._client._sendMayFail("DOM.getContentQuads", { + objectId: handle._objectId + }); + if (!result2) + return null; + const position = await this._framePosition(); + if (!position) + return null; + return result2.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 result2 = await this._client._sendMayFail("DOM.resolveNode", { + backendNodeId, + executionContextId: to.delegate._contextId + }); + if (!result2 || result2.object.subtype === "null") + throw new Error(kUnableToAdoptErrorMessage); + return createHandle(to, result2.object).asElement(); + } + }; + } +}); + +// packages/playwright-core/src/server/chromium/crServiceWorker.ts +var CRServiceWorker; +var init_crServiceWorker = __esm({ + "packages/playwright-core/src/server/chromium/crServiceWorker.ts"() { + "use strict"; + init_page(); + init_crExecutionContext(); + init_crNetworkManager(); + init_browserContext(); + init_network2(); + init_console(); + init_crProtocolHelper(); + CRServiceWorker = class extends Worker { + constructor(browserContext, session2, url2) { + super(browserContext, url2); + this._session = session2; + this.browserContext = browserContext; + if (!process.env.PLAYWRIGHT_DISABLE_SERVICE_WORKER_NETWORK) + this._networkManager = new CRNetworkManager(null, this); + session2.on("Inspector.targetCrashed", () => this.destroyExecutionContext("Service worker restarted")); + session2.on("Runtime.executionContextCreated", (event) => { + this.createExecutionContext(new CRExecutionContext(session2, event.context)); + if (this.browserContext._browser.majorVersion() < 143) + this.workerScriptLoaded(); + }); + if (this.browserContext._browser.majorVersion() >= 143) + session2.on("Inspector.workerScriptLoaded", () => this.workerScriptLoaded()); + if (this._networkManager && this._isNetworkInspectionEnabled()) { + this.updateRequestInterception(); + this.updateExtraHTTPHeaders(); + this.updateHttpCredentials(); + this.updateOffline(); + this._networkManager.addSession( + session2, + void 0, + true + /* isMain */ + ).catch(() => { + }); + } + session2.on("Runtime.consoleAPICalled", (event) => { + if (!this.existingExecutionContext || process.env.PLAYWRIGHT_DISABLE_SERVICE_WORKER_CONSOLE) + return; + const args = event.args.map((o) => createHandle(this.existingExecutionContext, o)); + const message = new ConsoleMessage(null, this, event.type, void 0, args, stackTraceToLocation(event.stackTrace), event.timestamp); + this.browserContext.emit(BrowserContext.Events.Console, message); + }); + session2.send("Runtime.enable", {}).catch((e) => { + }); + session2.send("Runtime.runIfWaitingForDebugger").catch((e) => { + }); + session2.on("Inspector.targetReloadedAfterCrash", () => { + session2._sendMayFail("Runtime.runIfWaitingForDebugger", {}); + }); + } + didClose() { + this._networkManager?.removeSession(this._session); + this._session.dispose(); + super.didClose(); + } + async updateOffline() { + if (!this._isNetworkInspectionEnabled()) + return; + await this._networkManager?.setOffline(!!this.browserContext._options.offline).catch(() => { + }); + } + async updateHttpCredentials() { + if (!this._isNetworkInspectionEnabled()) + return; + await this._networkManager?.authenticate(this.browserContext._options.httpCredentials || null).catch(() => { + }); + } + async updateExtraHTTPHeaders() { + if (!this._isNetworkInspectionEnabled()) + return; + await this._networkManager?.setExtraHTTPHeaders(this.browserContext._options.extraHTTPHeaders || []).catch(() => { + }); + } + async updateRequestInterception() { + if (!this._isNetworkInspectionEnabled()) + return; + await this._networkManager?.setRequestInterception(this.needsRequestInterception()).catch(() => { + }); + } + needsRequestInterception() { + return this._isNetworkInspectionEnabled() && this.browserContext.requestInterceptors.length > 0; + } + reportRequestFinished(request2, response2) { + this.browserContext.emit(BrowserContext.Events.RequestFinished, { request: request2, response: response2 }); + } + requestFailed(request2, _canceled) { + this.browserContext.emit(BrowserContext.Events.RequestFailed, request2); + } + requestReceivedResponse(response2) { + this.browserContext.emit(BrowserContext.Events.Response, response2); + } + requestStarted(request2, route2) { + this.browserContext.emit(BrowserContext.Events.Request, request2); + if (route2) + new Route(request2, route2).handle(this.browserContext.requestInterceptors); + } + _isNetworkInspectionEnabled() { + return this.browserContext._options.serviceWorkers !== "block"; + } + }; + } +}); + +// packages/playwright-core/src/server/chromium/crBrowser.ts +function shouldProxyLoopback(bypass) { + if (process.env.PLAYWRIGHT_DISABLE_FORCED_CHROMIUM_PROXIED_LOOPBACK) + return false; + const hosts = (bypass || "").split(",").map((s) => s.trim()); + const shouldBypassSomeLoopback = ["localhost", "127.0.0.1", "::1", "[::]", "[::1]", "", "<-loopback>"].some((host) => hosts.includes(host)); + return !shouldBypassSomeLoopback; +} +var import_path22, CRBrowser, CREvents, CRBrowserContext; +var init_crBrowser = __esm({ + "packages/playwright-core/src/server/chromium/crBrowser.ts"() { + "use strict"; + import_path22 = __toESM(require("path")); + init_assert(); + init_crypto(); + init_artifact(); + init_browser(); + init_browserContext(); + init_frames(); + init_network2(); + init_page(); + init_crConnection(); + init_crPage(); + init_crProtocolHelper(); + init_crServiceWorker(); + CRBrowser = class _CRBrowser extends Browser { + constructor(parent, connection, options2) { + super(parent, options2); + this._clientRootSessionPromise = null; + this._contexts = /* @__PURE__ */ new Map(); + this._crPages = /* @__PURE__ */ new Map(); + this._serviceWorkers = /* @__PURE__ */ new Map(); + this._version = ""; + this._majorVersion = 0; + this._revision = ""; + this._tracingRecording = false; + this._userAgent = ""; + this._connection = connection; + this._session = this._connection.rootSession; + this._connection.on(ConnectionEvents.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(parent, transport, options2.protocolLogger, options2.browserLogsCollector); + const browser = new _CRBrowser(parent, connection, options2); + browser._devtools = devtools; + if (browser.isClank()) + browser._isCollocatedWithServer = false; + const session2 = connection.rootSession; + if (options2.__testHookOnConnectToBrowser) + await options2.__testHookOnConnectToBrowser(); + const version3 = await session2.send("Browser.getVersion"); + browser._revision = version3.revision; + browser._version = version3.product.substring(version3.product.indexOf("/") + 1); + try { + browser._majorVersion = +browser._version.split(".")[0]; + } catch { + } + browser._userAgent = version3.userAgent; + browser.options.headful = !version3.userAgent.includes("Headless"); + if (!options2.persistent) { + await session2.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true }); + return browser; + } + browser._defaultContext = new CRBrowserContext(browser, void 0, options2.persistent); + await Promise.all([ + session2.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true }).then(async () => { + await session2.send("Target.getTargetInfo"); + }), + browser._defaultContext.initialize() + ]); + await browser._waitForAllPagesToBeInitialized(); + return browser; + } + async doCreateNewContext(options2) { + const proxy = options2.proxyOverride || options2.proxy; + let proxyBypassList = void 0; + if (proxy) { + if (shouldProxyLoopback(proxy.bypass)) + proxyBypassList = "<-loopback>" + (proxy.bypass ? `,${proxy.bypass}` : ""); + else + proxyBypassList = proxy.bypass; + } + const { browserContextId } = await this._session.send("Target.createBrowserContext", { + disposeOnDetach: true, + proxyServer: proxy ? proxy.server : void 0, + proxyBypassList + }); + const context2 = new CRBrowserContext(this, browserContextId, options2); + await context2.initialize(); + this._contexts.set(browserContextId, context2); + return context2; + } + contexts() { + return Array.from(this._contexts.values()); + } + version() { + return this._version; + } + majorVersion() { + return this._majorVersion; + } + 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 session2 = this._session.createChildSession(sessionId); + assert(targetInfo.browserContextId, "targetInfo: " + JSON.stringify(targetInfo, null, 2)); + let context2 = this._contexts.get(targetInfo.browserContextId) || null; + if (!context2) { + context2 = this._defaultContext; + } + if (targetInfo.type === "other" && targetInfo.url.startsWith("devtools://devtools") && this._devtools) { + this._devtools.install(session2); + return; + } + const treatOtherAsPage = targetInfo.type === "other" && process.env.PW_CHROMIUM_ATTACH_TO_OTHER; + if (!context2 || targetInfo.type === "other" && !treatOtherAsPage) { + session2.detach().catch(() => { + }); + return; + } + assert(!this._crPages.has(targetInfo.targetId), "Duplicate target " + targetInfo.targetId); + assert(!this._serviceWorkers.has(targetInfo.targetId), "Duplicate target " + targetInfo.targetId); + if (targetInfo.type === "page" || treatOtherAsPage) { + const opener = targetInfo.openerId ? this._crPages.get(targetInfo.openerId) || null : null; + const crPage = new CRPage(session2, targetInfo.targetId, context2, opener, { hasUIWindow: targetInfo.type === "page" }); + this._crPages.set(targetInfo.targetId, crPage); + return; + } + if (targetInfo.type === "service_worker") { + const serviceWorker = new CRServiceWorker(context2, session2, targetInfo.url); + this._serviceWorkers.set(targetInfo.targetId, serviceWorker); + context2.emit(CRBrowserContext.CREvents.ServiceWorker, serviceWorker); + return; + } + session2.detach().catch(() => { + }); + } + _onDetachedFromTarget(payload) { + const targetId = payload.targetId; + const crPage = this._crPages.get(targetId); + if (crPage) { + this._crPages.delete(targetId); + crPage.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 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: categories2 = defaultCategories + } = options2; + if (screenshots) + categories2.push("disabled-by-default-devtools.screenshot"); + this._tracingRecording = true; + await this._tracingClient.send("Tracing.start", { + transferMode: "ReturnAsStream", + categories: categories2.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 = import_path22.default.join(this.options.artifactsDir, createGuid() + ".crtrace"); + await saveProtocolStream(this._tracingClient, event.stream, tracingPath); + this._tracingRecording = false; + const artifact = new Artifact(this, tracingPath); + artifact.reportFinished(); + return artifact; + } + isConnected() { + return !this._connection._closed; + } + async _clientRootSession() { + if (!this._clientRootSessionPromise) + this._clientRootSessionPromise = this._connection.createBrowserSession(); + return this._clientRootSessionPromise; + } + }; + CREvents = { + ServiceWorker: "serviceworker" + }; + CRBrowserContext = class extends BrowserContext { + static { + this.CREvents = CREvents; + } + constructor(browser, browserContextId, options2) { + super(browser, options2, browserContextId); + this.authenticateProxyViaCredentials(); + } + async initialize() { + assert(!Array.from(this._browser._crPages.values()).some((page) => page._browserContext === this)); + const promises = [super.initialize()]; + if (this._browser.options.name !== "clank" && this._options.acceptDownloads !== "internal-browser-default") { + promises.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(promises); + } + _crPages() { + return [...this._browser._crPages.values()].filter((crPage) => crPage._browserContext === this); + } + possiblyUninitializedPages() { + return this._crPages().map((crPage) => crPage._page); + } + async doCreateNewPage() { + const { targetId } = await this._browser._session.send("Target.createTarget", { url: "about:blank", browserContextId: this._browserContextId }); + return this._browser._crPages.get(targetId)._page; + } + async doGetCookies(urls) { + const { cookies } = await this._browser._session.send("Storage.getCookies", { browserContextId: this._browserContextId }); + return filterCookies(cookies.map((c) => { + const { name, value: value2, domain, path: path59, expires, httpOnly, secure, sameSite } = c; + const copy = { + name, + value: value2, + domain, + path: path59, + expires, + httpOnly, + secure, + sameSite: sameSite ?? "Lax" + }; + if (c.partitionKey) { + copy._crHasCrossSiteAncestor = c.partitionKey.hasCrossSiteAncestor; + copy.partitionKey = c.partitionKey.topLevelSite; + } + return copy; + }), urls); + } + async addCookies(cookies) { + function toChromiumCookie(cookie) { + const { name, value: value2, url: url2, domain, path: path59, expires, httpOnly, secure, sameSite, partitionKey, _crHasCrossSiteAncestor } = cookie; + const copy = { + name, + value: value2, + url: url2, + domain, + path: path59, + expires, + httpOnly, + secure, + sameSite + }; + if (partitionKey) { + copy.partitionKey = { + topLevelSite: partitionKey, + // _crHasCrossSiteAncestor is non-standard, set it true by default if the cookie is partitioned. + hasCrossSiteAncestor: _crHasCrossSiteAncestor ?? true + }; + } + return copy; + } + await this._browser._session.send("Storage.setCookies", { + cookies: rewriteCookies(cookies).map(toChromiumCookie), + 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"], + ["local-fonts", "localFonts"], + ["local-network-access", ["localNetworkAccess", "localNetwork", "loopbackNetwork"]], + ["screen-wake-lock", "wakeLockScreen"] + ]); + const grantPermissions = async (mapping) => { + const filtered = permissions.flatMap((permission) => { + const protocolPermission = mapping.get(permission); + if (!protocolPermission) + throw new Error("Unknown permission: " + permission); + return typeof protocolPermission === "string" ? [protocolPermission] : protocolPermission; + }); + await this._browser._session.send("Browser.grantPermissions", { origin: origin === "*" ? void 0 : origin, browserContextId: this._browserContextId, permissions: filtered }); + }; + try { + await grantPermissions(webPermissionToProtocol); + } catch (e) { + const fallbackMapping = new Map(webPermissionToProtocol); + fallbackMapping.set("local-network-access", ["localNetworkAccess"]); + await grantPermissions(fallbackMapping); + } + } + 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 doUpdateExtraHTTPHeaders() { + 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 doUpdateOffline() { + 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 doUpdateDefaultViewport() { + } + async doUpdateDefaultEmulatedMedia() { + } + async doExposePlaywrightBinding() { + for (const page of this._crPages()) + await page.exposePlaywrightBinding(); + } + async doClose(reason) { + await this.dialogManager.closeBeforeUnloadDialogs(); + if (!this._browserContextId) { + return "close-browser"; + } + await Promise.all([...this._downloads].map((download) => download.cancel().catch(() => { + }))); + 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); + } + } + onClosePersistent() { + } + 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 + }); + } + serviceWorkers() { + return Array.from(this._browser._serviceWorkers.values()).filter((serviceWorker) => serviceWorker.browserContext === this); + } + async newCDPSession(page) { + let targetId = null; + if (page instanceof Page) { + targetId = page.delegate._targetId; + } else if (page instanceof Frame) { + const session2 = page._page.delegate._sessions.get(page._id); + if (!session2) + throw new Error(`This frame does not have a separate CDP session, it is a part of the parent frame's session`); + targetId = session2._targetId; + } else { + throw new Error("page: expected Page or Frame"); + } + const rootSession = await this._browser._clientRootSession(); + return rootSession.attachToTarget(targetId); + } + }; + } +}); + +// packages/playwright-core/src/server/android/android.ts +function encodeWebFrame(data) { + return import_utilsBundle.wsSender.frame(Buffer.from(data), { + opcode: 1, + mask: true, + fin: true, + readOnly: true + })[0]; +} +var import_events7, import_fs24, import_os9, import_path23, import_utilsBundle, debug3, ARTIFACTS_FOLDER, Android, AndroidDevice, AndroidBrowser, ClankBrowserProcess; +var init_android = __esm({ + "packages/playwright-core/src/server/android/android.ts"() { + "use strict"; + import_events7 = require("events"); + import_fs24 = __toESM(require("fs")); + import_os9 = __toESM(require("os")); + import_path23 = __toESM(require("path")); + init_pipeTransport(); + init_crypto(); + init_debug(); + init_env(); + init_task(); + init_debugLogger(); + init_fileUtils(); + init_processLauncher(); + import_utilsBundle = require("./utilsBundle"); + init_browserContext(); + init_chromiumSwitches(); + init_crBrowser(); + init_helper(); + init_instrumentation(); + init_progress(); + init_registry(); + debug3 = require("./utilsBundle").debug; + ARTIFACTS_FOLDER = import_path23.default.join(import_os9.default.tmpdir(), "playwright-artifacts-"); + Android = class extends SdkObject { + constructor(parent, backend) { + super(parent, "android"); + this._devices = /* @__PURE__ */ new Map(); + this._backend = backend; + } + async devices(progress2, options2) { + const devices = (await progress2.race(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; + await progress2.race(AndroidDevice.create(this, d, options2).then((device) => 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); + } + }; + AndroidDevice = class _AndroidDevice 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; + this.logName = "browser"; + } + static { + this.Events = { + WebViewAdded: "webViewAdded", + WebViewRemoved: "webViewRemoved", + Close: "close" + }; + } + static async create(android, backend, options2) { + await backend.init(); + const model = await backend.runCommand("shell:getprop ro.product.model"); + const device = new _AndroidDevice(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(progress2, command) { + return await progress2.race(this._shell(command)); + } + async _shell(command) { + const result2 = await this._backend.runCommand(`shell:${command}`); + await this._refreshWebViews(); + return result2; + } + async open(progress2, command) { + return await this._open(progress2, command); + } + async screenshot(progress2) { + return await progress2.race(this._backend.runCommand(`shell:screencap -p`)); + } + async _driver() { + if (this._isClosed) + return; + if (!this._driverPromise) { + const controller = new ProgressController(); + this._driverPromise = controller.run((progress2) => this._installDriver(progress2)); + } + return this._driverPromise; + } + async _installDriver(progress2) { + debug3("pw:android")("Stopping the old driver"); + await progress2.race(this._shell(`am force-stop com.microsoft.playwright.androiddriver`)); + if (!this._options.omitDriverInstall) { + debug3("pw:android")("Uninstalling the old driver"); + await this.shell(progress2, `cmd package uninstall com.microsoft.playwright.androiddriver`); + await this.shell(progress2, `cmd package uninstall com.microsoft.playwright.androiddriver.test`); + debug3("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 = import_path23.default.join(executable.directory, file); + if (!import_fs24.default.existsSync(fullName)) + throw new Error(`Please install Android driver apk using '${packageManagerCommand} playwright install android'`); + await this.installApk(progress2, await progress2.race(import_fs24.default.promises.readFile(fullName))); + } + } else { + debug3("pw:android")("Skipping the driver installation"); + } + debug3("pw:android")("Starting the new driver"); + this._shell("am instrument -w com.microsoft.playwright.androiddriver.test/androidx.test.runner.AndroidJUnitRunner").catch((e) => debug3("pw:android")(e)); + const socket = await this._waitForLocalAbstract(progress2, "playwright_android_driver_socket"); + const transport = new PipeTransport(socket, socket, socket, "be"); + transport.onmessage = (message) => { + const response2 = JSON.parse(message); + const { id, result: result2, error } = response2; + const callback = this._callbacks.get(id); + if (!callback) + return; + if (error) + callback.reject(new Error(error)); + else + callback.fulfill(result2); + this._callbacks.delete(id); + }; + return transport; + } + async _waitForLocalAbstract(progress2, socketName) { + let socket; + debug3("pw:android")(`Polling the socket localabstract:${socketName}`); + while (!socket) { + try { + socket = await this._open(progress2, `localabstract:${socketName}`); + } catch (e) { + if (isAbortError(e)) + throw e; + await progress2.wait(250); + } + } + debug3("pw:android")(`Connected to localabstract:${socketName}`); + return socket; + } + async send(progress2, method, params2 = {}) { + return await progress2.race(this._send(method, params2)); + } + async _send(method, params2 = {}) { + params2 = { + ...params2, + // Patch the timeout in, just in case it's missing in one of the commands. + timeout: params2.timeout || 0 + }; + if (params2.androidSelector) { + params2.selector = params2.androidSelector; + delete params2.androidSelector; + } + const driver = await this._driver(); + if (!driver) + throw new Error("Device is closed"); + const id = ++this._lastId; + const result2 = new Promise((fulfill, reject) => this._callbacks.set(id, { fulfill, reject })); + driver.send(JSON.stringify({ id, method, params: params2 })); + return result2; + } + async close(progress2) { + await progress2.race(this._close()); + } + 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?.close(); + } + await this._backend.close(); + this._android._deviceClosed(this); + this.emit(_AndroidDevice.Events.Close); + } + async launchBrowser(progress2, pkg = "com.android.chrome", options2) { + debug3("pw:android")("Force-stopping", pkg); + await progress2.race(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(" "); + debug3("pw:android")("Starting", pkg, commandLine); + await progress2.race(this._backend.runCommand(`shell:echo "${Buffer.from(commandLine).toString("base64")}" | base64 -d > /data/local/tmp/chrome-command-line`)); + await progress2.race(this._backend.runCommand(`shell:am start -a android.intent.action.VIEW -d about:blank ${pkg}`)); + const browserContext = await this._connectToBrowser(progress2, socketName, options2); + try { + await progress2.race(this._backend.runCommand(`shell:rm /data/local/tmp/chrome-command-line`)); + return browserContext; + } catch (error) { + await browserContext.close(progress2, { reason: "Failed to launch" }).catch(() => { + }); + throw error; + } + } + _defaultArgs(options2, socketName) { + const chromeArguments = [ + "_", + "--disable-fre", + "--no-default-browser-check", + `--remote-debugging-socket-name=${socketName}`, + ...chromiumSwitches({ android: true }), + ...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 (shouldProxyLoopback(proxy.bypass)) + proxyBypassRules.push("<-loopback>"); + if (proxyBypassRules.length > 0) + chromeArguments.push(`--proxy-bypass-list=${proxyBypassRules.join(";")}`); + } + chromeArguments.push(...args); + return chromeArguments; + } + async connectToWebView(progress2, socketName) { + const webView = this._webViews.get(socketName); + if (!webView) + throw new Error("WebView has been closed"); + return await this._connectToBrowser(progress2, socketName); + } + async _connectToBrowser(progress2, socketName, options2 = {}) { + const socket = await this._waitForLocalAbstract(progress2, socketName); + try { + const androidBrowser = new AndroidBrowser(this, socket); + await progress2.race(androidBrowser._init()); + this._browserConnections.add(androidBrowser); + const artifactsDir = await progress2.race(import_fs24.default.promises.mkdtemp(ARTIFACTS_FOLDER)); + const cleanupArtifactsDir = async () => { + const errors = (await removeFolders([artifactsDir])).filter(Boolean); + for (let i = 0; i < (errors || []).length; ++i) + debug3("pw:android")(`exception while removing ${artifactsDir}: ${errors[i]}`); + }; + gracefullyCloseSet.add(cleanupArtifactsDir); + socket.on("close", async () => { + gracefullyCloseSet.delete(cleanupArtifactsDir); + cleanupArtifactsDir().catch((e) => debug3("pw:android")(`could not cleanup artifacts dir: ${e}`)); + }); + const browserOptions = { + name: "clank", + browserType: "chromium", + 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: {} + }; + validateBrowserContextOptions(options2, browserOptions); + const browser = await progress2.race(CRBrowser.connect(this.attribution.playwright, androidBrowser, browserOptions)); + const defaultContext = browser._defaultContext; + await defaultContext.loadDefaultContextAsIs(progress2); + return defaultContext; + } catch (error) { + socket.close(); + throw error; + } + } + _open(progress2, command) { + return raceUncancellableOperationWithCleanup(progress2, () => this._backend.open(command), (socket) => socket.close()); + } + webViews() { + return [...this._webViews.values()]; + } + async installApk(progress2, content, options2) { + const args = options2 && options2.args ? options2.args : ["-r", "-t", "-S"]; + debug3("pw:android")("Opening install socket"); + const installSocket = await this._open(progress2, `shell:cmd package install ${args.join(" ")} ${content.length}`); + debug3("pw:android")("Writing driver bytes: " + content.length); + await progress2.race(installSocket.write(content)); + const success = await progress2.race(new Promise((f) => installSocket.on("data", f))); + debug3("pw:android")("Written driver bytes: " + success); + installSocket.close(); + } + async push(progress2, content, path59, mode = 420) { + const socket = await this._open(progress2, `sync:`); + const sendHeader = async (progress3, command, length) => { + const buffer = Buffer.alloc(command.length + 4); + buffer.write(command, 0); + buffer.writeUInt32LE(length, command.length); + await progress3.race(socket.write(buffer)); + }; + const send = async (progress3, command, data) => { + await sendHeader(progress3, command, data.length); + await progress3.race(socket.write(data)); + }; + await send(progress2, "SEND", Buffer.from(`${path59},${mode}`)); + const maxChunk = 65535; + for (let i = 0; i < content.length; i += maxChunk) + await send(progress2, "DATA", content.slice(i, i + maxChunk)); + await sendHeader(progress2, "DONE", Date.now() / 1e3 | 0); + const result2 = await progress2.race(new Promise((f) => socket.once("data", f))); + const code = result2.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(_AndroidDevice.Events.WebViewAdded, webView); + } + for (const p of this._webViews.keys()) { + if (!socketNames.has(p)) { + this._webViews.delete(p); + this.emit(_AndroidDevice.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; + } + }; + AndroidBrowser = class extends import_events7.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 import_utilsBundle.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", (data) => this._receiver._write(data, "binary", () => { + })); + } + async send(s) { + await this._socket.write(encodeWebFrame(JSON.stringify(s))); + } + async close() { + this._socket.close(); + } + }; + ClankBrowserProcess = class { + constructor(browser) { + this._browser = browser; + } + async kill() { + } + async close() { + await this._browser.close(); + } + }; + } +}); + +// packages/playwright-core/src/server/android/backendAdb.ts +async function runCommand(command, host = "127.0.0.1", port = 5037, serial) { + debug4("pw:adb:runCommand")(command, serial); + const socket = new BufferedSocketWrapper(command, import_net4.default.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(command)); + const status = await socket.read(4); + assert(status.toString() === "OKAY", status.toString()); + let commandOutput; + if (!command.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 open2(command, host = "127.0.0.1", port = 5037, serial) { + const socket = new BufferedSocketWrapper(command, import_net4.default.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(command)); + 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); +} +var import_events8, import_net4, debug4, AdbBackend, AdbDevice, BufferedSocketWrapper; +var init_backendAdb = __esm({ + "packages/playwright-core/src/server/android/backendAdb.ts"() { + "use strict"; + import_events8 = require("events"); + import_net4 = __toESM(require("net")); + init_assert(); + debug4 = require("./utilsBundle").debug; + AdbBackend = class { + async devices(options2 = {}) { + const result2 = await runCommand("host:devices", options2.host, options2.port); + const lines = result2.toString().trim().split("\n"); + return lines.map((line) => { + const [serial, status] = line.trim().split(" "); + return new AdbDevice(serial, status, options2.host, options2.port); + }); + } + }; + AdbDevice = class { + 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(command) { + if (this._closed) + throw new Error("Device is closed"); + return runCommand(command, this.host, this.port, this.serial); + } + async open(command) { + if (this._closed) + throw new Error("Device is closed"); + const result2 = await open2(command, this.host, this.port, this.serial); + result2.becomeSocket(); + return result2; + } + }; + BufferedSocketWrapper = class extends import_events8.EventEmitter { + constructor(command, socket) { + super(); + this._buffer = Buffer.from([]); + this._isSocket = false; + this._isClosed = false; + this._command = command; + this._socket = socket; + this._connectPromise = new Promise((f) => this._socket.on("connect", f)); + this._socket.on("data", (data) => { + debug4("pw:adb:data")(data.toString()); + if (this._isSocket) { + this.emit("data", data); + return; + } + this._buffer = Buffer.concat([this._buffer, data]); + 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", (error) => this.emit("error", error)); + } + async write(data) { + debug4("pw:adb:send")(data.toString().substring(0, 100) + "..."); + await this._connectPromise; + await new Promise((f) => this._socket.write(data, f)); + } + close() { + if (this._isClosed) + return; + debug4("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 result2 = this._buffer.slice(0, length); + this._buffer = this._buffer.slice(length); + debug4("pw:adb:recv")(result2.toString().substring(0, 100) + "..."); + return result2; + } + async readAll() { + while (!this._isClosed) + await new Promise((f) => this._notifyReader = f); + return this._buffer; + } + becomeSocket() { + assert(!this._buffer.length); + this._isSocket = true; + } + }; + } +}); + +// packages/playwright-core/src/server/pipeTransport.ts +var PipeTransport2; +var init_pipeTransport2 = __esm({ + "packages/playwright-core/src/server/pipeTransport.ts"() { + "use strict"; + init_debugLogger(); + init_task(); + PipeTransport2 = class { + constructor(pipeWrite, pipeRead) { + this._pendingBuffers = []; + this._waitForNextTask = makeWaitForNextTask(); + this._closed = false; + this._pipeRead = pipeRead; + this._pipeWrite = pipeWrite; + pipeRead.on("data", (buffer) => this._dispatch(buffer)); + 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(buffer) { + let end = buffer.indexOf("\0"); + if (end === -1) { + this._pendingBuffers.push(buffer); + return; + } + this._pendingBuffers.push(buffer.slice(0, end)); + const message = Buffer.concat(this._pendingBuffers).toString(); + this._waitForNextTask(() => { + if (this.onmessage) + this.onmessage.call(null, JSON.parse(message)); + }); + let start3 = end + 1; + end = buffer.indexOf("\0", start3); + while (end !== -1) { + const message2 = buffer.toString(void 0, start3, end); + this._waitForNextTask(() => { + if (this.onmessage) + this.onmessage.call(null, JSON.parse(message2)); + }); + start3 = end + 1; + end = buffer.indexOf("\0", start3); + } + this._pendingBuffers = [buffer.slice(start3)]; + } + }; + } +}); + +// packages/playwright-core/src/server/transport.ts +function stripQueryParams(url2) { + try { + const u = new URL(url2); + u.search = ""; + u.hash = ""; + return u.toString(); + } catch { + return url2; + } +} +var ws, perMessageDeflate2, WebSocketTransport; +var init_transport = __esm({ + "packages/playwright-core/src/server/transport.ts"() { + "use strict"; + init_happyEyeballs(); + init_task(); + ws = require("./utilsBundle").ws; + perMessageDeflate2 = { + clientNoContextTakeover: true, + zlibDeflateOptions: { + level: 3 + }, + zlibInflateOptions: { + chunkSize: 10 * 1024 + }, + threshold: 10 * 1024 + }; + WebSocketTransport = 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, + headers: options2.headers, + followRedirects: options2.followRedirects, + agent: /^(https|wss):\/\//.test(url2) ? httpsHappyEyeballsAgent : httpHappyEyeballsAgent, + perMessageDeflate: perMessageDeflate2 + }); + 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?.log(response2.rawHeaders[i + 1]); + } + }); + this._progress = progress2; + const messageWrap = makeWaitForNextTask(); + this._ws.addEventListener("message", (event) => { + messageWrap(() => { + const eventData = event.data; + let parsedJson; + try { + parsedJson = JSON.parse(eventData); + } catch (e) { + this._progress?.log(` Closing websocket due to malformed JSON. eventData=${eventData} e=${e?.message}`); + this._ws.close(); + return; + } + try { + if (this.onmessage) + this.onmessage.call(null, parsedJson); + } catch (e) { + this._progress?.log(` Closing websocket due to failed onmessage callback. eventData=${eventData} e=${e?.message}`); + this._ws.close(); + } + }); + }); + this._ws.addEventListener("close", (event) => { + this._progress?.log(` ${logUrl} code=${event.code} reason=${event.reason}`); + if (this.onclose) + this.onclose.call(null, event.reason); + }); + this._ws.addEventListener("error", (error) => this._progress?.log(` ${logUrl} ${error.type} ${error.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?.log(` ${logUrl}`); + const transport = new _WebSocketTransport(progress2, url2, logUrl, { ...options2, followRedirects: !!options2.followRedirects && hadRedirects }); + const resultPromise = new Promise((fulfill, reject) => { + transport._ws.on("open", async () => { + progress2?.log(` ${logUrl}`); + fulfill({}); + }); + transport._ws.on("error", (event) => { + 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?.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 error = chunks.length ? `${errorPrefix} +${Buffer.concat(chunks)}` : errorPrefix; + progress2?.log(` ${error}`); + reject(new Error("WebSocket error: " + error)); + transport._ws.close(); + }); + }); + }); + try { + const result2 = progress2 ? await progress2.race(resultPromise) : await resultPromise; + if (result2.redirect) { + const newHeaders = Object.fromEntries(Object.entries(options2.headers || {}).filter(([name]) => { + return !name.includes("access-key") && name.toLowerCase() !== "authorization"; + })); + return _WebSocketTransport._connect( + progress2, + result2.redirect.headers.location, + { ...options2, headers: newHeaders }, + true + /* hadRedirects */ + ); + } + return transport; + } catch (error) { + await transport.closeAndWait(); + throw error; + } + } + send(message) { + this._ws.send(JSON.stringify(message)); + } + close() { + this._progress?.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; + } + }; + } +}); + +// packages/playwright-core/src/server/browserType.ts +function copyTestHooks(from, to) { + for (const [key, value2] of Object.entries(from)) { + if (key.startsWith("__testHook")) + to[key] = value2; + } +} +var import_fs25, import_os10, import_path24, kNoXServerRunningError, BrowserType; +var init_browserType = __esm({ + "packages/playwright-core/src/server/browserType.ts"() { + "use strict"; + import_fs25 = __toESM(require("fs")); + import_os10 = __toESM(require("os")); + import_path24 = __toESM(require("path")); + init_assert(); + init_manualPromise(); + init_time(); + init_debug(); + init_fileUtils(); + init_processLauncher(); + init_debugLogger(); + init_browserContext(); + init_helper(); + init_instrumentation(); + init_pipeTransport2(); + init_protocolError(); + init_registry(); + init_socksClientCertificatesInterceptor(); + init_transport(); + 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"; + BrowserType = class extends SdkObject { + constructor(parent, browserName) { + super(parent, "browser-type"); + this.attribution.browserType = this; + this._name = browserName; + this.logName = "browser"; + } + executablePath() { + return registry.findExecutable(this._name).executablePath() || ""; + } + name() { + return this._name; + } + async launch(progress2, options2, protocolLogger) { + options2 = this._validateLaunchOptions(options2); + const seleniumHubUrl = options2.__testHookSeleniumRemoteURL || process.env.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); + }); + } + async launchPersistentContext(progress2, userDataDir, options2) { + const launchOptions = this._validateLaunchOptions(options2); + let clientCertificatesProxy; + if (options2.clientCertificates?.length) { + clientCertificatesProxy = await ClientCertificatesProxy.create(progress2, options2); + launchOptions.proxyOverride = clientCertificatesProxy.proxySettings(); + options2 = { ...options2 }; + options2.internalIgnoreHTTPSErrors = true; + } + try { + const browser = await this._innerLaunchWithRetries(progress2, launchOptions, options2, helper.debugProtocolLogger(), userDataDir).catch((e) => { + throw this._rewriteStartupLog(e); + }); + browser._defaultContext._clientCertificatesProxy = clientCertificatesProxy; + return browser._defaultContext; + } catch (error) { + await clientCertificatesProxy?.close().catch(() => { + }); + throw error; + } + } + async _innerLaunchWithRetries(progress2, options2, persistent, protocolLogger, userDataDir) { + try { + return await this._innerLaunch(progress2, options2, persistent, protocolLogger, userDataDir); + } catch (error) { + const errorMessage = typeof error === "object" && typeof error.message === "string" ? error.message : ""; + if (errorMessage.includes("Inconsistency detected by ld.so")) { + progress2.log(``); + return this._innerLaunch(progress2, options2, persistent, protocolLogger, userDataDir); + } + throw error; + } + } + 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, wsEndpoint } = await this._launchProcess(progress2, options2, !!persistent, browserLogsCollector, maybeUserDataDir); + try { + if (options2.__testHookBeforeCreateBrowser) + await progress2.race(options2.__testHookBeforeCreateBrowser()); + const browserOptions = { + name: this._name, + browserType: this._name, + 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, + originalLaunchOptions: options2, + userDataDir: persistent ? userDataDir : void 0 + }; + if (persistent) + validateBrowserContextOptions(persistent, browserOptions); + copyTestHooks(options2, browserOptions); + const browser = await progress2.race(this.connectToTransport(transport, browserOptions, browserLogsCollector)); + browser._userDataDirForTest = userDataDir; + if (persistent && !options2.ignoreAllDefaultArgs) + await browser._defaultContext.loadDefaultContext(progress2); + return browser; + } catch (error) { + await progress2.race(browserProcess.close().catch(() => { + })); + throw error; + } + } + async _prepareToLaunch(options2, isPersistent, userDataDir) { + const { + ignoreDefaultArgs, + ignoreAllDefaultArgs, + args = [], + executablePath = null + } = options2; + const tempDirectories = []; + let artifactsDir; + if (options2.artifactsDir) { + artifactsDir = options2.artifactsDir; + } else { + artifactsDir = await import_fs25.default.promises.mkdtemp(import_path24.default.join(import_os10.default.tmpdir(), "playwright-artifacts-")); + tempDirectories.push(artifactsDir); + } + if (userDataDir) { + assert(import_path24.default.isAbsolute(userDataDir), "userDataDir must be an absolute path"); + if (!await existsAsync(userDataDir)) + await import_fs25.default.promises.mkdir(userDataDir, { recursive: true, mode: 448 }); + } else { + userDataDir = await import_fs25.default.promises.mkdtemp(import_path24.default.join(import_os10.default.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(...(await this.defaultArgs(options2, isPersistent, userDataDir)).filter((arg) => ignoreDefaultArgs.indexOf(arg) === -1)); + else + browserArguments.push(...await 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); + } + return { executable, browserArguments, userDataDir, artifactsDir, tempDirectories }; + } + async _launchProcess(progress2, options2, isPersistent, browserLogsCollector, userDataDir) { + const { + handleSIGINT = true, + handleSIGTERM = true, + handleSIGHUP = true + } = options2; + const env = options2.env ? envArrayToObject(options2.env) : process.env; + const prepared = await progress2.race(this._prepareToLaunch(options2, isPersistent, userDataDir)); + let transport = void 0; + let browserProcess = void 0; + const exitPromise = new ManualPromise(); + const { launchedProcess, gracefullyClose, kill } = await progress2.race(launchProcess({ + command: prepared.executable, + args: prepared.browserArguments, + env: this.amendEnvironment(env, prepared.userDataDir, isPersistent, options2), + handleSIGINT, + handleSIGTERM, + handleSIGHUP, + log: (message) => { + progress2.log(message); + browserLogsCollector.log(message); + }, + stdio: "pipe", + tempDirectories: prepared.tempDirectories, + attemptToGracefullyClose: async () => { + if (options2.__testHookGracefullyClose) + await options2.__testHookGracefullyClose(); + if (transport) { + this.attemptToGracefullyCloseBrowser(transport); + } else { + throw new Error("Force-killing the browser because no transport is available to gracefully close it."); + } + }, + onExit: (exitCode, signal) => { + exitPromise.resolve(); + 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 + }; + try { + const { wsEndpoint } = await progress2.race([ + this.waitForReadyState(options2, browserLogsCollector), + exitPromise.then(() => ({ wsEndpoint: void 0 })) + ]); + if (exitPromise.isDone()) { + const log2 = helper.formatBrowserLogs(browserLogsCollector.recentLogs()); + const updatedLog = this.doRewriteStartupLog(log2); + throw new Error(`Failed to launch the browser process. +Browser logs: +${updatedLog}`); + } + if (!this.supportsPipeTransport()) { + transport = await WebSocketTransport.connect(progress2, wsEndpoint); + } else { + const stdio = launchedProcess.stdio; + transport = new PipeTransport2(stdio[3], stdio[4]); + } + return { browserProcess, artifactsDir: prepared.artifactsDir, userDataDir: prepared.userDataDir, transport, wsEndpoint }; + } catch (error) { + await progress2.race(closeOrKill(DEFAULT_PLAYWRIGHT_TIMEOUT).catch(() => { + })); + throw error; + } + } + async connectOverCDP(progress2, endpointURL, options2) { + throw new Error("CDP connections are only supported by Chromium"); + } + async connectToWorker(progress2, endpoint) { + 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) { + let { headless = true, downloadsPath, proxy } = options2; + if (debugMode() === "inspector") + headless = false; + if (downloadsPath && !import_path24.default.isAbsolute(downloadsPath)) + downloadsPath = import_path24.default.join(process.cwd(), downloadsPath); + if (options2.socksProxyPort) + proxy = { server: `socks5://127.0.0.1:${options2.socksProxyPort}` }; + return { ...options2, 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(error) { + if (!isProtocolError(error)) + return error; + if (error.logs) + error.logs = this.doRewriteStartupLog(error.logs); + return error; + } + async waitForReadyState(options2, browserLogsCollector) { + return {}; + } + async prepareUserDataDir(options2, userDataDir) { + } + supportsPipeTransport() { + return true; + } + getExecutableName(options2) { + return options2.channel || this._name; + } + }; + } +}); + +// packages/playwright-core/src/server/bidi/bidiConnection.ts +var import_events9, kBrowserCloseMessageId2, kShutdownSessionNewMessageId, BidiConnection, BidiSession; +var init_bidiConnection = __esm({ + "packages/playwright-core/src/server/bidi/bidiConnection.ts"() { + "use strict"; + import_events9 = require("events"); + init_debugLogger(); + init_helper(); + init_protocolError(); + kBrowserCloseMessageId2 = Number.MAX_SAFE_INTEGER - 1; + kShutdownSessionNewMessageId = kBrowserCloseMessageId2 - 1; + BidiConnection = class { + constructor(transport, onDisconnect, protocolLogger, browserLogsCollector) { + this._lastId = 0; + this._closed = false; + this._browsingContextToSession = /* @__PURE__ */ new Map(); + this._realmToBrowsingContext = /* @__PURE__ */ new Map(); + // TODO: shared/service workers might have multiple owner realms. + this._realmToOwnerRealm = /* @__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) { + this._protocolLogger("receive", message); + const object = message; + if (object.type === "event") { + if (object.method === "script.realmCreated") { + if ("context" in object.params) + this._realmToBrowsingContext.set(object.params.realm, object.params.context); + if (object.params.type === "dedicated-worker") + this._realmToOwnerRealm.set(object.params.realm, object.params.owners[0]); + } else if (object.method === "script.realmDestroyed") { + this._realmToBrowsingContext.delete(object.params.realm); + this._realmToOwnerRealm.delete(object.params.realm); + } + let context2; + let realm; + if ("context" in object.params) { + context2 = object.params.context; + } else if (object.method === "log.entryAdded" || object.method === "script.message") { + context2 = object.params.source?.context; + realm = object.params.source?.realm; + } else if (object.method === "script.realmCreated" && object.params.type === "dedicated-worker") { + realm = object.params.owners[0]; + } + if (!context2 && realm) { + while (this._realmToOwnerRealm.get(realm)) + realm = this._realmToOwnerRealm.get(realm); + context2 = this._realmToBrowsingContext.get(realm); + } + if (context2) { + const session2 = this._browsingContextToSession.get(context2); + if (session2) { + session2.dispatchMessage(message); + return; + } + } + } else if (message.id) { + for (const session2 of this._browsingContextToSession.values()) { + if (session2.hasCallback(message.id)) { + session2.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 result2 = new BidiSession(this, bowsingContextId, (message) => this.rawSend(message)); + this._browsingContextToSession.set(bowsingContextId, result2); + return result2; + } + }; + BidiSession = class extends import_events9.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(context2) { + this._browsingContexts.add(context2); + this.connection._browsingContextToSession.set(context2, this); + } + removeFrameBrowsingContext(context2) { + this._browsingContexts.delete(context2); + this.connection._browsingContextToSession.delete(context2); + } + async send(method, params2) { + 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: params2 }; + this._rawSend(messageObj); + return new Promise((resolve, reject) => { + this._callbacks.set(id, { resolve, reject, error: new ProtocolError("error", method) }); + }); + } + sendMayFail(method, params2) { + return this.send(method, params2).catch((error) => debugLogger.log("error", error)); + } + markAsCrashed() { + this._crashed = true; + } + isDisposed() { + return this._disposed; + } + dispose() { + this._disposed = true; + this.connection._browsingContextToSession.delete(this.sessionId); + for (const context2 of this._browsingContexts) + this.connection._browsingContextToSession.delete(context2); + this._browsingContexts.clear(); + for (const callback of this._callbacks.values()) { + callback.error.type = this._crashed ? "crashed" : "closed"; + callback.error.setMessage(`Internal server error, session ${callback.error.type}.`); + 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 === kBrowserCloseMessageId2 || object.id === kShutdownSessionNewMessageId) + 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)); + } + } + }; + } +}); + +// packages/playwright-core/src/server/bidi/third_party/bidiProtocolCore.ts +var Session, BrowsingContext, Emulation, Network, Script, Log, Input; +var init_bidiProtocolCore = __esm({ + "packages/playwright-core/src/server/bidi/third_party/bidiProtocolCore.ts"() { + "use strict"; + ((Session3) => { + let UserPromptHandlerType; + ((UserPromptHandlerType2) => { + UserPromptHandlerType2["Accept"] = "accept"; + UserPromptHandlerType2["Dismiss"] = "dismiss"; + UserPromptHandlerType2["Ignore"] = "ignore"; + })(UserPromptHandlerType = Session3.UserPromptHandlerType || (Session3.UserPromptHandlerType = {})); + })(Session || (Session = {})); + ((BrowsingContext2) => { + let ReadinessState; + ((ReadinessState2) => { + ReadinessState2["None"] = "none"; + ReadinessState2["Interactive"] = "interactive"; + ReadinessState2["Complete"] = "complete"; + })(ReadinessState = BrowsingContext2.ReadinessState || (BrowsingContext2.ReadinessState = {})); + })(BrowsingContext || (BrowsingContext = {})); + ((BrowsingContext2) => { + let UserPromptType; + ((UserPromptType2) => { + UserPromptType2["Alert"] = "alert"; + UserPromptType2["Beforeunload"] = "beforeunload"; + UserPromptType2["Confirm"] = "confirm"; + UserPromptType2["Prompt"] = "prompt"; + })(UserPromptType = BrowsingContext2.UserPromptType || (BrowsingContext2.UserPromptType = {})); + })(BrowsingContext || (BrowsingContext = {})); + ((BrowsingContext2) => { + let CreateType; + ((CreateType2) => { + CreateType2["Tab"] = "tab"; + CreateType2["Window"] = "window"; + })(CreateType = BrowsingContext2.CreateType || (BrowsingContext2.CreateType = {})); + })(BrowsingContext || (BrowsingContext = {})); + ((Emulation2) => { + let ForcedColorsModeTheme; + ((ForcedColorsModeTheme2) => { + ForcedColorsModeTheme2["Light"] = "light"; + ForcedColorsModeTheme2["Dark"] = "dark"; + })(ForcedColorsModeTheme = Emulation2.ForcedColorsModeTheme || (Emulation2.ForcedColorsModeTheme = {})); + })(Emulation || (Emulation = {})); + ((Emulation2) => { + let ScreenOrientationNatural; + ((ScreenOrientationNatural2) => { + ScreenOrientationNatural2["Portrait"] = "portrait"; + ScreenOrientationNatural2["Landscape"] = "landscape"; + })(ScreenOrientationNatural = Emulation2.ScreenOrientationNatural || (Emulation2.ScreenOrientationNatural = {})); + })(Emulation || (Emulation = {})); + ((Network3) => { + let CollectorType; + ((CollectorType2) => { + CollectorType2["Blob"] = "blob"; + })(CollectorType = Network3.CollectorType || (Network3.CollectorType = {})); + })(Network || (Network = {})); + ((Network3) => { + let SameSite; + ((SameSite2) => { + SameSite2["Strict"] = "strict"; + SameSite2["Lax"] = "lax"; + SameSite2["None"] = "none"; + SameSite2["Default"] = "default"; + })(SameSite = Network3.SameSite || (Network3.SameSite = {})); + })(Network || (Network = {})); + ((Network3) => { + let DataType; + ((DataType2) => { + DataType2["Request"] = "request"; + DataType2["Response"] = "response"; + })(DataType = Network3.DataType || (Network3.DataType = {})); + })(Network || (Network = {})); + ((Network3) => { + let InterceptPhase; + ((InterceptPhase2) => { + InterceptPhase2["BeforeRequestSent"] = "beforeRequestSent"; + InterceptPhase2["ResponseStarted"] = "responseStarted"; + InterceptPhase2["AuthRequired"] = "authRequired"; + })(InterceptPhase = Network3.InterceptPhase || (Network3.InterceptPhase = {})); + })(Network || (Network = {})); + ((Script2) => { + let ResultOwnership; + ((ResultOwnership2) => { + ResultOwnership2["Root"] = "root"; + ResultOwnership2["None"] = "none"; + })(ResultOwnership = Script2.ResultOwnership || (Script2.ResultOwnership = {})); + })(Script || (Script = {})); + ((Log2) => { + let Level; + ((Level2) => { + Level2["Debug"] = "debug"; + Level2["Info"] = "info"; + Level2["Warn"] = "warn"; + Level2["Error"] = "error"; + })(Level = Log2.Level || (Log2.Level = {})); + })(Log || (Log = {})); + ((Input2) => { + let PointerType; + ((PointerType2) => { + PointerType2["Mouse"] = "mouse"; + PointerType2["Pen"] = "pen"; + PointerType2["Touch"] = "touch"; + })(PointerType = Input2.PointerType || (Input2.PointerType = {})); + })(Input || (Input = {})); + } +}); + +// packages/playwright-core/src/server/bidi/third_party/bidiProtocolPermissions.ts +var Permissions; +var init_bidiProtocolPermissions = __esm({ + "packages/playwright-core/src/server/bidi/third_party/bidiProtocolPermissions.ts"() { + "use strict"; + ((Permissions2) => { + let PermissionState; + ((PermissionState2) => { + PermissionState2["Granted"] = "granted"; + PermissionState2["Denied"] = "denied"; + PermissionState2["Prompt"] = "prompt"; + })(PermissionState = Permissions2.PermissionState || (Permissions2.PermissionState = {})); + })(Permissions || (Permissions = {})); + } +}); + +// packages/playwright-core/src/server/bidi/third_party/bidiProtocol.ts +var init_bidiProtocol = __esm({ + "packages/playwright-core/src/server/bidi/third_party/bidiProtocol.ts"() { + "use strict"; + init_bidiProtocolCore(); + init_bidiProtocolPermissions(); + } +}); + +// packages/playwright-core/src/server/bidi/bidiNetworkManager.ts +function fromBidiHeaders(bidiHeaders) { + const result2 = []; + for (const { name, value: value2 } of bidiHeaders) + result2.push({ name, value: bidiBytesValueToString(value2) }); + return result2; +} +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(c.sameSite) + }; + }); + return { cookies, headers: toBidiHeaders(otherHeaders) }; +} +function toBidiHeaders(headers) { + return headers.map(({ name, value: value2 }) => ({ name, value: { type: "string", value: value2 } })); +} +function bidiBytesValueToString(value2) { + if (value2.type === "string") + return value2.value; + if (value2.type === "base64") + return Buffer.from(value2.type, "base64").toString("binary"); + return "unknown value type: " + value2.type; +} +function toBidiSameSite(sameSite) { + if (!sameSite) + return void 0; + if (sameSite === "Strict") + return Network.SameSite.Strict; + if (sameSite === "Lax") + return Network.SameSite.Lax; + return Network.SameSite.None; +} +function resourceTypeFromBidi(requestDestination, requestInitiatorType, eventInitiatorType) { + switch (requestDestination) { + case "audio": + return "media"; + case "audioworklet": + return "script"; + case "document": + return "document"; + case "font": + return "font"; + case "frame": + return "document"; + case "iframe": + return "document"; + case "image": + return "image"; + case "object": + return "other"; + case "paintworklet": + return "script"; + case "script": + return "script"; + case "serviceworker": + return "script"; + case "sharedworker": + return "script"; + case "style": + return "stylesheet"; + case "track": + return "texttrack"; + case "video": + return "media"; + case "worker": + return "script"; + case "": + switch (requestInitiatorType) { + case "fetch": + return "fetch"; + case "font": + return "font"; + case "xmlhttprequest": + return "xhr"; + case null: + return eventInitiatorType === "script" ? "xhr" : "document"; + default: + return "other"; + } + default: + return "other"; + } +} +var REQUEST_BODY_HEADERS, BidiNetworkManager, BidiRequest, BidiRouteImpl; +var init_bidiNetworkManager = __esm({ + "packages/playwright-core/src/server/bidi/bidiNetworkManager.ts"() { + "use strict"; + init_eventsHelper(); + init_cookieStore(); + init_network2(); + init_bidiProtocol(); + REQUEST_BODY_HEADERS = /* @__PURE__ */ new Set(["content-encoding", "content-language", "content-location", "content-type"]); + BidiNetworkManager = class { + constructor(bidiSession, page) { + this._userRequestInterceptionEnabled = false; + this._protocolRequestInterceptionEnabled = false; + this._attemptedAuthentications = /* @__PURE__ */ new Set(); + this._session = bidiSession; + this._requests = /* @__PURE__ */ new Map(); + this._page = page; + 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) { + 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._deleteRequest(redirectedFrom._id); + if (param.request.method === "OPTIONS") { + const requestHeaders = Object.fromEntries(param.request.headers.map((h) => [h.name.toLowerCase(), bidiBytesValueToString(h.value)])); + if (param.initiator?.type === "preflight" || requestHeaders["access-control-request-method"]) { + if (param.intercepts) { + const responseHeaders = [ + { name: "Access-Control-Allow-Origin", value: requestHeaders["origin"] || "*" }, + { name: "Access-Control-Allow-Methods", value: requestHeaders["access-control-request-method"] }, + { 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"] }); + this._session.sendMayFail("network.provideResponse", { + request: param.request.request, + statusCode: 204, + headers: toBidiHeaders(responseHeaders) + }); + } + return; + } + } + let route2; + let headersOverride; + if (param.intercepts) { + if (redirectedFrom) { + let params2 = {}; + if (redirectedFrom._originalRequestRoute?._alreadyContinuedHeaders) { + const originalHeaders = fromBidiHeaders(param.request.headers); + headersOverride = applyHeadersOverrides(originalHeaders, redirectedFrom._originalRequestRoute._alreadyContinuedHeaders); + if (redirectedFrom.request.method() === "POST" && param.request.method === "GET") + headersOverride = headersOverride.filter(({ name }) => !REQUEST_BODY_HEADERS.has(name.toLowerCase())); + params2 = toBidiRequestHeaders(headersOverride); + } + this._session.sendMayFail("network.continueRequest", { + request: param.request.request, + ...params2 + }); + } else { + route2 = new BidiRouteImpl(this._session, param.request.request); + } + } + const request2 = new BidiRequest(frame, redirectedFrom, param, route2, headersOverride); + this._requests.set(request2._id, request2); + this._page.frameManager.requestStarted(request2.request, route2); + } + _onResponseStarted(params2) { + const request2 = this._requests.get(params2.request.request); + if (!request2) + return; + const getResponseBody = async () => { + const { bytes } = await this._session.send("network.getData", { request: params2.request.request, dataType: Network.DataType.Response }); + const encoding = bytes.type === "base64" ? "base64" : "utf8"; + return Buffer.from(bytes.value, encoding); + }; + const timings = params2.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 Response2(request2.request, params2.response.status, params2.response.statusText, fromBidiHeaders(params2.response.headers), timing, getResponseBody, false); + response2._serverAddrFinished(); + response2._securityDetailsFinished(); + response2._setHttpVersion(params2.response.protocol); + response2.setRawResponseHeaders(null); + response2.setResponseHeadersSize(params2.response.headersSize); + this._page.frameManager.requestReceivedResponse(response2); + } + _onResponseCompleted(params2) { + const request2 = this._requests.get(params2.request.request); + if (!request2) + return; + const response2 = request2.request._existingResponse(); + response2.setTransferSize(params2.response.bodySize); + response2.setEncodedBodySize(params2.response.bodySize); + const isRedirected = response2.status() >= 300 && response2.status() <= 399; + const responseEndTime = params2.request.timings.responseEnd - response2.timing().startTime; + if (isRedirected) { + response2._requestFinished(responseEndTime); + } else { + this._deleteRequest(request2._id); + response2._requestFinished(responseEndTime); + } + this._page.frameManager.reportRequestFinished(request2.request, response2); + } + _onFetchError(params2) { + const request2 = this._requests.get(params2.request.request); + if (!request2) + return; + this._deleteRequest(request2._id); + const response2 = request2.request._existingResponse(); + if (response2) { + response2.setTransferSize(null); + response2.setEncodedBodySize(null); + response2._requestFinished(-1); + } + request2.request._setFailureText(params2.errorText); + this._page.frameManager.requestFailed(request2.request, params2.errorText === "NS_BINDING_ABORTED"); + } + _onAuthRequired(params2) { + const isBasic = params2.response.authChallenges?.some((challenge) => challenge.scheme.startsWith("Basic")); + const credentials = this._page.browserContext._options.httpCredentials; + if (isBasic && credentials && (!credentials.origin || new URL(params2.request.url).origin.toLowerCase() === credentials.origin.toLowerCase())) { + if (this._attemptedAuthentications.has(params2.request.request)) { + this._session.sendMayFail("network.continueWithAuth", { + request: params2.request.request, + action: "cancel" + }); + } else { + this._attemptedAuthentications.add(params2.request.request); + this._session.sendMayFail("network.continueWithAuth", { + request: params2.request.request, + action: "provideCredentials", + credentials: { + type: "password", + username: credentials.username, + password: credentials.password + } + }); + } + } else { + this._session.sendMayFail("network.continueWithAuth", { + request: params2.request.request, + action: "cancel" + }); + } + } + _deleteRequest(requestId) { + this._requests.delete(requestId); + this._attemptedAuthentications.delete(requestId); + } + async setRequestInterception(value2) { + this._userRequestInterceptionEnabled = value2; + 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 contexts = [this._page.delegate._session.sessionId]; + const cachePromise = this._session.send("network.setCacheBehavior", { cacheBehavior: enabled ? "bypass" : "default", contexts }); + let interceptPromise = Promise.resolve(void 0); + if (enabled) { + interceptPromise = this._session.send("network.addIntercept", { + phases: [Network.InterceptPhase.BeforeRequestSent], + contexts + }).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]); + } + }; + BidiRequest = class { + constructor(frame, redirectedFrom, payload, route2, headersOverride) { + this._id = payload.request.request; + if (redirectedFrom) + redirectedFrom._redirectedTo = this; + const postDataBuffer = null; + this.request = new Request( + frame._page.browserContext, + frame, + null, + redirectedFrom ? redirectedFrom.request : null, + payload.navigation ?? void 0, + payload.request.url, + resourceTypeFromBidi(payload.request.destination, payload.request.initiatorType, payload.initiator?.type), + payload.request.method, + postDataBuffer, + headersOverride || fromBidiHeaders(payload.request.headers) + ); + this.request.setRawRequestHeaders(null); + this.request._setBodySize(payload.request.bodySize || 0); + this._originalRequestRoute = route2 ?? redirectedFrom?._originalRequestRoute; + route2?._setRequest(this.request); + } + _finalRequest() { + let request2 = this; + while (request2._redirectedTo) + request2 = request2._redirectedTo; + return request2; + } + }; + BidiRouteImpl = class { + constructor(session2, requestId) { + this._session = session2; + 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"); + const headers = response2.headers.filter((h) => h.name.toLowerCase() !== "content-encoding"); + await this._session.sendMayFail("network.provideResponse", { + request: this._requestId, + statusCode: response2.status, + reasonPhrase: statusText(response2.status), + ...toBidiResponseHeaders(headers), + body: { type: "base64", value: base64body } + }); + } + async abort(errorCode) { + await this._session.sendMayFail("network.failRequest", { + request: this._requestId + }); + } + }; + } +}); + +// packages/playwright-core/src/server/bidi/third_party/bidiSerializer.ts +var UnserializableError, BidiSerializer, isPlainObject, isRegExp6, isDate3; +var init_bidiSerializer = __esm({ + "packages/playwright-core/src/server/bidi/third_party/bidiSerializer.ts"() { + "use strict"; + UnserializableError = class extends Error { + }; + BidiSerializer = 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 value2; + if (Object.is(arg, -0)) { + value2 = "-0"; + } else if (Object.is(arg, Infinity)) { + value2 = "Infinity"; + } else if (Object.is(arg, -Infinity)) { + value2 = "-Infinity"; + } else if (Object.is(arg, NaN)) { + value2 = "NaN"; + } else { + value2 = arg; + } + return { + type: "number", + value: value2 + }; + } + 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 (error) { + if (error instanceof TypeError && error.message.startsWith("Converting circular structure to JSON")) { + error.message += " Recursive objects are not allowed."; + } + throw error; + } + const parsedObject = []; + for (const key in arg) { + parsedObject.push([_BidiSerializer.serialize(key), _BidiSerializer.serialize(arg[key])]); + } + return { + type: "object", + value: parsedObject + }; + } else if (isRegExp6(arg)) { + return { + type: "regexp", + value: { + pattern: arg.source, + flags: arg.flags + } + }; + } else if (isDate3(arg)) { + return { + type: "date", + value: arg.toISOString() + }; + } + throw new UnserializableError( + "Custom object serialization not possible. Use plain objects instead." + ); + } + }; + isPlainObject = (obj) => { + return typeof obj === "object" && obj?.constructor === Object; + }; + isRegExp6 = (obj) => { + return typeof obj === "object" && obj?.constructor === RegExp; + }; + isDate3 = (obj) => { + return typeof obj === "object" && obj?.constructor === Date; + }; + } +}); + +// packages/playwright-core/src/server/bidi/bidiDeserializer.ts +function deserializeBidiValue(result2, internalIdMap = /* @__PURE__ */ new Map()) { + switch (result2.type) { + case "undefined": + return void 0; + case "null": + return null; + case "number": + return typeof result2.value === "number" ? result2.value : parseUnserializableValue(result2.value); + case "boolean": + return Boolean(result2.value); + case "string": + return result2.value; + case "bigint": + return BigInt(result2.value); + case "array": + return deserializeBidiList(result2, internalIdMap); + case "arraybuffer": + return getValue(result2, internalIdMap, () => ({})); + case "date": + return getValue(result2, internalIdMap, () => new Date(result2.value)); + case "error": + return getValue(result2, internalIdMap, () => { + const error = new Error(); + error.stack = ""; + return error; + }); + case "function": + return void 0; + case "generator": + return getValue(result2, internalIdMap, () => ({})); + case "htmlcollection": + return { ...deserializeBidiList(result2, internalIdMap) }; + case "map": + return getValue(result2, internalIdMap, () => ({})); + case "node": + return "ref: "; + case "nodelist": + return { ...deserializeBidiList(result2, internalIdMap) }; + case "object": + return deserializeBidiMapping(result2, internalIdMap); + case "promise": + return getValue(result2, internalIdMap, () => ({})); + case "proxy": + return getValue(result2, internalIdMap, () => ({})); + case "regexp": + return getValue(result2, internalIdMap, () => new RegExp(result2.value.pattern, result2.value.flags)); + case "set": + return getValue(result2, internalIdMap, () => ({})); + case "symbol": + return void 0; + case "typedarray": + return void 0; + case "weakmap": + return getValue(result2, internalIdMap, () => ({})); + case "weakset": + return getValue(result2, internalIdMap, () => ({})); + case "window": + return "ref: "; + } +} +function getValue(bidiValue, internalIdMap, defaultValue) { + if ("internalId" in bidiValue && bidiValue.internalId) { + if (internalIdMap.has(bidiValue.internalId)) { + return internalIdMap.get(bidiValue.internalId); + } else { + const value2 = defaultValue(); + internalIdMap.set(bidiValue.internalId, value2); + return value2; + } + } else { + return defaultValue(); + } +} +function deserializeBidiList(bidiValue, internalIdMap) { + const result2 = getValue(bidiValue, internalIdMap, () => []); + for (const val of bidiValue.value || []) + result2.push(deserializeBidiValue(val, internalIdMap)); + return result2; +} +function deserializeBidiMapping(bidiValue, internalIdMap) { + const result2 = getValue(bidiValue, internalIdMap, () => ({})); + for (const [serializedKey, serializedValue] of bidiValue.value || []) { + const key = typeof serializedKey === "string" ? serializedKey : deserializeBidiValue(serializedKey, internalIdMap); + const value2 = deserializeBidiValue(serializedValue, internalIdMap); + result2[key] = value2; + } + return result2; +} +var init_bidiDeserializer = __esm({ + "packages/playwright-core/src/server/bidi/bidiDeserializer.ts"() { + "use strict"; + init_javascript(); + } +}); + +// packages/playwright-core/src/server/bidi/bidiExecutionContext.ts +function rewriteError2(error) { + if (error.message.includes("too much recursion") || error.message.includes("stack limit exceeded")) + throw new Error("Cannot serialize result: object reference chain is too long."); + throw error; +} +function renderPreview2(remoteObject, nested = false) { + switch (remoteObject.type) { + case "undefined": + case "null": + return remoteObject.type; + case "number": + case "boolean": + case "string": + return String(remoteObject.value); + case "bigint": + return `${remoteObject.value}n`; + case "date": + return String(new Date(remoteObject.value)); + case "regexp": + return String(new RegExp(remoteObject.value.pattern, remoteObject.value.flags)); + case "node": + return remoteObject.value?.localName || "Node"; + case "object": + if (nested) + return "Object"; + const tokens = []; + for (const [name, value2] of remoteObject.value || []) { + if (typeof name === "string") + tokens.push(`${name}: ${renderPreview2(value2, true)}`); + } + return `{${tokens.join(", ")}}`; + case "array": + case "htmlcollection": + case "nodelist": + if (nested || !remoteObject.value) + return remoteObject.value ? `Array(${remoteObject.value.length})` : "Array"; + return `[${remoteObject.value.map((v) => renderPreview2(v, true)).join(", ")}]`; + case "map": + return remoteObject.value ? `Map(${remoteObject.value.length})` : "Map"; + case "set": + return remoteObject.value ? `Set(${remoteObject.value.length})` : "Set"; + case "arraybuffer": + return "ArrayBuffer"; + case "error": + return "Error"; + case "function": + return "Function"; + case "generator": + return "Generator"; + case "promise": + return "Promise"; + case "proxy": + return "Proxy"; + case "symbol": + return "Symbol()"; + case "typedarray": + return "TypedArray"; + case "weakmap": + return "WeakMap"; + case "weakset": + return "WeakSet"; + case "window": + return "Window"; + } +} +function createHandle2(context2, remoteObject) { + if (remoteObject.type === "node") { + assert(context2 instanceof FrameExecutionContext); + return new ElementHandle(context2, remoteObject.handle); + } + const objectId = "handle" in remoteObject ? remoteObject.handle : void 0; + const preview = renderPreview2(remoteObject); + const handle = new JSHandle(context2, remoteObject.type, preview, objectId, deserializeBidiValue(remoteObject)); + handle._setPreview(preview); + return handle; +} +var BidiExecutionContext; +var init_bidiExecutionContext = __esm({ + "packages/playwright-core/src/server/bidi/bidiExecutionContext.ts"() { + "use strict"; + init_utilityScriptSerializers(); + init_assert(); + init_javascript(); + init_dom(); + init_bidiProtocol(); + init_bidiSerializer(); + init_bidiDeserializer(); + BidiExecutionContext = class { + constructor(session2, realmInfo) { + this._session = session2; + if (realmInfo.type === "window") { + this._target = { + context: realmInfo.context, + sandbox: realmInfo.sandbox + }; + } else { + this._target = { + realm: realmInfo.realm + }; + } + } + async rawEvaluateJSON(expression2) { + const response2 = await this._session.send("script.evaluate", { + expression: expression2, + target: this._target, + serializationOptions: { + maxObjectDepth: 10, + maxDomDepth: 10 + }, + awaitPromise: true, + userActivation: true + }); + if (response2.type === "success") + return deserializeBidiValue(response2.result); + if (response2.type === "exception") + throw new JavaScriptErrorInEvaluate(response2.exceptionDetails.text); + throw new JavaScriptErrorInEvaluate("Unexpected response type: " + JSON.stringify(response2)); + } + async rawEvaluateHandle(context2, expression2) { + const response2 = await this._session.send("script.evaluate", { + expression: expression2, + 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 createHandle2(context2, response2.result); + throw new JavaScriptErrorInEvaluate("Cannot get handle: " + JSON.stringify(response2.result)); + } + if (response2.type === "exception") + throw new JavaScriptErrorInEvaluate(response2.exceptionDetails.text); + 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 + }).catch(rewriteError2); + if (response2.type === "exception") + throw new JavaScriptErrorInEvaluate(response2.exceptionDetails.text); + if (response2.type === "success") { + if (returnByValue) + return parseEvaluationResultValue(deserializeBidiValue(response2.result)); + return createHandle2(utilityScript._context, response2.result); + } + throw new JavaScriptErrorInEvaluate("Unexpected response type: " + JSON.stringify(response2)); + } + async getProperties(handle) { + const names = await handle.evaluate((object) => { + const names2 = []; + const descriptors = Object.getOwnPropertyDescriptors(object); + for (const name in descriptors) { + if (descriptors[name]?.enumerable) + names2.push(name); + } + return names2; + }); + const values = await Promise.all(names.map(async (name) => { + const value2 = await this._rawCallFunction("(object, name) => object[name]", [{ handle: handle._objectId }, { type: "string", value: name }], true, false); + return createHandle2(handle._context, value2); + })); + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < names.length; i++) + map.set(names[i], values[i]); + return map; + } + async releaseHandle(handle) { + if (!handle._objectId) + return; + await this._session.send("script.disown", { + target: this._target, + handles: [handle._objectId] + }); + } + shouldPrependErrorPrefix() { + return false; + } + 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(context2, nodeId) { + const result2 = await this._remoteValueForReference(nodeId, true); + if (!("handle" in result2)) + throw new Error("Can't get remote object for nodeId"); + return createHandle2(context2, result2); + } + async contentFrameIdForFrame(handle) { + const contentWindow = await this._rawCallFunction("e => e.contentWindow", [{ handle: handle._objectId }]); + if (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, createHandle5) { + return await this._rawCallFunction("e => e", [reference], createHandle5); + } + async _rawCallFunction(functionDeclaration, args, createHandle5, awaitPromise = true) { + const response2 = await this._session.send("script.callFunction", { + functionDeclaration, + target: this._target, + arguments: args, + // "Root" is necessary for the handle to be returned. + resultOwnership: createHandle5 ? Script.ResultOwnership.Root : Script.ResultOwnership.None, + serializationOptions: { maxObjectDepth: 0, maxDomDepth: 0 }, + awaitPromise, + userActivation: true + }); + if (response2.type === "exception") + throw new JavaScriptErrorInEvaluate(response2.exceptionDetails.text); + if (response2.type === "success") + return response2.result; + throw new JavaScriptErrorInEvaluate("Unexpected response type: " + JSON.stringify(response2)); + } + }; + } +}); + +// packages/playwright-core/src/server/bidi/third_party/bidiKeyboard.ts +var getBidiKeyValue; +var init_bidiKeyboard = __esm({ + "packages/playwright-core/src/server/bidi/third_party/bidiKeyboard.ts"() { + "use strict"; + getBidiKeyValue = (keyName) => { + switch (keyName) { + case "\r": + case "\n": + keyName = "Enter"; + break; + } + if ([...keyName].length === 1) { + return keyName; + } + switch (keyName) { + case "Cancel": + return "\uE001"; + case "Help": + return "\uE002"; + case "Backspace": + return "\uE003"; + case "Tab": + return "\uE004"; + case "Clear": + return "\uE005"; + case "Enter": + return "\uE007"; + case "Shift": + case "ShiftLeft": + return "\uE008"; + case "Control": + case "ControlLeft": + return "\uE009"; + case "Alt": + case "AltLeft": + return "\uE00A"; + case "Pause": + return "\uE00B"; + case "Escape": + return "\uE00C"; + case "PageUp": + return "\uE00E"; + case "PageDown": + return "\uE00F"; + case "End": + return "\uE010"; + case "Home": + return "\uE011"; + case "ArrowLeft": + return "\uE012"; + case "ArrowUp": + return "\uE013"; + case "ArrowRight": + return "\uE014"; + case "ArrowDown": + return "\uE015"; + case "Insert": + return "\uE016"; + case "Delete": + return "\uE017"; + case "NumpadEqual": + return "\uE019"; + case "Numpad0": + return "\uE01A"; + case "Numpad1": + return "\uE01B"; + case "Numpad2": + return "\uE01C"; + case "Numpad3": + return "\uE01D"; + case "Numpad4": + return "\uE01E"; + case "Numpad5": + return "\uE01F"; + case "Numpad6": + return "\uE020"; + case "Numpad7": + return "\uE021"; + case "Numpad8": + return "\uE022"; + case "Numpad9": + return "\uE023"; + case "NumpadMultiply": + return "\uE024"; + case "NumpadAdd": + return "\uE025"; + case "NumpadSubtract": + return "\uE027"; + case "NumpadDecimal": + return "\uE028"; + case "NumpadDivide": + return "\uE029"; + case "F1": + return "\uE031"; + case "F2": + return "\uE032"; + case "F3": + return "\uE033"; + case "F4": + return "\uE034"; + case "F5": + return "\uE035"; + case "F6": + return "\uE036"; + case "F7": + return "\uE037"; + case "F8": + return "\uE038"; + case "F9": + return "\uE039"; + case "F10": + return "\uE03A"; + case "F11": + return "\uE03B"; + case "F12": + return "\uE03C"; + case "Meta": + case "MetaLeft": + return "\uE03D"; + case "ShiftRight": + return "\uE050"; + case "ControlRight": + return "\uE051"; + case "AltRight": + return "\uE052"; + case "MetaRight": + return "\uE053"; + 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}"`); + } + }; + } +}); + +// packages/playwright-core/src/server/bidi/bidiInput.ts +function toBidiButton(button) { + switch (button) { + case "left": + return 0; + case "right": + return 2; + case "middle": + return 1; + } + throw new Error("Unknown button: " + button); +} +var RawKeyboardImpl2, RawMouseImpl2, RawTouchscreenImpl2; +var init_bidiInput = __esm({ + "packages/playwright-core/src/server/bidi/bidiInput.ts"() { + "use strict"; + init_input(); + init_bidiKeyboard(); + init_bidiProtocol(); + RawKeyboardImpl2 = class { + constructor(session2) { + this._session = session2; + } + setSession(session2) { + this._session = session2; + } + async keydown(progress2, modifiers, keyName, description, autoRepeat) { + keyName = resolveSmartModifierString(keyName); + const actions = []; + actions.push({ type: "keyDown", value: getBidiKeyValue(keyName) }); + await this._performActions(progress2, actions); + } + async keyup(progress2, modifiers, keyName, description) { + keyName = resolveSmartModifierString(keyName); + const actions = []; + actions.push({ type: "keyUp", value: getBidiKeyValue(keyName) }); + await this._performActions(progress2, actions); + } + async sendText(progress2, text2) { + const actions = []; + for (const char of text2) { + const value2 = getBidiKeyValue(char); + actions.push({ type: "keyDown", value: value2 }); + actions.push({ type: "keyUp", value: value2 }); + } + await this._performActions(progress2, actions); + } + async _performActions(progress2, actions) { + await progress2.race(this._session.send("input.performActions", { + context: this._session.sessionId, + actions: [ + { + type: "key", + id: "pw_keyboard", + actions + } + ] + })); + } + }; + RawMouseImpl2 = class { + constructor(session2) { + this._session = session2; + } + async move(progress2, x, y, button, buttons, modifiers, forClick) { + await this._performActions(progress2, [{ type: "pointerMove", x, y }]); + } + async down(progress2, x, y, button, buttons, modifiers, clickCount) { + await this._performActions(progress2, [{ type: "pointerDown", button: toBidiButton(button) }]); + } + async up(progress2, x, y, button, buttons, modifiers, clickCount) { + await this._performActions(progress2, [{ type: "pointerUp", button: toBidiButton(button) }]); + } + async wheel(progress2, x, y, buttons, modifiers, deltaX, deltaY) { + x = Math.floor(x); + y = Math.floor(y); + await progress2.race(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(progress2, actions) { + await progress2.race(this._session.send("input.performActions", { + context: this._session.sessionId, + actions: [ + { + type: "pointer", + id: "pw_mouse", + parameters: { + pointerType: Input.PointerType.Mouse + }, + actions + } + ] + })); + } + }; + RawTouchscreenImpl2 = class { + constructor(session2) { + this._session = session2; + } + async tap(progress2, x, y, modifiers) { + } + }; + } +}); + +// packages/playwright-core/src/server/bidi/bidiPdf.ts +function convertPrintParameterToInches2(text2) { + if (text2 === void 0) + return void 0; + let unit = text2.substring(text2.length - 2).toLowerCase(); + let valueText = ""; + if (unitToPixels2.hasOwnProperty(unit)) { + valueText = text2.substring(0, text2.length - 2); + } else { + unit = "px"; + valueText = text2; + } + const value2 = Number(valueText); + assert(!isNaN(value2), "Failed to parse parameter value: " + text2); + const pixels = value2 * unitToPixels2[unit]; + return pixels / 96; +} +var PagePaperFormats2, unitToPixels2, BidiPDF; +var init_bidiPdf = __esm({ + "packages/playwright-core/src/server/bidi/bidiPdf.ts"() { + "use strict"; + init_assert(); + PagePaperFormats2 = { + 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 } + }; + unitToPixels2 = { + "px": 1, + "in": 96, + "cm": 37.8, + "mm": 3.78 + }; + BidiPDF = class { + constructor(session2) { + this._session = session2; + } + async generate(options2) { + const { + scale = 1, + printBackground = false, + landscape = false, + pageRanges = "", + margin = {} + } = options2; + let paperWidth = 8.5; + let paperHeight = 11; + if (options2.format) { + const format2 = PagePaperFormats2[options2.format.toLowerCase()]; + assert(format2, "Unknown paper format: " + options2.format); + paperWidth = format2.width; + paperHeight = format2.height; + } else { + paperWidth = convertPrintParameterToInches2(options2.width) || paperWidth; + paperHeight = convertPrintParameterToInches2(options2.height) || paperHeight; + } + const { data } = await this._session.send("browsingContext.print", { + context: this._session.sessionId, + background: printBackground, + margin: { + bottom: convertPrintParameterToInches2(margin.bottom) || 0, + left: convertPrintParameterToInches2(margin.left) || 0, + right: convertPrintParameterToInches2(margin.right) || 0, + top: convertPrintParameterToInches2(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(data, "base64"); + } + }; + } +}); + +// packages/playwright-core/src/server/bidi/bidiPage.ts +function toBidiExecutionContext(executionContext) { + return executionContext.delegate; +} +var UTILITY_WORLD_NAME, kPlaywrightBindingChannel, BidiPage; +var init_bidiPage = __esm({ + "packages/playwright-core/src/server/bidi/bidiPage.ts"() { + "use strict"; + init_debugLogger(); + init_eventsHelper(); + init_dialog(); + init_dom(); + init_bidiBrowser(); + init_page(); + init_bidiExecutionContext(); + init_bidiInput(); + init_bidiNetworkManager(); + init_bidiPdf(); + init_bidiProtocol(); + init_progress(); + init_network2(); + UTILITY_WORLD_NAME = "__playwright_utility_world__"; + kPlaywrightBindingChannel = "playwrightChannel"; + BidiPage = class { + constructor(browserContext, bidiSession, opener) { + this._realmToWorkerContext = /* @__PURE__ */ new Map(); + this._sessionListeners = []; + this._initScriptIds = /* @__PURE__ */ new Map(); + this._fragmentNavigations = /* @__PURE__ */ new Set(); + this._session = bidiSession; + this._opener = opener; + this.rawKeyboard = new RawKeyboardImpl2(bidiSession); + this.rawMouse = new RawMouseImpl2(bidiSession); + this.rawTouchscreen = new RawTouchscreenImpl2(bidiSession); + this._contextIdToContext = /* @__PURE__ */ new Map(); + this._page = new Page(this, browserContext); + this._browserContext = browserContext; + this._networkManager = new BidiNetworkManager(this._session, this._page); + this._pdf = new BidiPDF(this._session); + this._page.on(Page.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.navigationCommitted", this._onNavigationCommitted.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.historyUpdated", this._onHistoryUpdated.bind(this)), + eventsHelper.addEventListener(bidiSession, "browsingContext.domContentLoaded", this._onDomContentLoaded.bind(this)), + eventsHelper.addEventListener(bidiSession, "browsingContext.load", this._onLoad.bind(this)), + eventsHelper.addEventListener(bidiSession, "browsingContext.downloadWillBegin", this._onDownloadWillBegin.bind(this)), + eventsHelper.addEventListener(bidiSession, "browsingContext.downloadEnd", this._onDownloadEnded.bind(this)), + eventsHelper.addEventListener(bidiSession, "browsingContext.userPromptOpened", this._onUserPromptOpened.bind(this)), + eventsHelper.addEventListener(bidiSession, "log.entryAdded", this._onLogEntryAdded.bind(this)), + eventsHelper.addEventListener(bidiSession, "input.fileDialogOpened", this._onFileDialogOpened.bind(this)) + ]; + this._initialize().then( + () => this._page.reportAsNew(this._opener?._page), + (error) => this._page.reportAsNew(this._opener?._page, error) + ); + } + async _initialize() { + this._onFrameAttached(this._session.sessionId, null); + await Promise.all([ + this.updateHttpCredentials() + // 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. + ]); + } + 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 [contextId4, context2] of this._contextIdToContext) { + if (context2.frame === frame) { + this._contextIdToContext.delete(contextId4); + if (notifyFrame) + frame.contextDestroyed(context2); + } + } + } + _onRealmCreated(realmInfo) { + if (realmInfo.type === "dedicated-worker") { + const delegate2 = new BidiExecutionContext(this._session, realmInfo); + const worker = new Worker(this._page, realmInfo.origin); + this._realmToWorkerContext.set(realmInfo.realm, worker.createExecutionContext(delegate2)); + worker.workerScriptLoaded(); + this._page.addWorker(realmInfo.realm, worker); + return; + } + if (this._contextIdToContext.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) { + worldName = "utility"; + } else { + return; + } + const delegate = new BidiExecutionContext(this._session, realmInfo); + const context2 = new FrameExecutionContext(delegate, frame, worldName); + frame.contextCreated(worldName, context2); + this._contextIdToContext.set(realmInfo.realm, context2); + } + async _touchUtilityWorld(context2) { + await this._session.sendMayFail("script.evaluate", { + expression: "1 + 1", + target: { + context: context2, + sandbox: UTILITY_WORLD_NAME + }, + serializationOptions: { + maxObjectDepth: 10, + maxDomDepth: 10 + }, + awaitPromise: true, + userActivation: true + }); + } + _onRealmDestroyed(params2) { + const context2 = this._contextIdToContext.get(params2.realm); + if (context2) { + this._contextIdToContext.delete(params2.realm); + context2.frame.contextDestroyed(context2); + return true; + } + const existed = this._realmToWorkerContext.delete(params2.realm); + if (existed) { + this._page.removeWorker(params2.realm); + return true; + } + return false; + } + // TODO: route the message directly to the browser + _onBrowsingContextDestroyed(params2) { + this._browserContext._browser._onBrowsingContextDestroyed(params2); + } + _onNavigationStarted(params2) { + const frameId = params2.context; + this._page.frameManager.frameRequestedNavigation(frameId, params2.navigation); + } + _onNavigationCommitted(params2) { + const frameId = params2.context; + const frame = this._page.frameManager.frame(frameId); + this._browserContext.doGrantGlobalPermissionsForURL(params2.url).catch((error) => debugLogger.log("error", error)); + this._page.frameManager.frameCommittedNewDocumentNavigation( + frameId, + params2.url, + frame._name, + params2.navigation, + /* initial */ + false + ); + } + _onDomContentLoaded(params2) { + const frameId = params2.context; + this._page.frameManager.frameLifecycleEvent(frameId, "domcontentloaded"); + } + _onLoad(params2) { + this._page.frameManager.frameLifecycleEvent(params2.context, "load"); + } + _onNavigationAborted(params2) { + this._page.frameManager.frameAbortedNavigation(params2.context, "Navigation aborted", params2.navigation || void 0); + } + _onNavigationFailed(params2) { + this._page.frameManager.frameAbortedNavigation(params2.context, "Navigation failed", params2.navigation || void 0); + } + _onFragmentNavigated(params2) { + if (params2.navigation) + this._fragmentNavigations.add(params2.navigation); + this._page.frameManager.frameCommittedSameDocumentNavigation(params2.context, params2.url); + } + _onHistoryUpdated(params2) { + this._page.frameManager.frameCommittedSameDocumentNavigation(params2.context, params2.url); + } + _onUserPromptOpened(event) { + this._page.browserContext.dialogManager.dialogDidOpen(new Dialog( + this._page, + event.type, + event.message, + async (accept, userText) => { + await this._session.send("browsingContext.handleUserPrompt", { context: event.context, accept, userText }); + }, + event.defaultValue + )); + } + _onDownloadWillBegin(event) { + if (!event.navigation) + return; + this._page.frameManager.frameAbortedNavigation(event.context, "Download is starting"); + let originPage = this._page.initializedOrUndefined(); + if (!originPage && this._opener) + originPage = this._opener._page.initializedOrUndefined(); + if (!originPage) + return; + this._browserContext._browser.downloadCreated(originPage, event.navigation, event.url, event.suggestedFilename); + } + _onDownloadEnded(event) { + if (!event.navigation) + return; + this._browserContext._browser.downloadFinished(event.navigation, event.status === "canceled" ? "canceled" : void 0); + } + _onLogEntryAdded(params2) { + if (params2.type === "javascript" && params2.level === "error") { + let errorName = ""; + let errorMessage; + if (params2.text?.includes(": ")) { + const index = params2.text.indexOf(": "); + errorName = params2.text.substring(0, index); + errorMessage = params2.text.substring(index + 2); + } else { + errorMessage = params2.text ?? void 0; + } + const error = new Error(errorMessage); + error.name = errorName; + error.stack = `${params2.text} +${params2.stackTrace?.callFrames.map((f) => { + const location4 = `${f.url}:${f.lineNumber + 1}:${f.columnNumber + 1}`; + return f.functionName ? ` at ${f.functionName} (${location4})` : ` at ${location4}`; + }).join("\n")}`; + const callFrame2 = params2.stackTrace?.callFrames[0]; + const location3 = callFrame2 ?? { url: "", lineNumber: 1, columnNumber: 1 }; + this._page.addPageError(error, location3); + return; + } + if (params2.type !== "console") + return; + const entry = params2; + const context2 = this._contextIdToContext.get(params2.source.realm) ?? this._realmToWorkerContext.get(params2.source.realm); + if (!context2) + return; + const callFrame = params2.stackTrace?.callFrames[0]; + const location2 = callFrame ?? { url: "", lineNumber: 1, columnNumber: 1 }; + const type3 = entry.method === "warn" ? "warning" : entry.method; + const text2 = (entry.method === "timeLog" || entry.method === "timeEnd") && entry.text ? entry.text : void 0; + this._page.addConsoleMessage(null, type3, entry.args.map((arg) => createHandle2(context2, arg)), location2, text2, params2.timestamp); + } + async _onFileDialogOpened(params2) { + if (!params2.element) + return; + const frame = this._page.frameManager.frame(params2.context); + if (!frame) + return; + const executionContext = await frame.mainContext(); + try { + const handle = await toBidiExecutionContext(executionContext).remoteObjectForNodeId(executionContext, { sharedId: params2.element.sharedId }); + await this._page._onFileChooserOpened(handle); + } catch { + } + } + async navigateFrame(frame, url2, referrer) { + const { navigation } = await this._session.send("browsingContext.navigate", { + context: frame._id, + url: url2 + }); + if (navigation && this._fragmentNavigations.has(navigation)) { + this._fragmentNavigations.delete(navigation); + return {}; + } + return { newDocumentId: navigation || void 0 }; + } + async updateExtraHTTPHeaders() { + const allHeaders = mergeHeaders([ + this._browserContext._options.extraHTTPHeaders, + this._page.extraHTTPHeaders() + ]); + await this._session.send("network.setExtraHeaders", { + headers: allHeaders.map(({ name, value: value2 }) => ({ name, value: { type: "string", value: value2 } })), + contexts: [this._session.sessionId] + }); + } + 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 screenSize = emulatedSize.screen; + const viewportSize = emulatedSize.viewport; + await Promise.all([ + this._session.send("browsingContext.setViewport", { + context: this._session.sessionId, + viewport: { + width: viewportSize.width, + height: viewportSize.height + }, + devicePixelRatio: options2.deviceScaleFactor || 1 + }), + this._session.send("emulation.setScreenOrientationOverride", { + contexts: [this._session.sessionId], + screenOrientation: getScreenOrientation(!!options2.isMobile, screenSize) + }), + this._session.send("emulation.setScreenSettingsOverride", { + contexts: [this._session.sessionId], + screenArea: { + width: screenSize.width, + height: screenSize.height + } + }) + ]); + } + async updateRequestInterception() { + await this._networkManager.setRequestInterception(this._page.requestInterceptors.length > 0); + } + 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() { + const result2 = await this._session.send("script.evaluate", { + expression: "TestUtils.gc()", + target: { context: this._session.sessionId }, + awaitPromise: true + }); + if (result2.type === "exception") + 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 context2 = this._contextIdToContext.get(event.source.realm); + if (!context2) + return; + if (event.data.type !== "string") + return; + await this._page.onBindingCalled(event.data.value, context2); + } + 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) { + if (runBeforeUnload) { + this._session.sendMayFail("browsingContext.close", { + context: this._session.sessionId, + promptUnload: runBeforeUnload + }); + } else { + await this._session.send("browsingContext.close", { + context: this._session.sessionId, + promptUnload: runBeforeUnload + }); + } + } + async setBackgroundColor(color) { + if (color) + throw new Error("Not implemented"); + } + async takeScreenshot(progress2, format2, documentRect, viewportRect, quality, fitsViewport, scale) { + const rect = documentRect || viewportRect; + const { data } = await progress2.race(this._session.send("browsingContext.captureScreenshot", { + context: this._session.sessionId, + format: { + type: `image/${format2 === "png" ? "png" : "jpeg"}`, + quality: quality !== void 0 ? quality / 100 : void 0 + }, + origin: documentRect ? "document" : "viewport", + clip: { + type: "box", + ...rect + } + })); + return Buffer.from(data, "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((node) => { + const doc = node.ownerDocument ?? node; + return doc.defaultView; + }); + if (!windowHandle) + return null; + const executionContext = toBidiExecutionContext(handle._context); + return executionContext.frameIdForWindowHandle(windowHandle); + } + async getBoundingBox(handle) { + const box = await handle.evaluate((element2) => { + if (!(element2 instanceof Element) || element2.getClientRects().length === 0) + return null; + const rect = element2.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 element2 = await frame.frameElement(nullProgress); + const box = await element2.boundingBox(nullProgress); + if (!box) + return null; + const style = await element2.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, node]) => { + node.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; + }); + } + startScreencast(options2) { + } + stopScreencast() { + } + rafCountForStablePosition() { + return 1; + } + async getContentQuads(handle) { + const quads = await handle.evaluateInUtility(([injected, node]) => { + if (!node.isConnected) + return "error:notconnected"; + const rects = node.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(progress2, handle, paths) { + const fromContext = toBidiExecutionContext(handle._context); + await progress2.race(this._session.send("input.setFiles", { + context: this._session.sessionId, + element: await progress2.race(fromContext.nodeIdForElementHandle(handle)), + files: paths + })); + } + async adoptElementHandle(handle, to) { + const fromContext = toBidiExecutionContext(handle._context); + const nodeId = await fromContext.nodeIdForElementHandle(handle); + const executionContext = toBidiExecutionContext(to); + try { + return await executionContext.remoteObjectForNodeId(to, nodeId); + } catch { + throw new Error(kUnableToAdoptErrorMessage); + } + } + async inputActionEpilogue() { + } + async resetForReuse(progress2) { + } + 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 node = await this._getFrameNode(frame); + if (!node?.sharedId) + throw new Error("Frame has been detached."); + const parentFrameExecutionContext = await parent.mainContext(); + return await toBidiExecutionContext(parentFrameExecutionContext).remoteObjectForNodeId(parentFrameExecutionContext, { sharedId: node.sharedId }); + } + async _getFrameNode(frame) { + const parent = frame.parentFrame(); + if (!parent) + return void 0; + const result2 = await this._session.send("browsingContext.locateNodes", { + context: parent._id, + locator: { type: "context", value: { context: frame._id } } + }); + const node = result2.nodes[0]; + return node; + } + shouldToggleStyleSheetToSyncAnimations() { + return true; + } + async setDockTile(image) { + } + }; + } +}); + +// packages/playwright-core/src/server/bidi/bidiBrowser.ts +function fromBidiSameSite(sameSite) { + switch (sameSite) { + case "strict": + return "Strict"; + case "lax": + return "Lax"; + case "none": + return "None"; + case "default": + return "Lax"; + } + return "None"; +} +function toBidiSameSite2(sameSite) { + switch (sameSite) { + case "Strict": + return Network.SameSite.Strict; + case "Lax": + return Network.SameSite.Lax; + case "None": + return Network.SameSite.None; + } + return Network.SameSite.None; +} +function getProxyConfiguration(proxySettings) { + if (!proxySettings) + return void 0; + const proxy = { + proxyType: "manual" + }; + const url2 = new URL(proxySettings.server); + switch (url2.protocol) { + case "http:": + proxy.httpProxy = url2.host; + break; + case "https:": + proxy.sslProxy = 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: " + proxySettings.server); + } + const bypass = proxySettings.bypass ?? process.env.PLAYWRIGHT_PROXY_BYPASS_FOR_TESTING; + if (bypass) + proxy.noProxy = bypass.split(","); + return proxy; +} +function getScreenOrientation(isMobile, viewportSize) { + const screenOrientation = { + type: "landscape-primary", + natural: Emulation.ScreenOrientationNatural.Landscape + }; + if (isMobile) { + screenOrientation.natural = Emulation.ScreenOrientationNatural.Portrait; + if (viewportSize.width <= viewportSize.height) + screenOrientation.type = "portrait-primary"; + } + return screenOrientation; +} +var BidiBrowser, BidiBrowserContext2, Network2; +var init_bidiBrowser = __esm({ + "packages/playwright-core/src/server/bidi/bidiBrowser.ts"() { + "use strict"; + init_eventsHelper(); + init_browser(); + init_browserContext(); + init_network2(); + init_bidiConnection(); + init_bidiNetworkManager(); + init_bidiPage(); + init_page(); + init_bidiProtocol(); + BidiBrowser = class _BidiBrowser extends Browser { + constructor(parent, transport, options2) { + super(parent, options2); + this._contexts = /* @__PURE__ */ new Map(); + this._bidiPages = /* @__PURE__ */ new Map(); + this._cacheBehavior = "default"; + 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 browser = new _BidiBrowser(parent, transport, options2); + if (options2.__testHookOnConnectToBrowser) + await options2.__testHookOnConnectToBrowser(); + browser._bidiSessionInfo = await browser._browserSession.send("session.new", { + capabilities: { + alwaysMatch: { + "acceptInsecureCerts": options2.persistent?.internalIgnoreHTTPSErrors || options2.persistent?.ignoreHTTPSErrors, + "proxy": getProxyConfiguration(options2.originalLaunchOptions.proxyOverride ?? options2.proxy), + "unhandledPromptBehavior": { + default: Session.UserPromptHandlerType.Ignore + }, + "webSocketUrl": true, + // Chrome with WebDriver BiDi does not support prerendering + // yet because WebDriver BiDi behavior is not specified. See + // https://github.com/w3c/webdriver-bidi/issues/321. + "goog:prerenderingDisabled": true + } + } + }); + await browser._browserSession.send("session.subscribe", { + events: [ + "browsingContext", + "network", + "log", + "script", + "input" + ] + }); + await browser._browserSession.send("network.addIntercept", { phases: [Network.InterceptPhase.AuthRequired] }); + await browser._browserSession.send("network.addDataCollector", { + dataTypes: [Network.DataType.Response], + maxEncodedDataSize: 2e7 + // same default as in CDP: https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/inspector/inspector_network_agent.cc;l=134;drc=4128411589187a396829a827f59a655bed876aa7 + }); + if (options2.persistent) { + const context2 = new BidiBrowserContext2(browser, void 0, options2.persistent); + browser._defaultContext = context2; + await context2.initialize(); + const page = await browser._defaultContext.doCreateNewPage(); + await page.waitForInitializedOrError(); + } + return browser; + } + _onDisconnect() { + this.didClose(); + } + async doCreateNewContext(options2) { + const proxy = options2.proxyOverride || options2.proxy; + const { userContext } = await this._browserSession.send("browser.createUserContext", { + acceptInsecureCerts: options2.internalIgnoreHTTPSErrors || options2.ignoreHTTPSErrors, + proxy: getProxyConfiguration(proxy) + }); + const context2 = new BidiBrowserContext2(this, userContext, options2); + await context2.initialize(); + this._contexts.set(userContext, context2); + return context2; + } + contexts() { + return Array.from(this._contexts.values()); + } + version() { + return this._bidiSessionInfo.capabilities.browserVersion; + } + userAgent() { + return this._bidiSessionInfo.capabilities.userAgent; + } + isConnected() { + return !this._connection.isClosed(); + } + async updateCacheBehavior() { + const cacheBehavior = [...this._contexts.values()].some((context2) => context2.requestInterceptors.length > 0) ? "bypass" : "default"; + if (this._cacheBehavior !== cacheBehavior) { + await this._browserSession.send("network.setCacheBehavior", { cacheBehavior }); + this._cacheBehavior = cacheBehavior; + } + } + _onBrowsingContextCreated(event) { + if (event.parent) { + const parentFrameId = event.parent; + const page2 = this._findPageForFrame(parentFrameId); + if (page2) { + page2._session.addFrameBrowsingContext(event.context); + const frame = page2._page.frameManager.frameAttached(event.context, parentFrameId); + frame._url = event.url; + page2._getFrameNode(frame).then((node) => { + const attributes = node?.value?.attributes; + frame._name = attributes?.name ?? attributes?.id ?? ""; + }, () => { + }); + return; + } + return; + } + let context2 = this._contexts.get(event.userContext); + if (!context2) + context2 = this._defaultContext; + if (!context2) + return; + context2.doGrantGlobalPermissionsForURL(event.url); + const session2 = this._connection.createMainFrameBrowsingContextSession(event.context); + const opener = event.originalOpener && this._findPageForFrame(event.originalOpener); + const page = new BidiPage(context2, session2, 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; + } + } + _findPageForFrame(frameId) { + for (const page of this._bidiPages.values()) { + if (page._page.frameManager.frame(frameId)) + return page; + } + } + }; + BidiBrowserContext2 = class extends BrowserContext { + constructor(browser, browserContextId, options2) { + super(browser, options2, browserContextId); + this._originToPermissions = /* @__PURE__ */ new Map(); + this._initScriptIds = /* @__PURE__ */ new Map(); + this.authenticateProxyViaHeader(); + } + _bidiPages() { + return [...this._browser._bidiPages.values()].filter((bidiPage) => bidiPage._browserContext === this); + } + async initialize() { + const promises = [ + super.initialize() + ]; + const downloadBehavior = this._options.acceptDownloads === "accept" ? { type: "allowed", destinationFolder: this._browser.options.downloadsPath } : { type: "denied" }; + promises.push(this._browser._browserSession.send("browser.setDownloadBehavior", { + downloadBehavior, + userContexts: [this._userContextId()] + })); + promises.push(this.doUpdateDefaultViewport()); + if (this._options.geolocation) + promises.push(this.setGeolocation(this._options.geolocation)); + if (this._options.locale) { + promises.push(this._browser._browserSession.send("emulation.setLocaleOverride", { + locale: this._options.locale, + userContexts: [this._userContextId()] + })); + } + if (this._options.timezoneId) { + promises.push(this._browser._browserSession.send("emulation.setTimezoneOverride", { + timezone: this._options.timezoneId, + userContexts: [this._userContextId()] + })); + } + if (this._options.userAgent) { + promises.push(this._browser._browserSession.send("emulation.setUserAgentOverride", { + userAgent: this._options.userAgent, + userContexts: [this._userContextId()] + })); + } + if (this._options.extraHTTPHeaders) + promises.push(this.doUpdateExtraHTTPHeaders()); + if (this._options.permissions) + promises.push(this.doGrantPermissions("*", this._options.permissions)); + if (this._options.offline) + promises.push(this.doUpdateOffline()); + await Promise.all(promises); + } + possiblyUninitializedPages() { + return this._bidiPages().map((bidiPage) => bidiPage._page); + } + async doCreateNewPage() { + const { context: context2 } = await this._browser._browserSession.send("browsingContext.create", { + type: BrowsingContext.CreateType.Window, + userContext: this._browserContextId + }); + return this._browser._bidiPages.get(context2)._page; + } + 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 promises = cookies.map(async (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 && toBidiSameSite2(c.sameSite), + expiry: c.expires === -1 || c.expires === void 0 ? void 0 : Math.round(c.expires) + }; + try { + return await this._browser._browserSession.send( + "storage.setCookie", + { cookie, partition: { type: "storageKey", userContext: this._browserContextId, sourceOrigin: c.partitionKey } } + ); + } catch (e) { + if (!e.message.startsWith("Protocol error (storage.setCookie): unable to set cookie")) + throw e; + } + }); + await Promise.all(promises); + } + async doClearCookies() { + await this._browser._browserSession.send( + "storage.deleteCookies", + { partition: { type: "storageKey", userContext: this._browserContextId } } + ); + } + async doGrantPermissions(origin, permissions) { + if (origin === "null") + return; + const currentPermissions = this._originToPermissions.get(origin) || []; + const toGrant = permissions.filter((permission) => !currentPermissions.includes(permission)); + this._originToPermissions.set(origin, [...currentPermissions, ...toGrant]); + if (origin === "*") { + await Promise.all(this._bidiPages().flatMap( + (page) => page._page.frames().map( + (frame) => this.doGrantPermissions(new URL(frame._url).origin, permissions) + ) + )); + } else { + await Promise.all(toGrant.map((permission) => this._setPermission(origin, permission, Permissions.PermissionState.Granted))); + } + } + async doGrantGlobalPermissionsForURL(url2) { + const permissions = this._originToPermissions.get("*"); + if (!permissions) + return; + await this.doGrantPermissions(new URL(url2).origin, permissions); + } + async doClearPermissions() { + const currentPermissions = [...this._originToPermissions.entries()]; + this._originToPermissions = /* @__PURE__ */ new Map(); + await Promise.all(currentPermissions.flatMap(([origin, permissions]) => { + if (origin !== "*") + return permissions.map((p) => this._setPermission(origin, p, Permissions.PermissionState.Prompt)); + })); + } + async _setPermission(origin, permission, state) { + await this._browser._browserSession.send("permissions.setPermission", { + descriptor: { + name: permission + }, + state, + origin, + userContext: this._userContextId() + }); + } + 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._userContextId()] + }); + } + async doUpdateExtraHTTPHeaders() { + const allHeaders = this._options.extraHTTPHeaders || []; + await this._browser._browserSession.send("network.setExtraHeaders", { + headers: allHeaders.map(({ name, value: value2 }) => ({ name, value: { type: "string", value: value2 } })), + userContexts: [this._userContextId()] + }); + } + async setUserAgent(userAgent) { + this._options.userAgent = userAgent; + await this._browser._browserSession.send("emulation.setUserAgentOverride", { + userAgent: userAgent ?? null, + userContexts: [this._userContextId()] + }); + } + async doUpdateOffline() { + await this._browser._browserSession.send("emulation.setNetworkConditions", { + networkConditions: this._options.offline ? { type: "offline" } : null, + userContexts: [this._userContextId()] + }); + } + 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._userContextId()] + }); + 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() { + let interceptPromise = Promise.resolve(void 0); + if (this.requestInterceptors.length > 0 && !this._interceptId) { + interceptPromise = this._browser._browserSession.send("network.addIntercept", { + phases: [Network.InterceptPhase.BeforeRequestSent] + }).then(({ intercept }) => this._interceptId = intercept); + } + if (this.requestInterceptors.length === 0 && this._interceptId) { + const intercept = this._interceptId; + this._interceptId = void 0; + interceptPromise = this._browser._browserSession.send("network.removeIntercept", { intercept }); + } + await Promise.all([this._browser.updateCacheBehavior(), interceptPromise]); + } + async doUpdateDefaultViewport() { + if (!this._options.viewport && !this._options.screen) + return; + const screenSize = this._options.screen || this._options.viewport; + const viewportSize = this._options.viewport || this._options.screen; + await Promise.all([ + this._browser._browserSession.send("browsingContext.setViewport", { + viewport: { + width: viewportSize.width, + height: viewportSize.height + }, + devicePixelRatio: this._options.deviceScaleFactor || 1, + userContexts: [this._userContextId()] + }), + this._browser._browserSession.send("emulation.setScreenOrientationOverride", { + screenOrientation: getScreenOrientation(!!this._options.isMobile, screenSize), + userContexts: [this._userContextId()] + }), + this._browser._browserSession.send("emulation.setScreenSettingsOverride", { + screenArea: { + width: screenSize.width, + height: screenSize.height + }, + userContexts: [this._userContextId()] + }) + ]); + } + async doUpdateDefaultEmulatedMedia() { + } + async doExposePlaywrightBinding() { + const args = [{ + type: "channel", + value: { + channel: kPlaywrightBindingChannel, + ownership: Script.ResultOwnership.Root + } + }]; + const functionDeclaration = `function addMainBinding(callback) { globalThis['${PageBinding.kBindingName}'] = callback; }`; + const promises = []; + promises.push(this._browser._browserSession.send("script.addPreloadScript", { + functionDeclaration, + arguments: args, + userContexts: [this._userContextId()] + })); + promises.push(...this._bidiPages().map((page) => { + const realms = [...page._contextIdToContext].filter(([realm, context2]) => context2.world === "main").map(([realm, context2]) => 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(promises); + } + onClosePersistent() { + } + async clearCache() { + } + async doClose(reason) { + if (!this._browserContextId) { + return "close-browser"; + } + await this._browser._browserSession.send("browser.removeUserContext", { + userContext: this._browserContextId + }); + await Promise.all(this._bidiPages().map((bidiPage) => bidiPage._page.closedPromise)); + this._browser._contexts.delete(this._browserContextId); + } + async cancelDownload(uuid) { + } + _userContextId() { + if (this._browserContextId) + return this._browserContextId; + return "default"; + } + }; + ((Network3) => { + let SameSite; + ((SameSite2) => { + SameSite2["Strict"] = "strict"; + SameSite2["Lax"] = "lax"; + SameSite2["None"] = "none"; + })(SameSite = Network3.SameSite || (Network3.SameSite = {})); + })(Network2 || (Network2 = {})); + } +}); + +// packages/playwright-core/src/server/chromium/crDevTools.ts +var import_fs26, kBindingName, CRDevTools; +var init_crDevTools = __esm({ + "packages/playwright-core/src/server/chromium/crDevTools.ts"() { + "use strict"; + import_fs26 = __toESM(require("fs")); + kBindingName = "__pw_devtools__"; + CRDevTools = class { + constructor(preferencesPath) { + this._preferencesPath = preferencesPath; + this._savePromise = Promise.resolve(); + } + install(session2) { + session2.on("Runtime.bindingCalled", async (event) => { + if (event.name !== kBindingName) + return; + const parsed = JSON.parse(event.payload); + let result2 = void 0; + if (parsed.method === "getPreferences") { + if (this._prefs === void 0) { + try { + const json = await import_fs26.default.promises.readFile(this._preferencesPath, "utf8"); + this._prefs = JSON.parse(json); + } catch (e) { + this._prefs = {}; + } + } + result2 = 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(); + } + session2.send("Runtime.evaluate", { + expression: `window.DevToolsAPI.embedderMessageAck(${parsed.id}, ${JSON.stringify(result2)})`, + contextId: event.executionContextId + }).catch((e) => null); + }); + Promise.all([ + session2.send("Runtime.enable"), + session2.send("Runtime.addBinding", { name: kBindingName }), + session2.send("Page.enable"), + session2.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(); }, + }); + })() + ` }), + session2.send("Runtime.runIfWaitingForDebugger") + ]).catch((e) => null); + } + _save() { + this._savePromise = this._savePromise.then(async () => { + await import_fs26.default.promises.writeFile(this._preferencesPath, JSON.stringify(this._prefs)).catch((e) => null); + }); + } + }; + } +}); + +// packages/playwright-core/src/server/chromium/chromium.ts +function profileInUseError(logs) { + const markers = [ + "Failed to create a ProcessSingleton for your profile directory.", + "Opening in existing browser session." + ]; + for (const log2 of logs) { + const marker = markers.find((m) => log2.includes(m)); + if (marker) { + return new Error( + `${marker} This usually means that the profile is already in use by another instance of Chromium.` + ); + } + } +} +async function waitForReadyState(options2, browserLogsCollector) { + if (!options2.args?.some((a) => a.startsWith("--remote-debugging-port"))) + return {}; + const result2 = new ManualPromise(); + browserLogsCollector.onMessage((message) => { + const error = profileInUseError([message]); + if (error) + result2.reject(error); + const match = message.match(/DevTools listening on (.*)/); + if (match) + result2.resolve({ wsEndpoint: match[1] }); + }); + return result2; +} +async function urlToWSEndpoint(progress2, endpointURL, headers) { + if (endpointURL.startsWith("ws")) + return endpointURL; + progress2.log(` retrieving websocket url from ${endpointURL}`); + const url2 = new URL(endpointURL); + if (!url2.pathname.endsWith("/")) + url2.pathname += "/"; + url2.pathname += "json/version/"; + const httpURL = url2.toString(); + const json = await fetchData( + progress2, + { + 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 resolveChannelEndpoint(progress2, channel) { + const userDataDir = defaultUserDataDirForChannel(channel); + if (!userDataDir) + throw new Error(`Connecting to ${channel} by channel name is not supported on ${process.platform}.`); + const devToolsActivePortPath = import_path25.default.join(userDataDir, "DevToolsActivePort"); + progress2.log(` reading ${devToolsActivePortPath}`); + const contents = await progress2.race(import_fs27.default.promises.readFile(devToolsActivePortPath, "utf-8").catch(() => void 0)); + if (!contents) { + throw new Error( + `Could not connect to ${channel}: DevToolsActivePort file not found at ${devToolsActivePortPath}. +` + remoteDebuggingHint(channel) + ); + } + const port = parseInt(contents.trim(), 10); + if (isNaN(port)) + throw new Error(`Could not connect to ${channel}: invalid DevToolsActivePort file at ${devToolsActivePortPath}.`); + const endpoint = `ws://localhost:${port}/devtools/browser`; + progress2.log(` resolved channel "${channel}" to ${endpoint}`); + return endpoint; +} +async function seleniumErrorHandler(params2, 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 ${params2.url}: ${message}`); +} +function addProtocol(url2) { + if (!["ws://", "wss://", "http://", "https://"].some((protocol) => url2.startsWith(protocol))) + return "http://" + url2; + return url2; +} +function streamToString(stream3) { + return new Promise((resolve, reject) => { + const chunks = []; + stream3.on("data", (chunk) => chunks.push(Buffer.from(chunk))); + stream3.on("error", reject); + stream3.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}`); + } +} +function remoteDebuggingHint(channel) { + return `Make sure ${channel} is running with remote debugging enabled. Navigate to + + chrome://inspect/#remote-debugging + +and check "Allow remote debugging for this browser instance". +`; +} +var import_fs27, import_os11, import_path25, ARTIFACTS_FOLDER2, Chromium; +var init_chromium = __esm({ + "packages/playwright-core/src/server/chromium/chromium.ts"() { + "use strict"; + import_fs27 = __toESM(require("fs")); + import_os11 = __toESM(require("os")); + import_path25 = __toESM(require("path")); + init_manualPromise(); + init_ascii(); + init_chromiumChannels(); + init_debugLogger(); + init_fileUtils(); + init_processLauncher(); + init_debug(); + init_headers(); + init_utils2(); + init_userAgent(); + init_chromiumSwitches(); + init_crBrowser(); + init_crConnection(); + init_browserContext(); + init_browserType(); + init_helper(); + init_registry(); + init_transport(); + init_crDevTools(); + init_browser(); + init_page(); + init_crExecutionContext(); + init_console(); + init_crProtocolHelper(); + ARTIFACTS_FOLDER2 = import_path25.default.join(import_os11.default.tmpdir(), "playwright-artifacts-"); + Chromium = class extends BrowserType { + constructor(parent, bidiChromium) { + super(parent, "chromium"); + this._bidiChromium = bidiChromium; + if (debugMode() === "inspector") + this._devtools = this._createDevTools(); + } + launch(progress2, options2, protocolLogger) { + if (options2.channel?.startsWith("bidi-")) + return this._bidiChromium.launch(progress2, options2, protocolLogger); + return super.launch(progress2, options2, protocolLogger); + } + async launchPersistentContext(progress2, userDataDir, options2) { + if (options2.channel?.startsWith("bidi-")) + return this._bidiChromium.launchPersistentContext(progress2, userDataDir, options2); + return super.launchPersistentContext(progress2, userDataDir, options2); + } + async connectOverCDP(progress2, endpointURL, options2) { + return await this._connectOverCDPInternal(progress2, endpointURL, options2); + } + 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((key) => key.toLowerCase() === "user-agent")) + headersMap["User-Agent"] = getUserAgent(); + const channel = isChromiumChannelName(endpointURL) ? endpointURL : void 0; + if (channel) + endpointURL = await resolveChannelEndpoint(progress2, endpointURL); + let wsEndpoint; + let chromeTransport; + try { + wsEndpoint = await urlToWSEndpoint(progress2, endpointURL, headersMap); + chromeTransport = await WebSocketTransport.connect(progress2, wsEndpoint, { headers: headersMap, followRedirects: true, debugLogHeader: "x-playwright-debug-log" }); + } catch (e) { + if (channel) + throw new Error(`Could not connect to ${channel}. +${remoteDebuggingHint(channel)}`); + throw e; + } + const closeAndWait = async () => await chromeTransport.closeAndWait(); + return this._connectOverCDPImpl(progress2, chromeTransport, closeAndWait, options2, onClose); + } + async _connectOverCDPImpl(progress2, transport, closeAndWait, options2, onClose) { + const artifactsDir = await progress2.race(import_fs27.default.promises.mkdtemp(ARTIFACTS_FOLDER2)); + const doCleanup = async () => { + await removeFolders([artifactsDir]); + const cb = onClose; + onClose = void 0; + await cb?.(); + }; + const doClose = async () => { + await closeAndWait(); + await doCleanup(); + }; + try { + const browserProcess = { close: doClose, kill: doClose }; + const persistent = { + noDefaultViewport: true, + ...options2.noDefaults ? { acceptDownloads: "internal-browser-default" } : {} + }; + const browserOptions = { + slowMo: options2.slowMo, + name: "chromium", + browserType: "chromium", + persistent, + browserProcess, + protocolLogger: helper.debugProtocolLogger(), + browserLogsCollector: new RecentLogsCollector(), + artifactsDir, + downloadsPath: options2.downloadsPath || artifactsDir, + tracesDir: options2.tracesDir || artifactsDir, + originalLaunchOptions: {}, + noDefaults: options2.noDefaults + }; + validateBrowserContextOptions(persistent, browserOptions); + const browser = await progress2.race(CRBrowser.connect(this.attribution.playwright, transport, browserOptions)); + if (!options2.isLocal) + browser._isCollocatedWithServer = false; + browser.on(Browser.Events.Disconnected, doCleanup); + return browser; + } catch (error) { + await progress2.race(doClose().catch(() => { + })); + throw error; + } + } + async connectToWorker(progress2, endpoint) { + const wsEndpoint = await urlToWSEndpoint(progress2, endpoint, {}); + const transport = await WebSocketTransport.connect(progress2, wsEndpoint); + try { + const connection = new CRConnection(this, transport, helper.debugProtocolLogger(), new RecentLogsCollector()); + const session2 = connection.rootSession; + const worker = new Worker(this, "", () => transport.closeAndWait()); + session2.on("Runtime.executionContextCreated", (event) => { + const isDefault = event.context.auxData?.isDefault; + if (isDefault === false) { + return; + } + worker.workerScriptLoaded(); + worker.createExecutionContext(new CRExecutionContext(session2, event.context)); + }); + session2.on("Runtime.executionContextDestroyed", () => worker.destroyExecutionContext("Execution context was destroyed")); + session2.on("Runtime.consoleAPICalled", (event) => { + if (!worker.existingExecutionContext) + return; + const args = event.args.map((o) => createHandle(worker.existingExecutionContext, o)); + const message = new ConsoleMessage(null, worker, event.type, void 0, args, stackTraceToLocation(event.stackTrace), event.timestamp); + worker.emit(Worker.Events.Console, message); + }); + connection.on(ConnectionEvents.Disconnected, () => worker.didClose()); + session2._sendMayFail("Runtime.enable"); + session2._sendMayFail("Runtime.runIfWaitingForDebugger"); + return worker; + } catch (error) { + await progress2.race(transport.closeAndWait().catch(() => { + })); + throw error; + } + } + _createDevTools() { + const directory = registry.findExecutable("chromium").directory; + return directory ? new CRDevTools(import_path25.default.join(directory, "devtools-preferences.json")) : void 0; + } + async connectToTransport(transport, options2, browserLogsCollector) { + try { + return await CRBrowser.connect(this.attribution.playwright, transport, options2, this._devtools); + } catch (e) { + const error = profileInUseError(browserLogsCollector.recentLogs()); + if (error) + throw error; + throw e; + } + } + doRewriteStartupLog(logs) { + if (logs.includes("Missing X server")) + logs = "\n" + wrapInASCIIBox(kNoXServerRunningError, 1); + if (!logs.includes("crbug.com/357670") && !logs.includes("No usable sandbox!") && !logs.includes("crbug.com/638180")) + return logs; + return [ + `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"); + } + amendEnvironment(env) { + return env; + } + attemptToGracefullyCloseBrowser(transport) { + const message = { method: "Browser.close", id: kBrowserCloseMessageId, params: {} }; + transport.send(message); + } + async launchWithSeleniumHub(progress2, hubUrl, 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 (process.env.SELENIUM_REMOTE_CAPABILITIES) { + const remoteCapabilities = parseSeleniumRemoteParams({ name: "capabilities", value: process.env.SELENIUM_REMOTE_CAPABILITIES }, progress2); + if (remoteCapabilities) + desiredCapabilities = { ...desiredCapabilities, ...remoteCapabilities }; + } + let headers = {}; + if (process.env.SELENIUM_REMOTE_HEADERS) { + const remoteHeaders = parseSeleniumRemoteParams({ name: "headers", value: process.env.SELENIUM_REMOTE_HEADERS }, progress2); + if (remoteHeaders) + headers = remoteHeaders; + } + progress2.log(` connecting to ${hubUrl}`); + const response2 = await fetchData(progress2, { + url: hubUrl + "session", + method: "POST", + headers: { + "Content-Type": "application/json; charset=utf-8", + ...headers + }, + data: JSON.stringify({ + capabilities: { alwaysMatch: desiredCapabilities } + }) + }, seleniumErrorHandler); + const value2 = JSON.parse(response2).value; + const sessionId = value2.sessionId; + progress2.log(` connected to sessionId=${sessionId}`); + const disconnectFromSelenium = async () => { + progress2.log(` disconnecting from sessionId=${sessionId}`); + await fetchData(void 0, { + url: hubUrl + "session/" + sessionId, + method: "DELETE", + headers + }).catch((error) => progress2.log(`: ${error}`)); + progress2.log(` disconnected from sessionId=${sessionId}`); + gracefullyCloseSet.delete(disconnectFromSelenium); + }; + gracefullyCloseSet.add(disconnectFromSelenium); + try { + const capabilities = value2.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(progress2, { + url: sessionInfoUrl, + method: "GET", + 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 progress2.race(disconnectFromSelenium()); + throw e; + } + } + async defaultArgs(options2, isPersistent, userDataDir) { + const chromeArguments = this._innerDefaultArgs(options2); + chromeArguments.push(`--user-data-dir=${userDataDir}`); + 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()]; + chromeArguments.push("--enable-unsafe-swiftshader"); + 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 && !options2.socksProxyPort) { + chromeArguments.push(`--host-resolver-rules="MAP * ~NOTFOUND , EXCLUDE ${proxyURL.hostname}"`); + } + 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 (options2.socksProxyPort || shouldProxyLoopback(proxy.bypass)) + proxyBypassRules.push("<-loopback>"); + if (proxyBypassRules.length > 0) + chromeArguments.push(`--proxy-bypass-list=${proxyBypassRules.join(";")}`); + } + chromeArguments.push(...args); + return chromeArguments; + } + async waitForReadyState(options2, browserLogsCollector) { + return waitForReadyState(options2, browserLogsCollector); + } + getExecutableName(options2) { + if (options2.channel && registry.isChromiumAlias(options2.channel)) + return "chromium"; + if (options2.channel === "chromium-tip-of-tree") + return options2.headless ? "chromium-tip-of-tree-headless-shell" : "chromium-tip-of-tree"; + if (options2.channel) + return options2.channel; + return options2.headless ? "chromium-headless-shell" : "chromium"; + } + }; + } +}); + +// packages/playwright-core/src/server/bidi/bidiOverCdp.ts +var bidiOverCdp_exports = {}; +__export(bidiOverCdp_exports, { + connectBidiOverCdp: () => connectBidiOverCdp +}); +async function connectBidiOverCdp(cdp) { + let server = void 0; + const bidiTransport = new BidiTransportImpl(); + const bidiConnection = new BidiConnection2(bidiTransport, () => server?.close()); + const cdpTransportImpl = new CdpTransportImpl(cdp); + const cdpConnection = new bidiCdpConnection.MapperCdpConnection(cdpTransportImpl, bidiServerLogger); + cdp.onclose = () => bidiConnection.onclose?.(); + server = await bidiMapper.BidiServer.createAndStart( + bidiTransport, + cdpConnection, + await cdpConnection.createBrowserSession(), + /* selfTargetId= */ + "", + void 0, + bidiServerLogger + ); + return bidiConnection; +} +var bidiMapper, bidiCdpConnection, bidiServerLogger, BidiTransportImpl, BidiConnection2, CdpTransportImpl; +var init_bidiOverCdp = __esm({ + "packages/playwright-core/src/server/bidi/bidiOverCdp.ts"() { + "use strict"; + bidiMapper = __toESM(require("chromium-bidi/lib/cjs/bidiMapper/BidiMapper")); + bidiCdpConnection = __toESM(require("chromium-bidi/lib/cjs/cdp/CdpConnection")); + init_debugLogger(); + bidiServerLogger = (prefix, ...args) => { + debugLogger.log(prefix, args); + }; + BidiTransportImpl = class { + setOnMessage(handler) { + this._handler = handler; + } + sendMessage(message) { + return this._bidiConnection.onmessage?.(message); + } + close() { + this._bidiConnection.onclose?.(); + } + }; + BidiConnection2 = class { + constructor(bidiTransport, closeCallback) { + this._bidiTransport = bidiTransport; + this._bidiTransport._bidiConnection = this; + this._closeCallback = closeCallback; + } + send(s) { + this._bidiTransport._handler?.(s); + } + close() { + this._closeCallback(); + } + }; + CdpTransportImpl = class { + constructor(connection) { + this._connection = connection; + this._connection.onmessage = (message) => { + this._handler?.(JSON.stringify(message)); + }; + } + setOnMessage(handler) { + this._handler = handler; + } + sendMessage(message) { + return this._connection.send(JSON.parse(message)); + } + close() { + this._connection.close(); + } + }; + } +}); + +// packages/playwright-core/src/server/bidi/bidiChromium.ts +var import_os12, BidiChromium, kBidiOverCdpWrapper; +var init_bidiChromium = __esm({ + "packages/playwright-core/src/server/bidi/bidiChromium.ts"() { + "use strict"; + import_os12 = __toESM(require("os")); + init_ascii(); + init_browserType(); + init_bidiBrowser(); + init_bidiConnection(); + init_chromiumSwitches(); + init_chromium(); + init_crBrowser(); + BidiChromium = class extends BrowserType { + constructor(parent) { + super(parent, "chromium"); + } + async connectToTransport(transport, options2, browserLogsCollector) { + const bidiOverCdp = (init_bidiOverCdp(), __toCommonJS(bidiOverCdp_exports)); + const bidiTransport = await bidiOverCdp.connectBidiOverCdp(transport); + transport[kBidiOverCdpWrapper] = bidiTransport; + try { + return BidiBrowser.connect(this.attribution.playwright, bidiTransport, options2); + } catch (e) { + const error = profileInUseError(browserLogsCollector.recentLogs()); + if (error) + throw error; + throw e; + } + } + doRewriteStartupLog(logs) { + if (logs.includes("Missing X server")) + logs = "\n" + wrapInASCIIBox(kNoXServerRunningError, 1); + if (!logs.includes("crbug.com/357670") && !logs.includes("No usable sandbox!") && !logs.includes("crbug.com/638180")) + return logs; + return [ + `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"); + } + amendEnvironment(env) { + return env; + } + attemptToGracefullyCloseBrowser(transport) { + const bidiTransport = transport[kBidiOverCdpWrapper]; + if (bidiTransport) + transport = bidiTransport; + transport.send({ method: "browser.close", params: {}, id: kBrowserCloseMessageId2 }); + } + supportsPipeTransport() { + return false; + } + async 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; + } + async waitForReadyState(options2, browserLogsCollector) { + return waitForReadyState({ ...options2, args: ["--remote-debugging-port=0"] }, browserLogsCollector); + } + _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()]; + if (import_os12.default.platform() === "darwin") { + chromeArguments.push("--enable-unsafe-swiftshader"); + } + 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 && !options2.socksProxyPort) { + chromeArguments.push(`--host-resolver-rules="MAP * ~NOTFOUND , EXCLUDE ${proxyURL.hostname}"`); + } + 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 (options2.socksProxyPort || shouldProxyLoopback(proxy.bypass)) + proxyBypassRules.push("<-loopback>"); + if (proxyBypassRules.length > 0) + chromeArguments.push(`--proxy-bypass-list=${proxyBypassRules.join(";")}`); + } + chromeArguments.push(...args); + return chromeArguments; + } + getExecutableName(options2) { + switch (options2.channel) { + case "bidi-chromium": + return "chromium"; + case "bidi-chrome": + return "chrome"; + case "bidi-chrome-beta": + return "chrome-beta"; + case "bidi-chrome-dev": + return "chrome-dev"; + case "bidi-chrome-canary": + return "chrome-canary"; + } + throw new Error(`Unsupported Bidi Chromium channel: ${options2.channel}`); + } + }; + kBidiOverCdpWrapper = Symbol("kBidiConnectionWrapper"); + } +}); + +// packages/playwright-core/src/server/bidi/third_party/firefoxPrefs.ts +async function createProfile(options2) { + if (!import_fs28.default.existsSync(options2.path)) { + await import_fs28.default.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, + "datareporting.usage.uploadEnabled": false, + "telemetry.fog.test.localhost_port": -1, + // 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, + // Enable TestUtils + "dom.testing.testutils.enabled": true + }; + return Object.assign(defaultPrefs, extraPrefs); +} +async function writePreferences(options2) { + const prefsPath = import_path26.default.join(options2.path, "prefs.js"); + const lines = Object.entries(options2.preferences).map(([key, value2]) => { + return `user_pref(${JSON.stringify(key)}, ${JSON.stringify(value2)});`; + }); + const result2 = await Promise.allSettled([ + import_fs28.default.promises.writeFile(import_path26.default.join(options2.path, "user.js"), lines.join("\n")), + // Create a backup of the preferences file if it already exitsts. + import_fs28.default.promises.access(prefsPath, import_fs28.default.constants.F_OK).then( + async () => { + await import_fs28.default.promises.copyFile( + prefsPath, + import_path26.default.join(options2.path, "prefs.js.playwright") + ); + }, + // Swallow only if file does not exist + () => { + } + ) + ]); + for (const command of result2) { + if (command.status === "rejected") { + throw command.reason; + } + } +} +var import_fs28, import_path26; +var init_firefoxPrefs = __esm({ + "packages/playwright-core/src/server/bidi/third_party/firefoxPrefs.ts"() { + "use strict"; + import_fs28 = __toESM(require("fs")); + import_path26 = __toESM(require("path")); + } +}); + +// packages/playwright-core/src/server/bidi/bidiFirefox.ts +var import_os13, import_path27, BidiFirefox; +var init_bidiFirefox = __esm({ + "packages/playwright-core/src/server/bidi/bidiFirefox.ts"() { + "use strict"; + import_os13 = __toESM(require("os")); + import_path27 = __toESM(require("path")); + init_manualPromise(); + init_ascii(); + init_browserType(); + init_bidiBrowser(); + init_bidiConnection(); + init_firefoxPrefs(); + BidiFirefox = class extends BrowserType { + constructor(parent) { + super(parent, "firefox"); + } + executablePath() { + return ""; + } + async connectToTransport(transport, options2) { + return BidiBrowser.connect(this.attribution.playwright, transport, options2); + } + doRewriteStartupLog(logs) { + if (logs.includes(`as root in a regular user's session is not supported.`)) + 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${process.env.GITHUB_ACTION ? " in your GitHub Actions workflow file" : ""} when running Playwright.`, 1); + if (logs.includes("no DISPLAY environment variable specified")) + logs = "\n" + wrapInASCIIBox(kNoXServerRunningError, 1); + return logs; + } + amendEnvironment(env) { + if (!import_path27.default.isAbsolute(import_os13.default.homedir())) + throw new Error(`Cannot launch Firefox with relative home directory. Did you set ${import_os13.default.platform() === "win32" ? "USERPROFILE" : "HOME"} to a relative path?`); + env = { + ...env, + "MOZ_CRASHREPORTER": "1", + "MOZ_CRASHREPORTER_NO_REPORT": "1", + "MOZ_CRASHREPORTER_SHUTDOWN": "1" + }; + if (import_os13.default.platform() === "linux") { + return { ...env, SNAP_NAME: void 0, SNAP_INSTANCE_NAME: void 0 }; + } + return env; + } + attemptToGracefullyCloseBrowser(transport) { + this._attemptToGracefullyCloseBrowser(transport).catch(() => { + }); + } + async _attemptToGracefullyCloseBrowser(transport) { + if (!transport.onmessage) { + transport.send({ method: "session.new", params: { capabilities: {} }, id: kShutdownSessionNewMessageId }); + await new Promise((resolve) => { + transport.onmessage = (message) => { + if (message.id === kShutdownSessionNewMessageId) + resolve(true); + }; + }); + } + transport.send({ method: "browser.close", params: {}, id: kBrowserCloseMessageId2 }); + } + supportsPipeTransport() { + return false; + } + async prepareUserDataDir(options2, userDataDir) { + await createProfile({ + path: userDataDir, + preferences: options2.firefoxUserPrefs || {} + }); + } + async 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("-"))) + throw new Error("Arguments can not specify page to be opened"); + const firefoxArguments = ["--remote-debugging-port=0"]; + if (headless) + firefoxArguments.push("--headless"); + else + firefoxArguments.push("--foreground"); + firefoxArguments.push(`--profile`, userDataDir); + firefoxArguments.push(...args); + return firefoxArguments; + } + async waitForReadyState(options2, browserLogsCollector) { + const result2 = new ManualPromise(); + browserLogsCollector.onMessage((message) => { + const match = message.match(/WebDriver BiDi listening on (ws:\/\/.*)$/); + if (match) + result2.resolve({ wsEndpoint: match[1] + "/session" }); + }); + return result2; + } + }; + } +}); + +// packages/playwright-core/src/server/debugController.ts +function wireListeners(recorder, debugController) { + if (recorder[wiredSymbol]) + return; + recorder[wiredSymbol] = true; + const actions = []; + const languageGenerator = new JavaScriptLanguageGenerator( + /* isPlaywrightTest */ + true + ); + const actionsChanged = () => { + const aa = collapseActions(actions); + const { header, footer, text: text2, actionTexts } = generateCode(aa, languageGenerator, { + browserName: "chromium", + launchOptions: {}, + contextOptions: {}, + generateAutoExpect: debugController._generateAutoExpect + }); + debugController.emit(DebugController.Events.SourceChanged, { text: text2, header, footer, actions: actionTexts }); + }; + recorder.on(RecorderEvent.ElementPicked, (elementInfo) => { + const locator2 = asLocator(debugController._sdkLanguage, elementInfo.selector); + debugController.emit(DebugController.Events.InspectRequested, { selector: elementInfo.selector, locator: locator2, ariaSnapshot: elementInfo.ariaSnapshot }); + }); + recorder.on(RecorderEvent.PausedStateChanged, (paused) => { + debugController.emit(DebugController.Events.Paused, { paused }); + }); + recorder.on(RecorderEvent.ModeChanged, (mode) => { + debugController.emit(DebugController.Events.SetModeRequested, { mode }); + }); + recorder.on(RecorderEvent.ActionAdded, (action) => { + actions.push(action); + actionsChanged(); + }); + recorder.on(RecorderEvent.SignalAdded, (signal) => { + const lastAction = actions.findLast((a) => a.frame.pageGuid === signal.frame.pageGuid); + if (lastAction) + lastAction.action.signals.push(signal.signal); + actionsChanged(); + }); +} +var yaml, DebugController, wiredSymbol; +var init_debugController = __esm({ + "packages/playwright-core/src/server/debugController.ts"() { + "use strict"; + init_ariaSnapshot(); + init_locatorParser(); + init_processLauncher(); + init_locatorGenerators(); + init_instrumentation(); + init_recorder(); + init_language(); + init_recorderUtils(); + init_javascript2(); + yaml = require("./utilsBundle").yaml; + DebugController = class _DebugController extends SdkObject { + constructor(playwright2) { + super({ attribution: { isInternalPlaywright: true }, instrumentation: createInstrumentation() }, void 0, "DebugController"); + this._sdkLanguage = "javascript"; + this._generateAutoExpect = false; + this._playwright = playwright2; + } + static { + this.Events = { + StateChanged: "stateChanged", + InspectRequested: "inspectRequested", + SourceChanged: "sourceChanged", + Paused: "paused", + SetModeRequested: "setModeRequested" + }; + } + initialize(progress2, codegenId2, sdkLanguage) { + this._sdkLanguage = sdkLanguage; + } + dispose() { + this._setReportStateChanged(false); + } + setReportStateChanged(progress2, enabled) { + this._setReportStateChanged(enabled); + } + _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 setRecorderMode(progress2, params2) { + await this._closeBrowsersWithoutPages(progress2); + this._generateAutoExpect = !!params2.generateAutoExpect; + if (params2.mode === "none") { + const promises = []; + for (const recorder of await progress2.race(this._allRecorders())) { + promises.push(recorder.hideHighlightedSelector()); + promises.push(recorder.setMode("none")); + } + await progress2.race(Promise.all(promises)); + return; + } + if (!this._playwright.allBrowsers().length) + await this._playwright.chromium.launch(progress2, { headless: !!process.env.PW_DEBUG_CONTROLLER_HEADLESS }); + const pages = this._playwright.allPages(); + if (!pages.length) { + const [browser] = this._playwright.allBrowsers(); + const context2 = await browser.newContextForReuse(progress2, {}); + await context2.newPage(progress2); + } + if (params2.testIdAttributeName) { + for (const page of this._playwright.allPages()) + page.browserContext.selectors().setTestIdAttributeName(params2.testIdAttributeName); + } + for (const recorder of await progress2.race(this._allRecorders())) { + recorder.hideHighlightedSelector(); + recorder.setMode(params2.mode); + } + } + async highlight(progress2, params2) { + if (params2.selector) + unsafeLocatorOrSelectorAsSelector(this._sdkLanguage, params2.selector, "data-testid"); + const ariaTemplate = params2.ariaTemplate ? parseAriaSnapshotUnsafe(yaml, params2.ariaTemplate) : void 0; + const promises = []; + for (const recorder of await progress2.race(this._allRecorders())) { + if (ariaTemplate) + promises.push(recorder.setHighlightedAriaTemplate(ariaTemplate)); + else if (params2.selector) + promises.push(recorder.setHighlightedSelector(params2.selector)); + } + await progress2.race(Promise.all(promises)); + } + async hideHighlight(progress2) { + const promises = []; + for (const recorder of await progress2.race(this._allRecorders())) + promises.push(recorder.hideHighlightedSelector()); + promises.push(...this._playwright.allPages().map((p) => p.hideHighlight().catch(() => { + }))); + await progress2.race(Promise.all(promises)); + } + async resume(progress2) { + for (const recorder of await progress2.race(this._allRecorders())) + recorder.resume(); + } + kill(progress2) { + gracefullyProcessExitDoNotHang(0); + } + _emitSnapshot(initial) { + const pageCount = this._playwright.allPages().length; + if (initial && !pageCount) + return; + this.emit(_DebugController.Events.StateChanged, { pageCount }); + } + async _allRecorders() { + const contexts = /* @__PURE__ */ new Set(); + for (const page of this._playwright.allPages()) + contexts.add(page.browserContext); + const recorders = await Promise.all([...contexts].map((c) => Recorder.forContext(c, { omitCallTracking: true }))); + const nonNullRecorders = recorders.filter(Boolean); + for (const recorder of recorders) + wireListeners(recorder, this); + return nonNullRecorders; + } + async _closeBrowsersWithoutPages(progress2) { + for (const browser of this._playwright.allBrowsers()) { + for (const context2 of browser.contexts()) { + if (!context2.pages().length) + await context2.close(progress2, { reason: "Browser collected" }); + } + if (!browser.contexts()) + await browser.close(progress2, { reason: "Browser collected" }); + } + } + }; + wiredSymbol = Symbol("wired"); + } +}); + +// packages/playwright-core/src/server/electron/electron.ts +async function waitForLine(progress2, process2, regex) { + const promise = new ManualPromise(); + const rl = readline2.createInterface({ input: process2.stderr }); + const failError = new Error("Process failed to launch!"); + const listeners = [ + eventsHelper.addEventListener(rl, "line", onLine), + eventsHelper.addEventListener(rl, "close", () => promise.reject(failError)), + eventsHelper.addEventListener(process2, "exit", () => promise.reject(failError)), + // It is Ok to remove error handler because we did not create process and there is another listener. + eventsHelper.addEventListener(process2, "error", () => promise.reject(failError)) + ]; + function onLine(line) { + const match = line.match(regex); + if (match) + promise.resolve(match); + } + try { + return await progress2.race(promise); + } finally { + eventsHelper.removeEventListeners(listeners); + } +} +function escapeDoubleQuotes(str) { + return str.replace(/"/g, '\\"'); +} +var import_fs29, import_os14, import_path28, readline2, ARTIFACTS_FOLDER3, ElectronApplication, Electron; +var init_electron = __esm({ + "packages/playwright-core/src/server/electron/electron.ts"() { + "use strict"; + import_fs29 = __toESM(require("fs")); + import_os14 = __toESM(require("os")); + import_path28 = __toESM(require("path")); + readline2 = __toESM(require("readline")); + init_ascii(); + init_debugLogger(); + init_eventsHelper(); + init_processLauncher(); + init_manualPromise(); + init_package(); + init_browserContext(); + init_crBrowser(); + init_crConnection(); + init_crExecutionContext(); + init_crProtocolHelper(); + init_console(); + init_helper(); + init_instrumentation(); + init_javascript(); + init_transport(); + init_progress(); + ARTIFACTS_FOLDER3 = import_path28.default.join(import_os14.default.tmpdir(), "playwright-artifacts-"); + ElectronApplication = class _ElectronApplication extends SdkObject { + constructor(parent, browser, nodeConnection, process2) { + super(parent, "electron-app"); + this._nodeElectronHandlePromise = new ManualPromise(); + this._process = process2; + this._browserContext = browser._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(this._nodeExecutionContext, "object", "ElectronModule", remoteObject.objectId)); + }); + this._nodeSession.on("Runtime.consoleAPICalled", (event) => this._onConsoleAPI(event)); + const appClosePromise = new Promise((f) => this.once(_ElectronApplication.Events.Close, f)); + this._browserContext.setCustomCloseHandler(async () => { + const electronHandle = await this._nodeElectronHandlePromise; + await electronHandle.evaluate(({ app }) => app.quit()).catch(() => { + }); + this._nodeConnection.close(); + await appClosePromise; + }); + } + static { + this.Events = { + Close: "close", + Console: "console" + }; + } + async _onConsoleAPI(event) { + if (event.executionContextId === 0) { + return; + } + if (!this._nodeExecutionContext) + return; + const args = event.args.map((arg) => createHandle(this._nodeExecutionContext, arg)); + const message = new ConsoleMessage(null, null, event.type, void 0, args, stackTraceToLocation(event.stackTrace), event.timestamp); + this.emit(_ElectronApplication.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(progress2) { + await this._browserContext.close(progress2, { reason: "Application exited" }); + } + async browserWindow(progress2, page) { + const targetId = page.delegate._targetId; + const electronHandle = await progress2.race(this._nodeElectronHandlePromise); + return await progress2.race(electronHandle.evaluateHandle(({ BrowserWindow, webContents }, targetId2) => { + const wc = webContents.fromDevToolsTargetId(targetId2); + return BrowserWindow.fromWebContents(wc); + }, targetId)); + } + }; + Electron = class extends SdkObject { + constructor(playwright2) { + super(playwright2, "electron"); + this.logName = "browser"; + } + async launch(progress2, options2) { + let app = void 0; + let electronArguments = ["--inspect=0", "--remote-debugging-port=0", ...options2.args || []]; + if (import_os14.default.platform() === "linux") { + if (!options2.chromiumSandbox && electronArguments.indexOf("--no-sandbox") === -1) + electronArguments.unshift("--no-sandbox"); + } + let artifactsDir; + const tempDirectories = []; + if (options2.artifactsDir) { + artifactsDir = options2.artifactsDir; + } else { + artifactsDir = await progress2.race(import_fs29.default.promises.mkdtemp(ARTIFACTS_FOLDER3)); + tempDirectories.push(artifactsDir); + } + const browserLogsCollector = new RecentLogsCollector(); + const env = options2.env ? envArrayToObject(options2.env) : process.env; + let command; + if (options2.executablePath) { + command = options2.executablePath; + } else { + try { + command = require("electron/index.js"); + } catch (error) { + if (error?.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 error; + } + electronArguments.unshift("-r", libPath("server", "electron", "loader.js")); + } + let shell = false; + if (process.platform === "win32") { + shell = true; + command = [command, ...electronArguments].map((arg) => `"${escapeDoubleQuotes(arg)}"`).join(" "); + electronArguments = []; + } + delete env.NODE_OPTIONS; + const { launchedProcess, gracefullyClose, kill } = await progress2.race(launchProcess({ + command, + args: electronArguments, + env, + log: (message) => { + progress2.log(message); + browserLogsCollector.log(message); + }, + shell, + stdio: "pipe", + cwd: options2.cwd, + tempDirectories, + attemptToGracefullyClose: () => app.close(nullProgress), + handleSIGINT: true, + handleSIGTERM: true, + handleSIGHUP: true, + onExit: () => app?.emit(ElectronApplication.Events.Close) + })); + const waitForXserverError = waitForLine(progress2, launchedProcess, /Unable to open X display/).then(() => { + throw 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")); + }); + 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\.\.\./); + try { + const nodeMatch = await nodeMatchPromise; + const nodeTransport = await WebSocketTransport.connect(progress2, nodeMatch[1]); + const nodeConnection = new CRConnection(this, nodeTransport, helper.debugProtocolLogger(), browserLogsCollector); + debuggerDisconnectPromise.then(() => { + nodeTransport.close(); + }).catch(() => { + }); + const chromeMatch = await progress2.race(Promise.race([ + chromeMatchPromise, + waitForXserverError + ])); + const chromeTransport = await WebSocketTransport.connect(progress2, chromeMatch[1]); + const browserProcess = { + onclose: void 0, + process: launchedProcess, + close: gracefullyClose, + kill + }; + const contextOptions = { + ...options2, + noDefaultViewport: true + }; + const browserOptions = { + name: "electron", + browserType: "chromium", + headful: true, + persistent: contextOptions, + browserProcess, + protocolLogger: helper.debugProtocolLogger(), + browserLogsCollector, + artifactsDir, + downloadsPath: artifactsDir, + tracesDir: options2.tracesDir || artifactsDir, + originalLaunchOptions: {} + }; + validateBrowserContextOptions(contextOptions, browserOptions); + const browser = await progress2.race(CRBrowser.connect(this.attribution.playwright, chromeTransport, browserOptions)); + app = new ElectronApplication(this, browser, nodeConnection, launchedProcess); + await progress2.race(app.initialize()); + return app; + } catch (error) { + await progress2.race(kill()); + throw error; + } + } + }; + } +}); + +// packages/playwright-core/src/server/firefox/ffConnection.ts +var import_events10, ConnectionEvents2, kBrowserCloseMessageId3, FFConnection, FFSession; +var init_ffConnection = __esm({ + "packages/playwright-core/src/server/firefox/ffConnection.ts"() { + "use strict"; + import_events10 = require("events"); + init_debugLogger(); + init_helper(); + init_protocolError(); + ConnectionEvents2 = { + Disconnected: Symbol("Disconnected") + }; + kBrowserCloseMessageId3 = -9999; + FFConnection = class extends import_events10.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 === kBrowserCloseMessageId3) + return; + const session2 = this._sessions.get(message.sessionId || ""); + if (session2) + session2.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(ConnectionEvents2.Disconnected)); + } + close() { + if (!this._closed) + this._transport.close(); + } + createSession(sessionId) { + const session2 = new FFSession(this, sessionId, (message) => this._rawSend({ ...message, sessionId })); + this._sessions.set(sessionId, session2); + return session2; + } + }; + FFSession = class extends import_events10.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; + } + markAsCrashed() { + this._crashed = true; + } + async send(method, params2) { + 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: params2, id }); + return new Promise((resolve, reject) => { + this._callbacks.set(id, { resolve, reject, error: new ProtocolError("error", method) }); + }); + } + sendMayFail(method, params2) { + return this.send(method, params2).catch((error) => debugLogger.log("error", error)); + } + 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(); + } + }; + } +}); + +// packages/playwright-core/src/server/firefox/ffExecutionContext.ts +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 rewriteError3(error) { + if (error.message.includes("cyclic object value") || error.message.includes("Object is not serializable")) + return { result: { type: "undefined", value: void 0 } }; + if (error instanceof TypeError && error.message.startsWith("Converting circular structure to JSON")) + rewriteErrorMessage(error, error.message + " Are you passing a nested JSHandle?"); + if (!isJavaScriptErrorInEvaluate(error) && !isSessionClosedError(error)) + throw new Error("Execution context was destroyed, most likely because of a navigation."); + throw error; +} +function potentiallyUnserializableValue2(remoteObject) { + const value2 = remoteObject.value; + const unserializableValue = remoteObject.unserializableValue; + return unserializableValue ? parseUnserializableValue(unserializableValue) : value2; +} +function renderPreview3(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 createHandle3(context2, remoteObject) { + if (remoteObject.subtype === "node") { + assert(context2 instanceof FrameExecutionContext); + return new ElementHandle(context2, remoteObject.objectId); + } + return new JSHandle(context2, remoteObject.subtype || remoteObject.type || "", renderPreview3(remoteObject), remoteObject.objectId, potentiallyUnserializableValue2(remoteObject)); +} +var FFExecutionContext; +var init_ffExecutionContext = __esm({ + "packages/playwright-core/src/server/firefox/ffExecutionContext.ts"() { + "use strict"; + init_assert(); + init_stackTrace(); + init_utilityScriptSerializers(); + init_javascript(); + init_dom(); + init_protocolError(); + FFExecutionContext = class { + constructor(session2, executionContextId) { + this._session = session2; + this._executionContextId = executionContextId; + } + async rawEvaluateJSON(expression2) { + const payload = await this._session.send("Runtime.evaluate", { + expression: expression2, + returnByValue: true, + executionContextId: this._executionContextId + }).catch(rewriteError3); + checkException(payload.exceptionDetails); + return payload.result.value; + } + async rawEvaluateHandle(context2, expression2) { + const payload = await this._session.send("Runtime.evaluate", { + expression: expression2, + returnByValue: false, + executionContextId: this._executionContextId + }).catch(rewriteError3); + checkException(payload.exceptionDetails); + return createHandle3(context2, payload.result); + } + async evaluateWithArguments(expression2, returnByValue, utilityScript, values, handles) { + const payload = await this._session.send("Runtime.callFunction", { + functionDeclaration: expression2, + args: [ + { objectId: utilityScript._objectId, value: void 0 }, + ...values.map((value2) => ({ value: value2 })), + ...handles.map((handle) => ({ objectId: handle._objectId, value: void 0 })) + ], + returnByValue, + executionContextId: this._executionContextId + }).catch(rewriteError3); + checkException(payload.exceptionDetails); + if (returnByValue) + return parseEvaluationResultValue(payload.result.value); + return createHandle3(utilityScript._context, payload.result); + } + async getProperties(object) { + const response2 = await this._session.send("Runtime.getObjectProperties", { + executionContextId: this._executionContextId, + objectId: object._objectId + }); + const result2 = /* @__PURE__ */ new Map(); + for (const property of response2.properties) + result2.set(property.name, createHandle3(object._context, property.value)); + return result2; + } + async releaseHandle(handle) { + if (!handle._objectId) + return; + await this._session.send("Runtime.disposeObject", { + executionContextId: this._executionContextId, + objectId: handle._objectId + }); + } + shouldPrependErrorPrefix() { + return true; + } + }; + } +}); + +// packages/playwright-core/src/server/firefox/ffInput.ts +function toFirefoxKeyDescription(description) { + const override = kFirefoxKeyOverrides.get(description.key); + if (!override) + return description; + return { + ...description, + ...override + }; +} +function toModifiersMask2(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 toButtonsMask2(buttons) { + let mask = 0; + if (buttons.has("left")) + mask |= 1; + if (buttons.has("right")) + mask |= 2; + if (buttons.has("middle")) + mask |= 4; + return mask; +} +var kFirefoxKeyOverrides, RawKeyboardImpl3, RawMouseImpl3, RawTouchscreenImpl3; +var init_ffInput = __esm({ + "packages/playwright-core/src/server/firefox/ffInput.ts"() { + "use strict"; + kFirefoxKeyOverrides = /* @__PURE__ */ new Map([ + ["AudioVolumeMute", { code: "VolumeMute", keyCodeWithoutLocation: 181 }], + ["AudioVolumeDown", { code: "VolumeDown", keyCodeWithoutLocation: 182 }], + ["AudioVolumeUp", { code: "VolumeUp", keyCodeWithoutLocation: 183 }] + ]); + RawKeyboardImpl3 = class { + constructor(client) { + this._client = client; + } + async keydown(progress2, modifiers, keyName, description, autoRepeat) { + const keyDescription = toFirefoxKeyDescription(description); + let text2 = keyDescription.text; + if (text2 === "\r") + text2 = ""; + const { code, key, location: location2 } = keyDescription; + await progress2.race(this._client.send("Page.dispatchKeyEvent", { + type: "keydown", + keyCode: keyDescription.keyCodeWithoutLocation, + code, + key, + repeat: autoRepeat, + location: location2, + text: text2 + })); + } + async keyup(progress2, modifiers, keyName, description) { + const keyDescription = toFirefoxKeyDescription(description); + const { code, key, location: location2 } = keyDescription; + await progress2.race(this._client.send("Page.dispatchKeyEvent", { + type: "keyup", + key, + keyCode: keyDescription.keyCodeWithoutLocation, + code, + location: location2, + repeat: false + })); + } + async sendText(progress2, text2) { + await progress2.race(this._client.send("Page.insertText", { text: text2 })); + } + }; + RawMouseImpl3 = class { + constructor(client) { + this._client = client; + } + async move(progress2, x, y, button, buttons, modifiers, forClick) { + await progress2.race(this._client.send("Page.dispatchMouseEvent", { + type: "mousemove", + button: 0, + buttons: toButtonsMask2(buttons), + x: Math.floor(x), + y: Math.floor(y), + modifiers: toModifiersMask2(modifiers) + })); + } + async down(progress2, x, y, button, buttons, modifiers, clickCount) { + await progress2.race(this._client.send("Page.dispatchMouseEvent", { + type: "mousedown", + button: toButtonNumber(button), + buttons: toButtonsMask2(buttons), + x: Math.floor(x), + y: Math.floor(y), + modifiers: toModifiersMask2(modifiers), + clickCount + })); + } + async up(progress2, x, y, button, buttons, modifiers, clickCount) { + await progress2.race(this._client.send("Page.dispatchMouseEvent", { + type: "mouseup", + button: toButtonNumber(button), + buttons: toButtonsMask2(buttons), + x: Math.floor(x), + y: Math.floor(y), + modifiers: toModifiersMask2(modifiers), + clickCount + })); + } + async wheel(progress2, x, y, buttons, modifiers, deltaX, deltaY) { + await this._page.mainFrame().evaluateExpression(progress2, `new Promise(requestAnimationFrame)`, { world: "utility" }); + await progress2.race(this._client.send("Page.dispatchWheelEvent", { + deltaX, + deltaY, + x: Math.floor(x), + y: Math.floor(y), + deltaZ: 0, + modifiers: toModifiersMask2(modifiers) + })); + } + setPage(page) { + this._page = page; + } + }; + RawTouchscreenImpl3 = class { + constructor(client) { + this._client = client; + } + async tap(progress2, x, y, modifiers) { + await progress2.race(this._client.send("Page.dispatchTapEvent", { + x, + y, + modifiers: toModifiersMask2(modifiers) + })); + } + }; + } +}); + +// packages/playwright-core/src/server/firefox/ffNetworkManager.ts +function parseMultivalueHeaders(headers) { + const result2 = []; + 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) + result2.push({ name: header.name, value: token }); + } + return result2; +} +var FFNetworkManager, causeToResourceType, internalCauseToResourceType, InterceptableRequest2, FFRouteImpl; +var init_ffNetworkManager = __esm({ + "packages/playwright-core/src/server/firefox/ffNetworkManager.ts"() { + "use strict"; + init_eventsHelper(); + init_network2(); + FFNetworkManager = class { + constructor(session2, page) { + this._session = session2; + this._requests = /* @__PURE__ */ new Map(); + this._page = page; + this._eventListeners = [ + eventsHelper.addEventListener(session2, "Network.requestWillBeSent", this._onRequestWillBeSent.bind(this)), + eventsHelper.addEventListener(session2, "Network.responseReceived", this._onResponseReceived.bind(this)), + eventsHelper.addEventListener(session2, "Network.requestFinished", this._onRequestFinished.bind(this)), + eventsHelper.addEventListener(session2, "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 (event.method === "OPTIONS" && !event.isIntercepted) + return; + if (redirectedFrom) + this._requests.delete(redirectedFrom._id); + const request2 = new InterceptableRequest2(frame, redirectedFrom, event); + let route2; + if (event.isIntercepted) + route2 = new FFRouteImpl(this._session, request2); + this._requests.set(request2._id, request2); + this._page.frameManager.requestStarted(request2.request, route2); + } + _onResponseReceived(event) { + const request2 = this._requests.get(event.requestId); + if (!request2) + return; + const getResponseBody = async () => { + const response3 = await this._session.send("Network.getResponseBody", { + requestId: request2._id + }); + if (response3.evicted) + throw new Error(`Response body for ${request2.request.method()} ${request2.request.url()} was evicted!`); + return Buffer.from(response3.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 Response2(request2.request, event.status, event.statusText, parseMultivalueHeaders(event.headers), timing, getResponseBody, event.fromServiceWorker); + if (event?.remoteIPAddress && typeof event?.remotePort === "number") { + response2._serverAddrFinished({ + ipAddress: event.remoteIPAddress, + port: event.remotePort + }); + } else { + response2._serverAddrFinished(); + } + response2._securityDetailsFinished({ + protocol: event?.securityDetails?.protocol, + subjectName: event?.securityDetails?.subjectName, + issuer: event?.securityDetails?.issuer, + validFrom: event?.securityDetails?.validFrom, + validTo: event?.securityDetails?.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); + } + response2._setHttpVersion(event.protocolVersion ?? null); + 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); + response2._setHttpVersion(null); + } + request2.request._setFailureText(event.errorCode); + this._page.frameManager.requestFailed(request2.request, event.errorCode === "NS_BINDING_ABORTED"); + } + }; + 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: "cspreport", + TYPE_XSLT: "other", + TYPE_BEACON: "beacon", + TYPE_FETCH: "fetch", + TYPE_IMAGESET: "image", + TYPE_WEB_MANIFEST: "manifest" + }; + internalCauseToResourceType = { + TYPE_INTERNAL_EVENTSOURCE: "eventsource" + }; + InterceptableRequest2 = class { + 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( + 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; + } + }; + FFRouteImpl = class { + constructor(session2, request2) { + this._session = session2; + 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 + }); + } + }; + } +}); + +// packages/playwright-core/src/server/firefox/ffPage.ts +function webSocketId(frameId, wsid) { + return `${frameId}---${wsid}`; +} +var UTILITY_WORLD_NAME2, FFPage; +var init_ffPage = __esm({ + "packages/playwright-core/src/server/firefox/ffPage.ts"() { + "use strict"; + init_stackTrace(); + init_eventsHelper(); + init_dialog(); + init_dom(); + init_page(); + init_page(); + init_ffConnection(); + init_ffExecutionContext(); + init_ffInput(); + init_ffNetworkManager(); + init_errors(); + init_videoRecorder(); + UTILITY_WORLD_NAME2 = "__playwright_utility_world__"; + FFPage = class { + constructor(session2, browserContext, opener) { + this.cspErrorsAsynchronousForInlineScripts = true; + this._reportedAsNew = false; + this._workers = /* @__PURE__ */ new Map(); + this._initScripts = []; + this._session = session2; + this._opener = opener; + this.rawKeyboard = new RawKeyboardImpl3(session2); + this.rawMouse = new RawMouseImpl3(session2); + this.rawTouchscreen = new RawTouchscreenImpl3(session2); + this._contextIdToContext = /* @__PURE__ */ new Map(); + this._browserContext = browserContext; + this._page = new Page(this, browserContext); + this.rawMouse.setPage(this._page); + this._networkManager = new FFNetworkManager(session2, this._page); + this._page.on(Page.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.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)) + ]; + const promises = []; + if (!this._page.isStorageStatePage) + startAutomaticVideoRecording(this._page); + promises.push(new Promise((f) => this._session.once("Page.ready", f))); + Promise.all(promises).then(() => this._reportAsNew(), (error) => this._reportAsNew(error)); + this.addInitScript(new InitScript(this._page, ""), UTILITY_WORLD_NAME2).catch((e) => this._reportAsNew(e)); + } + _reportAsNew(error) { + if (this._reportedAsNew) + return; + this._reportedAsNew = true; + this._page.reportAsNew(this._opener?._page, error); + } + _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_NAME2) + worldName = "utility"; + else if (!auxData.name) + worldName = "main"; + const context2 = new FrameExecutionContext(delegate, frame, worldName); + if (worldName) + frame.contextCreated(worldName, context2); + this._contextIdToContext.set(executionContextId, context2); + } + _onExecutionContextDestroyed(payload) { + const { executionContextId } = payload; + const context2 = this._contextIdToContext.get(executionContextId); + if (!context2) + return; + this._contextIdToContext.delete(executionContextId); + context2.frame.contextDestroyed(context2); + } + _onExecutionContextsCleared() { + for (const executionContextId of Array.from(this._contextIdToContext.keys())) + this._onExecutionContextDestroyed({ executionContextId }); + } + _removeContextsForFrame(frame) { + for (const [contextId4, context2] of this._contextIdToContext) { + if (context2.frame === frame) + this._contextIdToContext.delete(contextId4); + } + } + _onLinkClicked(phase) { + if (phase === "before") + this._page.frameManager.frameWillPotentiallyRequestNavigation(); + else + this._page.frameManager.frameDidPotentiallyRequestNavigation(); + } + _onNavigationStarted(params2) { + this._page.frameManager.frameRequestedNavigation(params2.frameId, params2.navigationId); + } + _onNavigationAborted(params2) { + this._page.frameManager.frameAbortedNavigation(params2.frameId, params2.errorText, params2.navigationId); + } + _onNavigationCommitted(params2) { + for (const [workerId, worker] of this._workers) { + if (worker.frameId === params2.frameId) + this._onWorkerDestroyed({ workerId }); + } + this._page.frameManager.frameCommittedNewDocumentNavigation(params2.frameId, params2.url, params2.name || "", params2.navigationId || "", false); + } + _onSameDocumentNavigation(params2) { + this._page.frameManager.frameCommittedSameDocumentNavigation(params2.frameId, params2.url); + } + _onFrameAttached(params2) { + this._page.frameManager.frameAttached(params2.frameId, params2.parentFrameId); + } + _onFrameDetached(params2) { + this._page.frameManager.frameDetached(params2.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(params2) { + const { name, message } = splitErrorMessage(params2.message); + const error = new Error(message); + error.stack = params2.message + "\n" + params2.stack.split("\n").filter(Boolean).map((a) => a.replace(/([^@]*)@(.*)/, " at $1 ($2)")).join("\n"); + error.name = name; + this._page.addPageError(error, params2.location); + } + _onConsole(payload) { + const { type: type3, args, executionContextId, location: location2 } = payload; + const context2 = this._contextIdToContext.get(executionContextId); + if (!context2) + return; + const timestamp = Date.now(); + this._page.addConsoleMessage(null, type3 === "warn" ? "warning" : type3, args.map((arg) => createHandle3(context2, arg)), location2, void 0, timestamp); + } + _onDialogOpened(params2) { + this._page.browserContext.dialogManager.dialogDidOpen(new Dialog( + this._page, + params2.type, + params2.message, + async (accept, promptText) => { + await this._session.sendMayFail("Page.handleDialog", { dialogId: params2.dialogId, accept, promptText }); + }, + params2.defaultValue + )); + } + async _onBindingCalled(event) { + const pageOrError = await this._page.waitForInitializedOrError(); + if (!(pageOrError instanceof Error)) { + const context2 = this._contextIdToContext.get(event.executionContextId); + if (context2) + await this._page.onBindingCalled(event.payload, context2); + } + } + async _onFileChooserOpened(payload) { + const { executionContextId, element: element2 } = payload; + const context2 = this._contextIdToContext.get(executionContextId); + if (!context2) + return; + const handle = createHandle3(context2, element2).asElement(); + await this._page._onFileChooserOpened(handle); + } + async _onWorkerCreated(event) { + const workerId = event.workerId; + const worker = new Worker(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)); + worker.workerScriptLoaded(); + }); + workerSession.on("Runtime.console", (event2) => { + const { type: type3, args, location: location2 } = event2; + const context2 = worker.existingExecutionContext; + this._page.addConsoleMessage(worker, type3, args.map((arg) => createHandle3(context2, arg)), location2, void 0, Date.now()); + }); + } + _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(); + } + didClose() { + this._reportAsNew(new TargetClosedError(this._page.closeReason())); + 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() { + const viewportSize = this._page.emulatedSize()?.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 set = new Set(initScripts); + this._initScripts = this._initScripts.filter((s) => !set.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, format2, 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 + }; + } + const { data } = await progress2.race(this._session.send("Page.screenshot", { + mimeType: "image/" + format2, + clip: documentRect, + quality, + omitDeviceScaleFactor: scale === "css" + })); + return Buffer.from(data, "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; + }); + } + startScreencast(options2) { + this._session.sendMayFail("Page.startScreencast", { width: options2.width, height: options2.height, quality: options2.quality }); + } + stopScreencast() { + this._session.sendMayFail("Page.stopScreencast"); + } + _onScreencastFrame(event) { + const buffer = Buffer.from(event.data, "base64"); + this._page.screencast.onScreencastFrame({ + buffer, + frameSwapWallTime: event.timestamp * 1e3, + // timestamp is in seconds, we need to convert to milliseconds. + viewportWidth: event.deviceWidth, + viewportHeight: event.deviceHeight + }, () => { + this._session.sendMayFail("Page.screencastFrameAck"); + }); + } + rafCountForStablePosition() { + return 1; + } + async getContentQuads(handle) { + const result2 = await this._session.sendMayFail("Page.getContentQuads", { + frameId: handle._context.frame._id, + objectId: handle._objectId + }); + if (!result2) + return null; + return result2.quads.map((quad) => [quad.p1, quad.p2, quad.p3, quad.p4]); + } + async setInputFilePaths(progress2, handle, files) { + await progress2.race(this._session.send("Page.setFileInputFiles", { + frameId: handle._context.frame._id, + objectId: handle._objectId, + files + })); + } + async adoptElementHandle(handle, to) { + const result2 = await this._session.send("Page.adoptNode", { + frameId: handle._context.frame._id, + objectId: handle._objectId, + executionContextId: to.delegate._executionContextId + }); + if (!result2.remoteObject) + throw new Error(kUnableToAdoptErrorMessage); + return createHandle3(to, result2.remoteObject); + } + async inputActionEpilogue() { + } + async resetForReuse(progress2) { + await this.rawMouse.move(progress2, -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 context2 = await parent.mainContext(); + const result2 = await this._session.send("Page.adoptNode", { + frameId: frame._id, + executionContextId: context2.delegate._executionContextId + }); + if (!result2.remoteObject) + throw new Error("Frame has been detached."); + return createHandle3(context2, result2.remoteObject); + } + shouldToggleStyleSheetToSyncAnimations() { + return false; + } + async setDockTile(image) { + } + }; + } +}); + +// packages/playwright-core/src/server/firefox/ffBrowser.ts +function toJugglerProxyOptions(proxy) { + const proxyServer = new URL(proxy.server); + let port = parseInt(proxyServer.port, 10); + let type3 = "http"; + if (proxyServer.protocol === "socks5:") + type3 = "socks"; + else if (proxyServer.protocol === "socks4:") + type3 = "socks4"; + else if (proxyServer.protocol === "https:") + type3 = "https"; + if (proxyServer.port === "") { + if (proxyServer.protocol === "http:") + port = 80; + else if (proxyServer.protocol === "https:") + port = 443; + } + return { + type: type3, + bypass: proxy.bypass ? proxy.bypass.split(",").map((domain) => domain.trim()) : [], + host: proxyServer.hostname, + port, + username: proxy.username, + password: proxy.password + }; +} +var FFBrowser, FFBrowserContext, kBandaidFirefoxUserPrefs; +var init_ffBrowser = __esm({ + "packages/playwright-core/src/server/firefox/ffBrowser.ts"() { + "use strict"; + init_assert(); + init_browser(); + init_browserContext(); + init_network2(); + init_ffConnection(); + init_ffPage(); + init_page(); + FFBrowser = class _FFBrowser extends Browser { + 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(ConnectionEvents2.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)); + } + static async connect(parent, transport, options2) { + const connection = new FFConnection(transport, options2.protocolLogger, options2.browserLogsCollector); + const browser = 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 promises = [ + browser.session.send("Browser.enable", { + attachToDefaultContext: !!options2.persistent, + userPrefs: Object.entries(firefoxUserPrefs).map(([name, value2]) => ({ name, value: value2 })) + }), + browser._initVersion() + ]; + if (options2.persistent) { + browser._defaultContext = new FFBrowserContext(browser, void 0, options2.persistent); + promises.push(browser._defaultContext.initialize()); + } + const proxy = options2.originalLaunchOptions.proxyOverride || options2.proxy; + if (proxy) + promises.push(browser.session.send("Browser.setBrowserProxy", toJugglerProxyOptions(proxy))); + await Promise.all(promises); + return browser; + } + async _initVersion() { + const result2 = await this.session.send("Browser.getInfo"); + this._version = result2.version.substring(result2.version.indexOf("/") + 1); + this._userAgent = result2.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 context2 = new FFBrowserContext(this, browserContextId, options2); + await context2.initialize(); + this._contexts.set(browserContextId, context2); + return context2; + } + 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: type3 } = payload.targetInfo; + assert(type3 === "page"); + const context2 = browserContextId ? this._contexts.get(browserContextId) : this._defaultContext; + assert(context2, `Unknown context id:${browserContextId}, _defaultContext: ${this._defaultContext}`); + const session2 = this._connection.createSession(payload.sessionId); + const opener = openerId ? this._ffPages.get(openerId) : null; + const ffPage = new FFPage(session2, context2, 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._reportAsNew(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 error = payload.canceled ? "canceled" : payload.error; + this.downloadFinished(payload.uuid, error); + } + _onDisconnect() { + for (const ffPage of this._ffPages.values()) + ffPage.didClose(); + this._ffPages.clear(); + this.didClose(); + } + }; + FFBrowserContext = class extends BrowserContext { + constructor(browser, browserContextId, options2) { + super(browser, options2, browserContextId); + } + async initialize() { + assert(!this._ffPages().length); + const browserContextId = this._browserContextId; + const promises = [ + super.initialize(), + this._updateInitScripts() + ]; + if (this._options.acceptDownloads !== "internal-browser-default") { + promises.push(this._browser.session.send("Browser.setDownloadOptions", { + browserContextId, + downloadOptions: { + behavior: this._options.acceptDownloads === "accept" ? "saveToDisk" : "cancel", + downloadsDir: this._browser.options.downloadsPath + } + })); + } + promises.push(this.doUpdateDefaultViewport()); + if (this._options.hasTouch) + promises.push(this._browser.session.send("Browser.setTouchOverride", { browserContextId, hasTouch: true })); + if (this._options.userAgent) + promises.push(this._browser.session.send("Browser.setUserAgentOverride", { browserContextId, userAgent: this._options.userAgent })); + if (this._options.bypassCSP) + promises.push(this._browser.session.send("Browser.setBypassCSP", { browserContextId, bypassCSP: true })); + if (this._options.ignoreHTTPSErrors || this._options.internalIgnoreHTTPSErrors) + promises.push(this._browser.session.send("Browser.setIgnoreHTTPSErrors", { browserContextId, ignoreHTTPSErrors: true })); + if (this._options.javaScriptEnabled === false) + promises.push(this._browser.session.send("Browser.setJavaScriptDisabled", { browserContextId, javaScriptDisabled: true })); + if (this._options.locale) + promises.push(this._browser.session.send("Browser.setLocaleOverride", { browserContextId, locale: this._options.locale })); + if (this._options.timezoneId) + promises.push(this._browser.session.send("Browser.setTimezoneOverride", { browserContextId, timezoneId: this._options.timezoneId })); + if (this._options.extraHTTPHeaders || this._options.locale) + promises.push(this.doUpdateExtraHTTPHeaders()); + if (this._options.httpCredentials) + promises.push(this.innerSetHTTPCredentials(this._options.httpCredentials)); + if (this._options.geolocation) + promises.push(this.setGeolocation(this._options.geolocation)); + if (this._options.offline) + promises.push(this.doUpdateOffline()); + promises.push(this.doUpdateDefaultEmulatedMedia()); + const proxy = this._options.proxyOverride || this._options.proxy; + if (proxy) { + promises.push(this._browser.session.send("Browser.setContextProxy", { + browserContextId: this._browserContextId, + ...toJugglerProxyOptions(proxy) + })); + } + await Promise.all(promises); + } + _ffPages() { + return Array.from(this._browser._ffPages.values()).filter((ffPage) => ffPage._browserContext === this); + } + possiblyUninitializedPages() { + return this._ffPages().map((ffPage) => ffPage._page); + } + async doCreateNewPage() { + 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; + }); + return this._browser._ffPages.get(targetId)._page; + } + async doGetCookies(urls) { + const { cookies } = await this._browser.session.send("Browser.getCookies", { browserContextId: this._browserContextId }); + return filterCookies(cookies.map((c) => { + const { name, value: value2, domain, path: path59, expires, httpOnly, secure, sameSite } = c; + return { + name, + value: value2, + domain, + path: path59, + expires, + httpOnly, + secure, + sameSite + }; + }), urls); + } + async addCookies(cookies) { + const cc = rewriteCookies(cookies).map((c) => { + const { name, value: value2, url: url2, domain, path: path59, expires, httpOnly, secure, sameSite } = c; + return { + name, + value: value2, + url: url2, + domain, + path: path59, + expires: expires === -1 ? void 0 : expires, + httpOnly, + secure, + sameSite + }; + }); + 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"], + ["screen-wake-lock", "screen-wake-lock"] + ]); + 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 doUpdateExtraHTTPHeaders() { + 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 doUpdateOffline() { + await this._browser.session.send("Browser.setOnlineOverride", { browserContextId: this._browserContextId, override: this._options.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((binding) => binding.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 doUpdateDefaultViewport() { + if (!this._options.viewport) + return; + const viewport = { + viewportSize: { width: this._options.viewport.width, height: this._options.viewport.height }, + deviceScaleFactor: this._options.deviceScaleFactor || 1 + }; + await this._browser.session.send("Browser.setDefaultViewport", { browserContextId: this._browserContextId, viewport }); + } + async doUpdateDefaultEmulatedMedia() { + if (this._options.colorScheme !== "no-override") { + await this._browser.session.send("Browser.setColorScheme", { + browserContextId: this._browserContextId, + colorScheme: this._options.colorScheme !== void 0 ? this._options.colorScheme : "light" + }); + } + if (this._options.reducedMotion !== "no-override") { + await this._browser.session.send("Browser.setReducedMotion", { + browserContextId: this._browserContextId, + reducedMotion: this._options.reducedMotion !== void 0 ? this._options.reducedMotion : "no-preference" + }); + } + if (this._options.forcedColors !== "no-override") { + await this._browser.session.send("Browser.setForcedColors", { + browserContextId: this._browserContextId, + forcedColors: this._options.forcedColors !== void 0 ? this._options.forcedColors : "none" + }); + } + if (this._options.contrast !== "no-override") { + await this._browser.session.send("Browser.setContrast", { + browserContextId: this._browserContextId, + contrast: this._options.contrast !== void 0 ? this._options.contrast : "no-preference" + }); + } + } + 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) { + return "close-browser"; + } 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 }); + } + }; + kBandaidFirefoxUserPrefs = {}; + } +}); + +// packages/playwright-core/src/server/firefox/firefox.ts +var import_os15, import_path29, Firefox; +var init_firefox = __esm({ + "packages/playwright-core/src/server/firefox/firefox.ts"() { + "use strict"; + import_os15 = __toESM(require("os")); + import_path29 = __toESM(require("path")); + init_manualPromise(); + init_ascii(); + init_ffBrowser(); + init_ffConnection(); + init_browserType(); + Firefox = class extends BrowserType { + constructor(parent, bidiFirefox) { + super(parent, "firefox"); + this._bidiFirefox = bidiFirefox; + } + launch(progress2, options2, protocolLogger) { + if (options2.channel?.startsWith("moz-")) + return this._bidiFirefox.launch(progress2, options2, protocolLogger); + return super.launch(progress2, options2, protocolLogger); + } + async launchPersistentContext(progress2, userDataDir, options2) { + if (options2.channel?.startsWith("moz-")) + return this._bidiFirefox.launchPersistentContext(progress2, userDataDir, options2); + return super.launchPersistentContext(progress2, userDataDir, options2); + } + connectToTransport(transport, options2) { + return FFBrowser.connect(this.attribution.playwright, transport, options2); + } + doRewriteStartupLog(logs) { + if (logs.includes(`as root in a regular user's session is not supported.`)) + 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${process.env.GITHUB_ACTION ? " in your GitHub Actions workflow file" : ""} when running Playwright.`, 1); + if (logs.includes("no DISPLAY environment variable specified")) + logs = "\n" + wrapInASCIIBox(kNoXServerRunningError, 1); + return logs; + } + amendEnvironment(env) { + if (!import_path29.default.isAbsolute(import_os15.default.homedir())) + throw new Error(`Cannot launch Firefox with relative home directory. Did you set ${import_os15.default.platform() === "win32" ? "USERPROFILE" : "HOME"} to a relative path?`); + if (import_os15.default.platform() === "linux") { + return { ...env, SNAP_NAME: void 0, SNAP_INSTANCE_NAME: void 0 }; + } + return env; + } + attemptToGracefullyCloseBrowser(transport) { + const message = { method: "Browser.close", params: {}, id: kBrowserCloseMessageId3 }; + transport.send(message); + } + async 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; + } + waitForReadyState(options2, browserLogsCollector) { + const result2 = new ManualPromise(); + browserLogsCollector.onMessage((message) => { + if (message.includes("Juggler listening to the pipe")) + result2.resolve({}); + }); + return result2; + } + }; + } +}); + +// packages/playwright-core/src/server/webkit/wkConnection.ts +var import_events11, kBrowserCloseMessageId4, kPageProxyMessageReceived, WKConnection, WKSession; +var init_wkConnection = __esm({ + "packages/playwright-core/src/server/webkit/wkConnection.ts"() { + "use strict"; + import_events11 = require("events"); + init_debugLogger(); + init_assert(); + init_helper(); + init_protocolError(); + kBrowserCloseMessageId4 = -9999; + kPageProxyMessageReceived = Symbol("kPageProxyMessageReceived"); + WKConnection = class { + 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 === kBrowserCloseMessageId4) + 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(); + } + }; + WKSession = class extends import_events11.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; + } + async send(method, params2) { + 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: params2 }; + this._rawSend(messageObj); + return new Promise((resolve, reject) => { + this._callbacks.set(id, { resolve, reject, error: new ProtocolError("error", method) }); + }); + } + sendMayFail(method, params2) { + return this.send(method, params2).catch((error) => debugLogger.log("error", error)); + } + 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(), JSON.stringify(object)); + } else { + Promise.resolve().then(() => this.emit(object.method, object.params)); + } + } + }; + } +}); + +// packages/playwright-core/src/server/webkit/wkExecutionContext.ts +function potentiallyUnserializableValue3(remoteObject) { + const value2 = remoteObject.value; + const isUnserializable = remoteObject.type === "number" && ["NaN", "-Infinity", "Infinity", "-0"].includes(remoteObject.description); + return isUnserializable ? parseUnserializableValue(remoteObject.description) : value2; +} +function rewriteError4(error) { + if (error.message.includes("Object has too long reference chain")) + throw new Error("Cannot serialize result: object reference chain is too long."); + if (!isJavaScriptErrorInEvaluate(error) && !isSessionClosedError(error)) + return new Error("Execution context was destroyed, most likely because of a navigation."); + return error; +} +function renderPreview4(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: value2 } of object.preview.properties) + tokens.push(`${name}: ${value2}`); + return `{${tokens.join(", ")}}`; + } + if (object.subtype === "array" && object.preview) + return sparseArrayToString(object.preview.properties); + return object.description; +} +function createHandle4(context2, remoteObject) { + if (remoteObject.subtype === "node") { + assert(context2 instanceof FrameExecutionContext); + return new ElementHandle(context2, remoteObject.objectId); + } + const isPromise = remoteObject.className === "Promise"; + return new JSHandle(context2, isPromise ? "promise" : remoteObject.subtype || remoteObject.type, renderPreview4(remoteObject), remoteObject.objectId, potentiallyUnserializableValue3(remoteObject)); +} +var WKExecutionContext; +var init_wkExecutionContext = __esm({ + "packages/playwright-core/src/server/webkit/wkExecutionContext.ts"() { + "use strict"; + init_assert(); + init_utilityScriptSerializers(); + init_javascript(); + init_dom(); + init_protocolError(); + WKExecutionContext = class { + constructor(session2, contextId4) { + this._session = session2; + this._contextId = contextId4; + } + async rawEvaluateJSON(expression2) { + try { + const response2 = await this._session.send("Runtime.evaluate", { + expression: expression2, + contextId: this._contextId, + returnByValue: true + }); + if (response2.wasThrown) + throw new JavaScriptErrorInEvaluate(response2.result.description); + return response2.result.value; + } catch (error) { + throw rewriteError4(error); + } + } + async rawEvaluateHandle(context2, expression2) { + try { + const response2 = await this._session.send("Runtime.evaluate", { + expression: expression2, + contextId: this._contextId, + returnByValue: false + }); + if (response2.wasThrown) + throw new JavaScriptErrorInEvaluate(response2.result.description); + return createHandle4(context2, response2.result); + } catch (error) { + throw rewriteError4(error); + } + } + async evaluateWithArguments(expression2, returnByValue, utilityScript, values, handles) { + try { + const response2 = await this._session.send("Runtime.callFunctionOn", { + functionDeclaration: expression2, + objectId: utilityScript._objectId, + arguments: [ + { objectId: utilityScript._objectId }, + ...values.map((value2) => ({ value: value2 })), + ...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 createHandle4(utilityScript._context, response2.result); + } catch (error) { + throw rewriteError4(error); + } + } + async getProperties(object) { + const response2 = await this._session.send("Runtime.getProperties", { + objectId: object._objectId, + ownProperties: true + }); + const result2 = /* @__PURE__ */ new Map(); + for (const property of response2.properties) { + if (!property.enumerable || !property.value) + continue; + result2.set(property.name, createHandle4(object._context, property.value)); + } + return result2; + } + async releaseHandle(handle) { + if (!handle._objectId) + return; + await this._session.send("Runtime.releaseObject", { objectId: handle._objectId }); + } + shouldPrependErrorPrefix() { + return false; + } + }; + } +}); + +// packages/playwright-core/src/server/webkit/wkInput.ts +function toModifiersMask3(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 toButtonsMask3(buttons) { + let mask = 0; + if (buttons.has("left")) + mask |= 1; + if (buttons.has("right")) + mask |= 2; + if (buttons.has("middle")) + mask |= 4; + return mask; +} +var RawKeyboardImpl4, RawMouseImpl4, RawTouchscreenImpl4; +var init_wkInput = __esm({ + "packages/playwright-core/src/server/webkit/wkInput.ts"() { + "use strict"; + init_stringUtils(); + init_input(); + init_macEditingCommands(); + RawKeyboardImpl4 = class { + constructor(session2) { + this._pageProxySession = session2; + } + setSession(session2) { + this._session = session2; + } + async keydown(progress2, 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, text: text2 } = description; + parts.push(code); + const shortcut = parts.join("+"); + let commands2 = macEditingCommands[shortcut]; + if (isString(commands2)) + commands2 = [commands2]; + await progress2.race(this._pageProxySession.send("Input.dispatchKeyEvent", { + type: "keyDown", + modifiers: toModifiersMask3(modifiers), + windowsVirtualKeyCode: keyCode, + code, + key, + text: text2, + unmodifiedText: text2, + autoRepeat, + macCommands: commands2, + isKeypad: description.location === keypadLocation2 + })); + } + async keyup(progress2, modifiers, keyName, description) { + const { code, key } = description; + await progress2.race(this._pageProxySession.send("Input.dispatchKeyEvent", { + type: "keyUp", + modifiers: toModifiersMask3(modifiers), + key, + windowsVirtualKeyCode: description.keyCode, + code, + isKeypad: description.location === keypadLocation2 + })); + } + async sendText(progress2, text2) { + await progress2.race(this._session.send("Page.insertText", { text: text2 })); + } + }; + RawMouseImpl4 = class { + constructor(session2) { + this._pageProxySession = session2; + } + setSession(session2) { + this._session = session2; + } + async move(progress2, x, y, button, buttons, modifiers, forClick) { + await progress2.race(this._pageProxySession.send("Input.dispatchMouseEvent", { + type: "move", + button, + buttons: toButtonsMask3(buttons), + x, + y, + modifiers: toModifiersMask3(modifiers) + })); + } + async down(progress2, x, y, button, buttons, modifiers, clickCount) { + await progress2.race(this._pageProxySession.send("Input.dispatchMouseEvent", { + type: "down", + button, + buttons: toButtonsMask3(buttons), + x, + y, + modifiers: toModifiersMask3(modifiers), + clickCount + })); + } + async up(progress2, x, y, button, buttons, modifiers, clickCount) { + await progress2.race(this._pageProxySession.send("Input.dispatchMouseEvent", { + type: "up", + button, + buttons: toButtonsMask3(buttons), + x, + y, + modifiers: toModifiersMask3(modifiers), + clickCount + })); + } + async wheel(progress2, x, y, buttons, modifiers, deltaX, deltaY) { + if (this._page?.browserContext._options.isMobile) + throw new Error("Mouse wheel is not supported in mobile WebKit"); + await progress2.race(this._session.send("Page.updateScrollingState")); + await this._page.mainFrame().evaluateExpression(progress2, `new Promise(requestAnimationFrame)`, { world: "utility" }); + await progress2.race(this._pageProxySession.send("Input.dispatchWheelEvent", { + x, + y, + deltaX, + deltaY, + modifiers: toModifiersMask3(modifiers) + })); + } + setPage(page) { + this._page = page; + } + }; + RawTouchscreenImpl4 = class { + constructor(session2) { + this._pageProxySession = session2; + } + async tap(progress2, x, y, modifiers) { + await progress2.race(this._pageProxySession.send("Input.dispatchTapEvent", { + x, + y, + modifiers: toModifiersMask3(modifiers) + })); + } + }; + } +}); + +// packages/playwright-core/src/server/webkit/wkInterceptableRequest.ts +function wkMillisToRoundishMillis(value2) { + if (value2 === -1e3) + return -1; + if (value2 <= 0) { + return -1; + } + return (value2 * 1e3 | 0) / 1e3; +} +function toResourceType2(type3) { + switch (type3) { + case "Document": + return "document"; + case "StyleSheet": + return "stylesheet"; + case "Image": + return "image"; + case "Font": + return "font"; + case "Script": + return "script"; + case "XHR": + return "xhr"; + case "Fetch": + return "fetch"; + case "Ping": + return "ping"; + case "Beacon": + return "beacon"; + case "WebSocket": + return "websocket"; + case "EventSource": + return "eventsource"; + default: + return "other"; + } +} +var errorReasons2, WKInterceptableRequest, WKRouteImpl; +var init_wkInterceptableRequest = __esm({ + "packages/playwright-core/src/server/webkit/wkInterceptableRequest.ts"() { + "use strict"; + init_assert(); + init_headers(); + init_network2(); + errorReasons2 = { + "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" + }; + WKInterceptableRequest = class { + constructor(session2, frame, event, redirectedFrom, documentId) { + this._session = session2; + this._requestId = event.requestId; + const resourceType = event.type ? toResourceType2(event.type) : 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( + frame._page.browserContext, + frame, + null, + 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 response3 = await this._session.send("Network.getResponseBody", { requestId: this._requestId }); + return Buffer.from(response3.body, response3.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 Response2(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; + } + }; + WKRouteImpl = class { + constructor(session2, requestId) { + this._session = session2; + this._requestId = requestId; + } + async abort(errorCode) { + const errorType = errorReasons2[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 + }); + } + }; + } +}); + +// packages/playwright-core/src/server/webkit/wkProvisionalPage.ts +var WKProvisionalPage; +var init_wkProvisionalPage = __esm({ + "packages/playwright-core/src/server/webkit/wkProvisionalPage.ts"() { + "use strict"; + init_eventsHelper(); + init_assert(); + WKProvisionalPage = class { + constructor(session2, page) { + this._sessionListeners = []; + this._mainFrameId = null; + this._session = session2; + this._wkPage = page; + this._coopNavigationRequest = page._page.mainFrame().pendingDocument()?.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(session2, "Network.requestWillBeSent", overrideFrameId((e) => this._onRequestWillBeSent(e))), + eventsHelper.addEventListener(session2, "Network.requestIntercepted", overrideFrameId((e) => wkPage._onRequestIntercepted(session2, e))), + eventsHelper.addEventListener(session2, "Network.responseReceived", overrideFrameId((e) => wkPage._onResponseReceived(session2, e))), + eventsHelper.addEventListener(session2, "Network.loadingFinished", overrideFrameId((e) => this._onLoadingFinished(e))), + eventsHelper.addEventListener(session2, "Network.loadingFailed", overrideFrameId((e) => this._onLoadingFailed(e))) + ]; + this.initializationPromise = this._wkPage._initializeSession(session2, 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; + } + }; + } +}); + +// packages/playwright-core/src/server/webkit/wkWorkers.ts +var WKWorkers; +var init_wkWorkers = __esm({ + "packages/playwright-core/src/server/webkit/wkWorkers.ts"() { + "use strict"; + init_eventsHelper(); + init_page(); + init_wkConnection(); + init_wkExecutionContext(); + WKWorkers = class { + constructor(page) { + this._sessionListeners = []; + this._workerSessions = /* @__PURE__ */ new Map(); + this._page = page; + } + setSession(session2) { + eventsHelper.removeEventListeners(this._sessionListeners); + this.clear(); + this._sessionListeners = [ + eventsHelper.addEventListener(session2, "Worker.workerCreated", (event) => { + const worker = new Worker(this._page, event.url); + const workerSession = new WKSession(session2.connection, event.workerId, (message) => { + session2.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)); + worker.workerScriptLoaded(); + 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"), + session2.send("Worker.initialized", { workerId: event.workerId }) + ]).catch((e) => { + this._page.removeWorker(event.workerId); + }); + }), + eventsHelper.addEventListener(session2, "Worker.dispatchMessageFromWorker", (event) => { + const workerSession = this._workerSessions.get(event.workerId); + if (!workerSession) + return; + workerSession.dispatchMessage(JSON.parse(event.message)); + }), + eventsHelper.addEventListener(session2, "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(session2) { + await session2.send("Worker.enable"); + } + async _onConsoleMessage(worker, event) { + const { type: type3, level, text: text2, parameters, url: url2, line: lineNumber, column: columnNumber } = event.message; + let derivedType = type3 || ""; + if (type3 === "log") + derivedType = level; + else if (type3 === "timing") + derivedType = "timeEnd"; + const handles = (parameters || []).map((p) => { + return createHandle4(worker.existingExecutionContext, p); + }); + const location2 = { + url: url2 || "", + lineNumber: (lineNumber || 1) - 1, + columnNumber: (columnNumber || 1) - 1 + }; + const timestamp = event.message.timestamp ? event.message.timestamp * 1e3 : Date.now(); + this._page.addConsoleMessage(worker, derivedType, handles, location2, handles.length ? void 0 : text2, timestamp); + } + }; + } +}); + +// packages/playwright-core/src/server/webkit/wkPage.ts +function parseRemoteAddress(value2) { + if (!value2) + return; + try { + const colon = value2.lastIndexOf(":"); + const dot = value2.lastIndexOf("."); + if (dot < 0) { + return { + ipAddress: `[${value2.slice(0, colon)}]`, + port: +value2.slice(colon + 1) + }; + } + if (colon > dot) { + const [address, port] = value2.split(":"); + return { + ipAddress: address, + port: +port + }; + } else { + const [address, port] = value2.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 (_) { + } +} +var PNG2, jpegjs3, UTILITY_WORLD_NAME3, enableFrameSessions, WKPage, WKFrame; +var init_wkPage = __esm({ + "packages/playwright-core/src/server/webkit/wkPage.ts"() { + "use strict"; + init_headers(); + init_stackTrace(); + init_eventsHelper(); + init_hostPlatform(); + init_assert(); + init_dialog(); + init_dom(); + init_errors(); + init_helper(); + init_network2(); + init_page(); + init_wkConnection(); + init_wkExecutionContext(); + init_wkInput(); + init_wkInterceptableRequest(); + init_wkProvisionalPage(); + init_wkWorkers(); + init_webkit(); + init_registry(); + init_videoRecorder(); + init_progress(); + ({ PNG: PNG2 } = require("./utilsBundle")); + jpegjs3 = require("./utilsBundle").jpegjs; + UTILITY_WORLD_NAME3 = "__playwright_utility_world__"; + enableFrameSessions = !process.env.WK_DISABLE_FRAME_SESSIONS && parseInt(registry.findExecutable("webkit").revision, 10) >= 2245 && parseInt(registry.findExecutable("webkit").revision, 10) <= 2255; + WKPage = class _WKPage { + constructor(browserContext, pageProxySession, opener) { + this._provisionalPage = null; + this._targetIdToFrameSession = /* @__PURE__ */ new Map(); + 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._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(this, browserContext); + this.rawMouse.setPage(this._page); + this._workers = new WKWorkers(this._page); + this._session = void 0; + this._browserContext = browserContext; + this._page.on(Page.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; + }); + this._firstNonInitialNavigationCommittedPromise.catch(() => { + }); + 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.isStorageStatePage) + return; + const promises = [ + this._pageProxySession.send("Dialog.enable"), + this._pageProxySession.send("Emulation.setActiveAndFocused", { active: true }) + ]; + const contextOptions = this._browserContext._options; + if (contextOptions.javaScriptEnabled === false) + promises.push(this._pageProxySession.send("Emulation.setJavaScriptEnabled", { enabled: false })); + promises.push(this._updateViewport()); + promises.push(this.updateHttpCredentials()); + if (this._browserContext._permissions.size) { + for (const [key, value2] of this._browserContext._permissions) + promises.push(this._grantPermissions(key, value2)); + } + startAutomaticVideoRecording(this._page); + await Promise.all(promises); + } + _setSession(session2) { + eventsHelper.removeEventListeners(this._sessionListeners); + this._session = session2; + this.rawKeyboard.setSession(session2); + this.rawMouse.setSession(session2); + this._addSessionListeners(); + this._workers.setSession(session2); + } + // 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(session2, provisional, resourceTreeHandler) { + await this._initializeSessionMayThrow(session2, resourceTreeHandler).catch((e) => { + if (provisional && session2.isDisposed()) + return; + if (this._session === session2) + throw e; + }); + } + async _initializeSessionMayThrow(session2, resourceTreeHandler) { + const [, frameTree] = await Promise.all([ + // Page agent must be enabled before Runtime. + session2.send("Page.enable"), + session2.send("Page.getResourceTree") + ]); + resourceTreeHandler(frameTree); + const promises = [ + // Resource tree should be received before first execution context. + session2.send("Runtime.enable"), + session2.send("Page.createUserWorld", { name: UTILITY_WORLD_NAME3 }).catch((_) => { + }), + // Worlds are per-process + session2.send("Network.enable"), + this._workers.initializeSession(session2) + ]; + if (enableFrameSessions) + this._initializeFrameSessions(frameTree.frameTree, promises); + else + promises.push(session2.send("Console.enable")); + if (this._page.browserContext.needsPlaywrightBinding()) + promises.push(session2.send("Runtime.addBinding", { name: PageBinding.kBindingName })); + if (this._page.needsRequestInterception()) { + promises.push(session2.send("Network.setInterceptionEnabled", { enabled: true })); + promises.push(session2.send("Network.setResourceCachingDisabled", { disabled: true })); + promises.push(session2.send("Network.addInterception", { url: ".*", stage: "request", isRegex: true })); + } + if (this._page.isStorageStatePage) { + await Promise.all(promises); + return; + } + const contextOptions = this._browserContext._options; + if (contextOptions.userAgent) + promises.push(this.updateUserAgent()); + const emulatedMedia = this._page.emulatedMedia(); + if (emulatedMedia.media || emulatedMedia.colorScheme || emulatedMedia.reducedMotion || emulatedMedia.forcedColors || emulatedMedia.contrast) + promises.push(_WKPage._setEmulateMedia(session2, emulatedMedia.media, emulatedMedia.colorScheme, emulatedMedia.reducedMotion, emulatedMedia.forcedColors, emulatedMedia.contrast)); + const bootstrapScript = this._calculateBootstrapScript(); + if (bootstrapScript.length) + promises.push(session2.send("Page.setBootstrapScript", { source: bootstrapScript })); + this._page.frames().map((frame) => frame.evaluateExpression(nullProgress, bootstrapScript).catch((e) => { + })); + if (contextOptions.bypassCSP) + promises.push(session2.send("Page.setBypassCSP", { enabled: true })); + const emulatedSize = this._page.emulatedSize(); + if (emulatedSize) { + promises.push(session2.send("Page.setScreenSizeOverride", { + width: emulatedSize.screen.width, + height: emulatedSize.screen.height + })); + } + promises.push(this.updateEmulateMedia()); + promises.push(session2.send("Network.setExtraHTTPHeaders", { headers: headersArrayToObject( + this._calculateExtraHTTPHeaders(), + false + /* lowerCase */ + ) })); + if (contextOptions.offline) + promises.push(session2.send("Network.setEmulateOfflineState", { offline: true })); + promises.push(session2.send("Page.setTouchEmulationEnabled", { enabled: !!contextOptions.hasTouch })); + if (contextOptions.timezoneId) { + promises.push(session2.send("Page.setTimeZone", { timeZone: contextOptions.timezoneId }).catch((e) => { + throw new Error(`Invalid timezone ID: ${contextOptions.timezoneId}`); + })); + } + if (this._page.fileChooserIntercepted()) + promises.push(session2.send("Page.setInterceptFileChooserDialog", { enabled: true })); + promises.push(session2.send("Page.overrideSetting", { setting: "DeviceOrientationEventEnabled", value: contextOptions.isMobile })); + promises.push(session2.send("Page.overrideSetting", { setting: "FullScreenEnabled", value: !contextOptions.isMobile })); + promises.push(session2.send("Page.overrideSetting", { setting: "NotificationsEnabled", value: !contextOptions.isMobile })); + promises.push(session2.send("Page.overrideSetting", { setting: "PointerLockEnabled", value: !contextOptions.isMobile })); + promises.push(session2.send("Page.overrideSetting", { setting: "InputTypeMonthEnabled", value: contextOptions.isMobile })); + promises.push(session2.send("Page.overrideSetting", { setting: "InputTypeWeekEnabled", value: contextOptions.isMobile })); + promises.push(session2.send("Page.overrideSetting", { setting: "FixedBackgroundsPaintRelativeToDocument", value: contextOptions.isMobile })); + await Promise.all(promises); + } + _initializeFrameSessions(frame, promises) { + const session2 = this._targetIdToFrameSession.get(`frame-${frame.frame.id}`); + if (session2) + promises.push(session2.initialize()); + for (const childFrame of frame.childFrames || []) + this._initializeFrameSessions(childFrame, promises); + } + _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(); + } + } else if (this._targetIdToFrameSession.has(targetId)) { + this._targetIdToFrameSession.get(targetId).dispose(); + this._targetIdToFrameSession.delete(targetId); + } + } + 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(this._page.closeReason())); + 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) { + const { targetInfo } = event; + const session2 = new WKSession(this._pageProxySession.connection, targetInfo.targetId, (message) => { + this._pageProxySession.send("Target.sendMessageToTarget", { + message: JSON.stringify(message), + targetId: targetInfo.targetId + }).catch((e) => { + session2.dispatchMessage({ id: message.id, error: { message: e.message } }); + }); + }); + if (targetInfo.type === "frame") { + if (enableFrameSessions) { + const wkFrame = new WKFrame(this, session2); + this._targetIdToFrameSession.set(targetInfo.targetId, wkFrame); + await wkFrame.initialize().catch((e) => { + }); + } + return; + } + 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(session2); + await Promise.all([ + this._initializePageProxySession(), + this._initializeSession(session2, 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 && this._page.mainFrame().url() === "") { + try { + await this._firstNonInitialNavigationCommittedPromise; + } catch (e) { + pageOrError = e; + } + } + this._page.reportAsNew(this._opener?._page, pageOrError instanceof Page ? void 0 : pageOrError); + } else { + assert(targetInfo.isProvisional); + assert(!this._provisionalPage); + this._provisionalPage = new WKProvisionalPage(session2, 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 if (this._targetIdToFrameSession.has(targetId)) + this._targetIdToFrameSession.get(targetId)._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.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, params2) { + await this._forAllSessions((session2) => session2.send(method, params2).then()); + } + async _forAllSessions(callback) { + const sessions = [ + this._session + ]; + if (this._provisionalPage) + sessions.push(this._provisionalPage._session); + await Promise.all(sessions.map((session2) => callback(session2).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"); + } + _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 [contextId4, context2] of this._contextIdToContext) { + if (context2.frame === frame) { + this._contextIdToContext.delete(contextId4); + if (notifyFrame) + frame.contextDestroyed(context2); + } + } + } + _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_NAME3) + worldName = "utility"; + const context2 = new FrameExecutionContext(delegate, frame, worldName); + if (worldName) + frame.contextCreated(worldName, context2); + this._contextIdToContext.set(contextPayload.id, context2); + } + async _onBindingCalled(contextId4, argument) { + const pageOrError = await this._page.waitForInitializedOrError(); + if (!(pageOrError instanceof Error)) { + const context2 = this._contextIdToContext.get(contextId4); + if (context2) + await this._page.onBindingCalled(argument, context2); + } + } + async navigateFrame(frame, url2, referrer) { + if (this._pageProxySession.isDisposed()) + throw new TargetClosedError(this._page.closeReason()); + const pageProxyId = this._pageProxySession.sessionId; + const result2 = await this._pageProxySession.connection.browserSession.send("Playwright.navigate", { url: url2, pageProxyId, frameId: frame._id, referrer }); + return { newDocumentId: result2.loaderId }; + } + _onConsoleMessage(event) { + const { type: type3, level, text: text2, parameters, url: url2, line: lineNumber, column: columnNumber, source: source8 } = event.message; + if (level === "error" && source8 === "javascript") { + const { name, message } = splitErrorMessage(text2); + let stack; + if (event.message.stackTrace) { + stack = text2 + "\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 error = new Error(message); + error.stack = stack; + error.name = name; + this._page.addPageError(error, { + url: url2 || "", + lineNumber: (lineNumber || 1) - 1, + columnNumber: (columnNumber || 1) - 1 + }); + return; + } + let derivedType = type3 || ""; + if (type3 === "log") + derivedType = level; + else if (type3 === "timing") + derivedType = "timeEnd"; + const handles = []; + for (const p of parameters || []) { + let context2; + if (p.objectId) { + const objectId = JSON.parse(p.objectId); + context2 = this._contextIdToContext.get(objectId.injectedScriptId); + } else { + context2 = [...this._contextIdToContext.values()].find((c) => c.frame === this._page.mainFrame()); + } + if (!context2) + return; + handles.push(createHandle4(context2, p)); + } + this._lastConsoleMessage = { + derivedType, + text: text2, + handles, + count: 0, + location: { + url: url2 || "", + lineNumber: (lineNumber || 1) - 1, + columnNumber: (columnNumber || 1) - 1 + } + }; + this._onConsoleRepeatCountUpdated({ count: 1, timestamp: event.message.timestamp }); + } + _onConsoleRepeatCountUpdated(event) { + if (this._lastConsoleMessage) { + const { + derivedType, + text: text2, + handles, + count, + location: location2 + } = this._lastConsoleMessage; + const timestamp = event.timestamp ? event.timestamp * 1e3 : Date.now(); + for (let i = count; i < event.count; ++i) + this._page.addConsoleMessage(null, derivedType, handles, location2, handles.length ? void 0 : text2, timestamp); + this._lastConsoleMessage.count = event.count; + } + } + _onDialog(event) { + this._page.browserContext.dialogManager.dialogDidOpen(new Dialog( + 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 context2 = await this._page.frameManager.frame(event.frameId).mainContext(); + handle = createHandle4(context2, event.element).asElement(); + } catch (e) { + return; + } + await this._page._onFileChooserOpened(handle); + } + static async _setEmulateMedia(session2, mediaType, colorScheme, reducedMotion, forcedColors, contrast) { + const promises = []; + promises.push(session2.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; + } + promises.push(session2.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; + } + promises.push(session2.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; + } + promises.push(session2.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; + } + promises.push(session2.send("Page.overrideUserPreference", { name: "PrefersContrast", value: contrastWk })); + await Promise.all(promises); + } + 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((session2) => _WKPage._setEmulateMedia(session2, emulatedMedia.media, colorScheme, reducedMotion, forcedColors, contrast)); + } + async updateEmulatedViewportSize() { + this._browserContext._validateEmulatedViewport(this._page.emulatedSize()?.viewport); + await this._updateViewport(); + } + async updateUserAgent() { + const contextOptions = this._browserContext._options; + this._updateState("Page.overrideUserAgent", { value: contextOptions.userAgent }); + } + async bringToFront() { + await 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 promises = [ + 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; + promises.push(this._pageProxySession.send("Emulation.setOrientationOverride", { angle })); + } + await Promise.all(promises); + if (!this._browserContext._browser?.options.headful && (hostPlatform === "ubuntu22.04-x64" || hostPlatform.startsWith("debian12"))) + await new Promise((r) => setTimeout(r, 500)); + } + 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((error) => { + if (error instanceof Error && error.message.includes(`Protocol error (Page.goBack): Failed to go`)) + return false; + throw error; + }); + } + goForward() { + return this._session.send("Page.goForward").then(() => true).catch((error) => { + if (error instanceof Error && error.message.includes(`Protocol error (Page.goForward): Failed to go`)) + return false; + throw error; + }); + } + 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 polyfill() { + window.PublicKeyCredential ??= { + async getClientCapabilities() { + return {}; + }, + async isConditionalMediationAvailable() { + return false; + }, + async isUserVerifyingPlatformAuthenticatorAvailable() { + return false; + } + }; + } + return `(${polyfill.toString()})();`; + } + async _updateBootstrapScript() { + await this._updateState("Page.setBootstrapScript", { source: this._calculateBootstrapScript() }); + } + async closePage(runBeforeUnload) { + await this._pageProxySession.sendMayFail("Target.close", { + targetId: this._session.sessionId, + runBeforeUnload + }); + } + async setBackgroundColor(color) { + await this._session.send("Page.setDefaultBackgroundColorOverride", { color }); + } + _toolbarHeight() { + if (this._page.browserContext._browser?.options.headful) { + if (hostPlatform === "mac10.15") + return 55; + if (hostPlatform === "mac26-arm64" || hostPlatform === "mac26") + return 69; + return 59; + } + return 0; + } + 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, format2, documentRect, viewportRect, quality, fitsViewport, scale) { + const rect = documentRect || viewportRect; + const omitDeviceScaleFactor = scale === "css"; + this.validateScreenshotDimension(rect.width, omitDeviceScaleFactor); + this.validateScreenshotDimension(rect.height, omitDeviceScaleFactor); + const result2 = await progress2.race(this._session.send("Page.snapshotRect", { ...rect, coordinateSystem: documentRect ? "Page" : "Viewport", omitDeviceScaleFactor })); + const prefix = "data:image/png;base64,"; + let buffer = Buffer.from(result2.dataURL.substr(prefix.length), "base64"); + if (format2 === "jpeg") + buffer = jpegjs3.encode(PNG2.sync.read(buffer), quality).data; + return buffer; + } + 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; + }); + } + startScreencast(options2) { + this._pageProxySession.send("Screencast.startScreencast", { + quality: options2.quality, + width: options2.width, + height: options2.height, + toolbarHeight: this._toolbarHeight() + }).then(({ generation }) => this._screencastGeneration = generation).catch(() => { + }); + } + stopScreencast() { + this._pageProxySession.sendMayFail("Screencast.stopScreencast"); + } + _onScreencastFrame(event) { + const generation = this._screencastGeneration; + const buffer = Buffer.from(event.data, "base64"); + this._page.screencast.onScreencastFrame({ + buffer, + frameSwapWallTime: event.timestamp ? event.timestamp * 1e3 : Date.now(), + viewportWidth: event.deviceWidth, + viewportHeight: event.deviceHeight + }, () => { + this._pageProxySession.sendMayFail("Screencast.screencastFrameAck", { generation }); + }); + } + rafCountForStablePosition() { + return process.platform === "win32" ? 5 : 1; + } + async getContentQuads(handle) { + const result2 = await this._session.sendMayFail("DOM.getContentQuads", { + objectId: handle._objectId + }); + if (!result2) + return null; + return result2.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(progress2, handle, paths) { + const pageProxyId = this._pageProxySession.sessionId; + const objectId = handle._objectId; + if (this._browserContext._browser?.options.channel === "webkit-wsl") + paths = await progress2.race(Promise.all(paths.map((path59) => translatePathToWSL(path59)))); + await progress2.race(Promise.all([ + this._pageProxySession.connection.browserSession.send("Playwright.grantFileReadAccess", { pageProxyId, paths }), + this._session.send("DOM.setInputFiles", { objectId, paths }) + ])); + } + async adoptElementHandle(handle, to) { + const result2 = await this._session.sendMayFail("DOM.resolveNode", { + objectId: handle._objectId, + executionContextId: to.delegate._contextId + }); + if (!result2 || result2.object.subtype === "null") + throw new Error(kUnableToAdoptErrorMessage); + return createHandle4(to, result2.object); + } + async inputActionEpilogue() { + } + async resetForReuse(progress2) { + } + async getFrameElement(frame) { + const parent = frame.parentFrame(); + if (!parent) + throw new Error("Frame has been detached."); + const context2 = await parent.mainContext(); + const result2 = await this._session.send("DOM.resolveNode", { + frameId: frame._id, + executionContextId: context2.delegate._contextId + }); + if (!result2 || result2.object.subtype === "null") + throw new Error("Frame has been detached."); + return createHandle4(context2, result2.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(session2, 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(session2, event, false); + } + _onRequest(session2, event, intercepted) { + let redirectedFrom = null; + if (event.redirectResponse) { + const request3 = this._requestIdToRequest.get(event.requestId); + if (request3) { + this._handleRequestRedirect(request3, event.requestId, event.redirectResponse, event.timestamp); + redirectedFrom = request3; + } + } + 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(session2, frame, event, redirectedFrom, documentId); + let route2; + if (intercepted) { + route2 = new WKRouteImpl(session2, event.requestId); + request2.request.setRawRequestHeaders(null); + } + this._requestIdToRequest.set(event.requestId, request2); + this._page.frameManager.requestStarted(request2.request, route2); + } + _handleRequestRedirect(request2, requestId, responsePayload, timestamp) { + const response2 = request2.createResponse(responsePayload); + response2._setHttpVersion(null); + response2._securityDetailsFinished(); + response2._serverAddrFinished(); + response2.setResponseHeadersSize(null); + response2.setEncodedBodySize(null); + response2._requestFinished(responsePayload.timing ? helper.secondsToRoundishMillis(timestamp - request2._timestamp) : -1); + this._requestIdToRequest.delete(requestId); + this._page.frameManager.requestReceivedResponse(response2); + this._page.frameManager.reportRequestFinished(request2.request, response2); + } + _onRequestIntercepted(session2, event) { + const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(event.requestId); + if (!requestWillBeSentEvent) { + session2.sendMayFail("Network.interceptWithRequest", { requestId: event.requestId }); + return; + } + this._requestIdToRequestWillBeSentEvent.delete(event.requestId); + this._onRequest(session2, requestWillBeSentEvent, true); + } + _onResponseReceived(session2, event) { + const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(event.requestId); + if (requestWillBeSentEvent) { + this._requestIdToRequestWillBeSentEvent.delete(event.requestId); + this._onRequest(session2, 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(session2, { + requestId: event.requestId, + errorText: "Aborted: 204 No Content", + timestamp: event.timestamp + }); + } + } + _onLoadingFinished(event) { + 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(event?.metrics?.remoteAddress)); + response2._securityDetailsFinished({ + protocol: isLoadedSecurely(response2.url(), response2.timing()) ? event.metrics?.securityConnection?.protocol : void 0, + subjectName: responseReceivedPayload?.response.security?.certificate?.subject, + validFrom: responseReceivedPayload?.response.security?.certificate?.validFrom, + validTo: responseReceivedPayload?.response.security?.certificate?.validUntil + }); + response2._setHttpVersion(event.metrics?.protocol ?? null); + response2.setEncodedBodySize(event.metrics?.responseBodyBytesReceived ?? null); + response2.setResponseHeadersSize(event.metrics?.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(session2, event) { + const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(event.requestId); + if (requestWillBeSentEvent) { + this._requestIdToRequestWillBeSentEvent.delete(event.requestId); + this._onRequest(session2, requestWillBeSentEvent, false); + } + const request2 = this._requestIdToRequest.get(event.requestId); + if (!request2) + return; + const response2 = request2.request._existingResponse(); + if (response2) { + response2._serverAddrFinished(); + response2._securityDetailsFinished(); + response2._setHttpVersion(null); + 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"], + ["screen-wake-lock", "screen-wake-lock"] + ]); + 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; + } + async setDockTile(image) { + } + }; + WKFrame = class { + constructor(page, session2) { + this._sessionListeners = []; + this._initializePromise = null; + this._page = page; + this._session = session2; + } + async initialize() { + if (this._initializePromise) + return this._initializePromise; + this._initializePromise = this._initializeImpl(); + return this._initializePromise; + } + async _initializeImpl() { + this._sessionListeners = [ + eventsHelper.addEventListener(this._session, "Console.messageAdded", (event) => this._page._onConsoleMessage(event)), + eventsHelper.addEventListener(this._session, "Console.messageRepeatCountUpdated", (event) => this._page._onConsoleRepeatCountUpdated(event)) + ]; + await this._session.send("Console.enable"); + } + dispose() { + eventsHelper.removeEventListeners(this._sessionListeners); + this._session.dispose(); + } + }; + } +}); + +// packages/playwright-core/src/server/webkit/wkBrowser.ts +var BROWSER_VERSION, DEFAULT_USER_AGENT, WKBrowser, WKBrowserContext; +var init_wkBrowser = __esm({ + "packages/playwright-core/src/server/webkit/wkBrowser.ts"() { + "use strict"; + init_assert(); + init_browser(); + init_browserContext(); + init_network2(); + init_wkConnection(); + init_wkPage(); + init_webkit(); + BROWSER_VERSION = "26.4"; + 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`; + WKBrowser = class _WKBrowser extends Browser { + 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(kPageProxyMessageReceived, this._onPageProxyMessageReceived.bind(this)); + } + static async connect(parent, transport, options2) { + const browser = new _WKBrowser(parent, transport, options2); + if (options2.__testHookOnConnectToBrowser) + await options2.__testHookOnConnectToBrowser(); + const promises = [ + browser._browserSession.send("Playwright.enable") + ]; + if (options2.persistent) { + options2.persistent.userAgent ||= DEFAULT_USER_AGENT; + browser._defaultContext = new WKBrowserContext(browser, void 0, options2.persistent); + promises.push(browser._defaultContext.initialize()); + } + await Promise.all(promises); + return browser; + } + _onDisconnect() { + for (const wkPage of this._wkPages.values()) + wkPage.didClose(); + this._wkPages.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" && this.attribution.browser?.options.channel !== "webkit-wsl" ? 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 context2 = new WKBrowserContext(this, browserContextId, options2); + await context2.initialize(); + this._contexts.set(browserContextId, context2); + return context2; + } + 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; + let frameId = payload.frameId; + if (!page._page.frameManager.frame(frameId)) + frameId = page._page.mainFrame()._id; + page._page.frameManager.frameAbortedNavigation(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); + } + _onPageProxyCreated(event) { + const pageProxyId = event.pageProxyId; + let context2 = null; + if (event.browserContextId) { + context2 = this._contexts.get(event.browserContextId) || null; + } + if (!context2) + context2 = this._defaultContext; + if (!context2) + 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(context2, pageProxySession, opener || null); + this._wkPages.set(pageProxyId, wkPage); + } + _onPageProxyDestroyed(event) { + const pageProxyId = event.pageProxyId; + const wkPage = this._wkPages.get(pageProxyId); + if (!wkPage) + return; + this._wkPages.delete(pageProxyId); + wkPage.didClose(); + } + _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(); + } + }; + WKBrowserContext = class extends BrowserContext { + constructor(browser, browserContextId, options2) { + super(browser, options2, browserContextId); + this._validateEmulatedViewport(options2.viewport); + this.authenticateProxyViaHeader(); + } + async initialize() { + assert(!this._wkPages().length); + const browserContextId = this._browserContextId; + const promises = [super.initialize()]; + promises.push(this._browser._browserSession.send("Playwright.setDownloadBehavior", { + behavior: this._options.acceptDownloads === "accept" ? "allow" : "deny", + downloadPath: this._browser.options.channel === "webkit-wsl" ? await translatePathToWSL(this._browser.options.downloadsPath) : this._browser.options.downloadsPath, + browserContextId + })); + if (this._options.ignoreHTTPSErrors || this._options.internalIgnoreHTTPSErrors) + promises.push(this._browser._browserSession.send("Playwright.setIgnoreCertificateErrors", { browserContextId, ignore: true })); + if (this._options.locale) + promises.push(this._browser._browserSession.send("Playwright.setLanguages", { browserContextId, languages: [this._options.locale] })); + if (this._options.geolocation) + promises.push(this.setGeolocation(this._options.geolocation)); + if (this._options.offline) + promises.push(this.doUpdateOffline()); + if (this._options.httpCredentials) + promises.push(this.innerSetHTTPCredentials(this._options.httpCredentials)); + await Promise.all(promises); + } + _wkPages() { + return Array.from(this._browser._wkPages.values()).filter((wkPage) => wkPage._browserContext === this); + } + possiblyUninitializedPages() { + return this._wkPages().map((wkPage) => wkPage._page); + } + async doCreateNewPage() { + const { pageProxyId } = await this._browser._browserSession.send("Playwright.createPage", { browserContextId: this._browserContextId }); + return this._browser._wkPages.get(pageProxyId)._page; + } + async doGetCookies(urls) { + const { cookies } = await this._browser._browserSession.send("Playwright.getAllCookies", { browserContextId: this._browserContextId }); + return filterCookies(cookies.map((c) => { + const { name, value: value2, domain, path: path59, expires, httpOnly, secure, sameSite } = c; + const copy = { + name, + value: value2, + domain, + path: path59, + expires: expires === -1 ? -1 : expires / 1e3, + httpOnly, + secure, + sameSite + }; + return copy; + }), urls); + } + async addCookies(cookies) { + const cc = rewriteCookies(cookies).map((c) => { + const { name, value: value2, domain, path: path59, expires, httpOnly, secure, sameSite } = c; + const copy = { + name, + value: value2, + domain, + path: path59, + expires: expires && expires !== -1 ? expires * 1e3 : expires, + httpOnly, + secure, + sameSite, + session: expires === -1 || expires === void 0 + }; + return copy; + }); + 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 doUpdateExtraHTTPHeaders() { + 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 doUpdateOffline() { + 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 doUpdateDefaultViewport() { + } + async doUpdateDefaultEmulatedMedia() { + } + 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) { + return "close-browser"; + } 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.`); + } + }; + } +}); + +// packages/playwright-core/src/server/webkit/webkit.ts +async function translatePathToWSL(path59) { + const { stdout } = await spawnAsync("wsl.exe", ["-d", "playwright", "--cd", "/home/pwuser", "wslpath", path59.replace(/\\/g, "\\\\")]); + return stdout.toString().trim(); +} +var import_path30, WebKit; +var init_webkit = __esm({ + "packages/playwright-core/src/server/webkit/webkit.ts"() { + "use strict"; + import_path30 = __toESM(require("path")); + init_ascii(); + init_spawnAsync(); + init_wkConnection(); + init_browserType(); + init_wkBrowser(); + WebKit = class extends BrowserType { + constructor(parent) { + super(parent, "webkit"); + } + connectToTransport(transport, options2) { + return WKBrowser.connect(this.attribution.playwright, transport, options2); + } + amendEnvironment(env, userDataDir, isPersistent, options2) { + return { + ...env, + CURL_COOKIE_JAR_PATH: process.platform === "win32" && isPersistent ? import_path30.default.join(userDataDir, "cookiejar.db") : void 0 + }; + } + doRewriteStartupLog(logs) { + if (logs.includes("Failed to open display") || logs.includes("cannot open display")) + logs = "\n" + wrapInASCIIBox(kNoXServerRunningError, 1); + return logs; + } + attemptToGracefullyCloseBrowser(transport) { + transport.send({ method: "Playwright.close", params: {}, id: kBrowserCloseMessageId4 }); + } + async 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" && options2.channel !== "webkit-wsl") + webkitArguments.push("--disable-accelerated-compositing"); + if (headless) + webkitArguments.push("--headless"); + if (isPersistent) + webkitArguments.push(`--user-data-dir=${options2.channel === "webkit-wsl" ? await translatePathToWSL(userDataDir) : 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" || process.platform === "win32" && options2.channel === "webkit-wsl") { + 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; + } + }; + } +}); + +// packages/playwright-core/src/server/playwright.ts +var playwright_exports = {}; +__export(playwright_exports, { + Playwright: () => Playwright, + createPlaywright: () => createPlaywright +}); +function createPlaywright(options2) { + return new Playwright(options2); +} +var Playwright; +var init_playwright = __esm({ + "packages/playwright-core/src/server/playwright.ts"() { + "use strict"; + init_android(); + init_backendAdb(); + init_bidiChromium(); + init_bidiFirefox(); + init_chromium(); + init_debugController(); + init_electron(); + init_firefox(); + init_instrumentation(); + init_webkit(); + Playwright = class extends SdkObject { + constructor(options2) { + super(createRootSdkObject(), void 0, "Playwright"); + this._allPages = /* @__PURE__ */ new Set(); + this._allBrowsers = /* @__PURE__ */ new Set(); + this.options = options2; + this.attribution.playwright = this; + this.instrumentation.addListener({ + onBrowserOpen: (browser) => this._allBrowsers.add(browser), + onBrowserClose: (browser) => this._allBrowsers.delete(browser), + onPageOpen: (page) => this._allPages.add(page), + onPageClose: (page) => this._allPages.delete(page) + }, null); + this.chromium = new Chromium(this, new BidiChromium(this)); + this.firefox = new Firefox(this, new BidiFirefox(this)); + this.webkit = new WebKit(this); + this.electron = new Electron(this); + this.android = new Android(this, new AdbBackend()); + this.debugController = new DebugController(this); + } + allBrowsers() { + return [...this._allBrowsers]; + } + allPages() { + return [...this._allPages]; + } + }; + } +}); + +// packages/playwright-core/src/server/recorder/recorderApp.ts +function determinePrimaryGeneratorId(sdkLanguage) { + for (const language of languageSet()) { + if (language.highlighter === sdkLanguage) + return language.id; + } + return sdkLanguage; +} +function findPageByGuid(context2, guid) { + return context2.pages().find((p) => p.guid === guid); +} +function createRecorderFrontend(page) { + return new Proxy({}, { + get: (_target, prop) => { + if (typeof prop !== "string") + return void 0; + return (params2) => { + page.mainFrame().evaluateExpression(nullProgress, ((event) => { + window.dispatch(event); + }).toString(), { isFunction: true }, { method: prop, params: params2 }).catch(() => { + }); + }; + } + }); +} +var import_fs30, import_path31, mime7, RecorderApp, ProgrammaticRecorderApp, recorderAppSymbol; +var init_recorderApp = __esm({ + "packages/playwright-core/src/server/recorder/recorderApp.ts"() { + "use strict"; + import_fs30 = __toESM(require("fs")); + import_path31 = __toESM(require("path")); + init_debug(); + init_package(); + init_launchApp(); + init_launchApp(); + init_progress(); + init_throttledFile(); + init_languages(); + init_recorderUtils(); + init_language(); + init_recorder(); + init_browserContext(); + mime7 = require("./utilsBundle").mime; + RecorderApp = class _RecorderApp { + constructor(recorder, params2, page, wsEndpointForTest) { + this._throttledOutputFile = null; + this._actions = []; + this._userSources = []; + this._recorderSources = []; + this._page = page; + this._recorder = recorder; + this._frontend = createRecorderFrontend(page); + this.wsEndpointForTest = wsEndpointForTest; + this._languageGeneratorOptions = { + browserName: params2.browserName, + launchOptions: { headless: false, ...params2.launchOptions, tracesDir: void 0 }, + contextOptions: { ...params2.contextOptions }, + deviceName: params2.device, + saveStorage: params2.saveStorage + }; + this._throttledOutputFile = params2.outputFile ? new ThrottledFile(params2.outputFile) : null; + this._primaryGeneratorId = process.env.TEST_INSPECTOR_LANGUAGE || params2.language || determinePrimaryGeneratorId(params2.sdkLanguage); + this._selectedGeneratorId = this._primaryGeneratorId; + for (const languageGenerator of languageSet()) { + if (languageGenerator.id === this._primaryGeneratorId) + this._recorder.setLanguage(languageGenerator.highlighter); + } + } + async _init(inspectedContext) { + await syncLocalStorageWithSettings(this._page, "recorder"); + const controller = new ProgressController(); + await controller.run(async (progress2) => { + await this._page.addRequestInterceptor(progress2, (route2) => { + if (!route2.request().url().startsWith("https://playwright/")) { + route2.continue({ isFallback: true }).catch(() => { + }); + return; + } + const uri = route2.request().url().substring("https://playwright/".length); + const file = import_path31.default.join(libPath("vite", "recorder"), uri); + import_fs30.default.promises.readFile(file).then((buffer) => { + route2.fulfill({ + status: 200, + headers: [ + { name: "Content-Type", value: mime7.getType(import_path31.default.extname(file)) || "application/octet-stream" } + ], + body: buffer.toString("base64"), + isBase64: true + }).catch(() => { + }); + }); + }); + await this._createDispatcher(progress2); + this._page.once("close", () => { + this._recorder.close(); + this._page.browserContext.close(nullProgress, { reason: "Recorder window closed" }).catch(() => { + }); + delete inspectedContext[recorderAppSymbol]; + }); + await this._page.mainFrame().goto(progress2, "https://playwright/index.html"); + }); + const url2 = this._recorder.url(); + if (url2) + this._frontend.pageNavigated({ url: url2 }); + this._frontend.modeChanged({ mode: this._recorder.mode() }); + this._frontend.pauseStateChanged({ paused: this._recorder.paused() }); + this._updateActions("reveal"); + this._onUserSourcesChanged(this._recorder.userSources(), this._recorder.pausedSourceId()); + this._frontend.callLogsUpdated({ callLogs: this._recorder.callLog() }); + this._wireListeners(this._recorder); + } + async _createDispatcher(progress2) { + const dispatcher = { + clear: async () => { + this._actions = []; + this._updateActions("reveal"); + this._recorder.clear(); + }, + fileChanged: async (params2) => { + const source8 = [...this._recorderSources, ...this._userSources].find((s) => s.id === params2.fileId); + if (source8) { + if (source8.isRecorded) + this._selectedGeneratorId = source8.id; + await this._recorder.setLanguage(source8.language); + } + }, + setAutoExpect: async (params2) => { + this._languageGeneratorOptions.generateAutoExpect = params2.autoExpect; + this._updateActions(); + }, + setMode: async (params2) => { + await this._recorder.setMode(params2.mode); + }, + resume: async () => { + this._recorder.resume(); + }, + pause: async () => { + this._recorder.pause(); + }, + step: async () => { + this._recorder.step(); + }, + highlightRequested: async (params2) => { + if (params2.selector) + await this._recorder.setHighlightedSelector(params2.selector); + if (params2.ariaTemplate) + await this._recorder.setHighlightedAriaTemplate(params2.ariaTemplate); + } + }; + await this._page.exposeBinding(progress2, "sendCommand", async (_, data) => { + const { method, params: params2 } = data; + return await dispatcher[method].call(dispatcher, params2); + }); + } + static async show(context2, params2) { + if (process.env.PW_CODEGEN_NO_INSPECTOR) + return; + const recorder = await Recorder.forContext(context2, params2); + if (params2.recorderMode === "api") { + const browserName = context2._browser.options.name; + await ProgrammaticRecorderApp.run(context2, recorder, browserName, params2); + return; + } + await _RecorderApp._show(recorder, context2, params2); + } + async close() { + await this._page.close(nullProgress); + } + static showInspectorNoReply(context2) { + if (process.env.PW_CODEGEN_NO_INSPECTOR) + return; + void Recorder.forContext(context2, {}).then((recorder) => _RecorderApp._show(recorder, context2, {})).catch(() => { + }); + } + static async _show(recorder, inspectedContext, params2) { + if (inspectedContext[recorderAppSymbol]) + return; + inspectedContext[recorderAppSymbol] = true; + const sdkLanguage = inspectedContext._browser.sdkLanguage(); + const isChromium = inspectedContext._browser.options.browserType === "chromium"; + const headed = !!inspectedContext._browser.options.headful; + const { createPlaywright: createPlaywright2 } = (init_playwright(), __toCommonJS(playwright_exports)); + const recorderPlaywright = createPlaywright2({ sdkLanguage: "javascript", isInternalPlaywright: true }); + const { context: appContext, page } = await launchApp(recorderPlaywright.chromium, { + sdkLanguage, + windowSize: { width: 600, height: 600 }, + windowPosition: { x: 1020, y: 10 }, + persistentContextOptions: { + noDefaultViewport: true, + headless: !!process.env.PWTEST_CLI_HEADLESS || isUnderTest() && !headed, + args: isUnderTest() ? ["--remote-debugging-port=0"] : void 0, + handleSIGINT: params2.handleSIGINT, + executablePath: isChromium ? inspectedContext._browser.options.customExecutablePath : void 0, + // Use the same channel as the inspected context to guarantee that the browser is installed. + channel: isChromium ? inspectedContext._browser.options.channel : void 0 + } + }); + const controller = new ProgressController(); + await controller.run(async (progress2) => { + await appContext._browser._defaultContext.loadDefaultContextAsIs(progress2); + }); + const appParams = { + browserName: inspectedContext._browser.options.name, + sdkLanguage: inspectedContext._browser.sdkLanguage(), + wsEndpointForTest: inspectedContext._browser.options.wsEndpoint, + headed: !!inspectedContext._browser.options.headful, + executablePath: isChromium ? inspectedContext._browser.options.customExecutablePath : void 0, + channel: isChromium ? inspectedContext._browser.options.channel : void 0, + ...params2 + }; + const recorderApp = new _RecorderApp(recorder, appParams, page, appContext._browser.options.wsEndpoint); + await recorderApp._init(inspectedContext); + inspectedContext.recorderAppForTest = recorderApp; + } + _wireListeners(recorder) { + recorder.on(RecorderEvent.ActionAdded, (action) => { + this._onActionAdded(action); + }); + recorder.on(RecorderEvent.SignalAdded, (signal) => { + this._onSignalAdded(signal); + }); + recorder.on(RecorderEvent.PageNavigated, (url2) => { + this._frontend.pageNavigated({ url: url2 }); + }); + recorder.on(RecorderEvent.ContextClosed, () => { + this._throttledOutputFile?.flush(); + this._page.browserContext.close(nullProgress, { reason: "Recorder window closed" }).catch(() => { + }); + }); + recorder.on(RecorderEvent.ModeChanged, (mode) => { + this._frontend.modeChanged({ mode }); + }); + recorder.on(RecorderEvent.PausedStateChanged, (paused) => { + this._frontend.pauseStateChanged({ paused }); + }); + recorder.on(RecorderEvent.UserSourcesChanged, (sources, pausedSourceId) => { + this._onUserSourcesChanged(sources, pausedSourceId); + }); + recorder.on(RecorderEvent.ElementPicked, (elementInfo, userGesture) => { + if (userGesture) + this._page.bringToFront(nullProgress).catch(() => { + }); + this._frontend.elementPicked({ elementInfo, userGesture }); + }); + recorder.on(RecorderEvent.CallLogsUpdated, (callLogs) => { + this._frontend.callLogsUpdated({ callLogs }); + }); + } + _onActionAdded(action) { + this._actions.push(action); + this._updateActions("reveal"); + } + _onSignalAdded(signal) { + const lastAction = this._actions.findLast((a) => a.frame.pageGuid === signal.frame.pageGuid); + if (lastAction) + lastAction.action.signals.push(signal.signal); + this._updateActions(); + } + _onUserSourcesChanged(sources, pausedSourceId) { + if (!sources.length && !this._userSources.length) + return; + this._userSources = sources; + this._pushAllSources(); + this._revealSource(pausedSourceId); + } + _pushAllSources() { + const sources = [...this._userSources, ...this._recorderSources]; + this._frontend.sourcesUpdated({ sources }); + } + _revealSource(sourceId) { + if (!sourceId) + return; + this._frontend.sourceRevealRequested({ sourceId }); + } + _updateActions(reveal) { + const recorderSources = []; + const actions = collapseActions(this._actions); + let revealSourceId; + for (const languageGenerator of languageSet()) { + const { header, footer, actionTexts, text: text2 } = generateCode(actions, languageGenerator, this._languageGeneratorOptions); + const source8 = { + isRecorded: true, + label: languageGenerator.name, + group: languageGenerator.groupName, + id: languageGenerator.id, + text: text2, + header, + footer, + actions: actionTexts, + language: languageGenerator.highlighter, + highlight: [] + }; + source8.revealLine = text2.split("\n").length - 1; + recorderSources.push(source8); + if (languageGenerator.id === this._primaryGeneratorId) + this._throttledOutputFile?.setContent(source8.text); + if (reveal === "reveal" && source8.id === this._selectedGeneratorId) + revealSourceId = source8.id; + } + this._recorderSources = recorderSources; + this._pushAllSources(); + this._revealSource(revealSourceId); + } + }; + ProgrammaticRecorderApp = class { + static async run(inspectedContext, recorder, browserName, params2) { + let lastAction = null; + const languages = [...languageSet()]; + const languageGeneratorOptions = { + browserName, + launchOptions: { headless: false, ...params2.launchOptions, tracesDir: void 0 }, + contextOptions: { ...params2.contextOptions }, + deviceName: params2.device, + saveStorage: params2.saveStorage + }; + const languageGenerator = languages.find((l) => l.id === params2.language) ?? languages.find((l) => l.id === "playwright-test"); + recorder.on(RecorderEvent.ActionAdded, (action) => { + const page = findPageByGuid(inspectedContext, action.frame.pageGuid); + if (!page) + return; + const { actionTexts } = generateCode([action], languageGenerator, languageGeneratorOptions); + if (!lastAction || !shouldMergeAction(action, lastAction)) + inspectedContext.emit(BrowserContext.Events.RecorderEvent, { event: "actionAdded", data: action, page, code: actionTexts.join("\n") }); + else + inspectedContext.emit(BrowserContext.Events.RecorderEvent, { event: "actionUpdated", data: action, page, code: actionTexts.join("\n") }); + lastAction = action; + }); + recorder.on(RecorderEvent.SignalAdded, (signal) => { + const page = findPageByGuid(inspectedContext, signal.frame.pageGuid); + if (!page) + return; + inspectedContext.emit(BrowserContext.Events.RecorderEvent, { event: "signalAdded", data: signal, page, code: "" }); + }); + } + }; + recorderAppSymbol = Symbol("recorderApp"); + } +}); + +// packages/playwright-core/src/server/selectors.ts +var Selectors; +var init_selectors = __esm({ + "packages/playwright-core/src/server/selectors.ts"() { + "use strict"; + init_selectorParser(); + init_crypto(); + Selectors = class { + constructor(engines, testIdAttributeName2) { + this.guid = `selectors@${createGuid()}`; + this._builtinEngines = /* @__PURE__ */ new Set([ + "css", + "css:light", + "xpath", + "xpath:light", + "_react", + "_vue", + "text", + "text:light", + "id", + "id:light", + "data-testid", + "data-testid:light", + "data-test-id", + "data-test-id:light", + "data-test", + "data-test:light", + "nth", + "visible", + "internal:control", + "internal:has", + "internal:has-not", + "internal:has-text", + "internal:has-not-text", + "internal:and", + "internal:or", + "internal:chain", + "role", + "internal:attr", + "internal:label", + "internal:text", + "internal:role", + "internal:testid", + "internal:describe", + "aria-ref" + ]); + this._builtinEnginesInMainWorld = /* @__PURE__ */ new Set([ + "_react", + "_vue" + ]); + this._engines = /* @__PURE__ */ new Map(); + this._testIdAttributeName = testIdAttributeName2 ?? "data-testid"; + for (const engine of engines) + this.register(engine); + } + register(engine) { + if (!engine.name.match(/^[a-zA-Z_0-9-]+$/)) + throw new Error("Selector engine name may only contain [a-zA-Z0-9_] characters"); + if (this._builtinEngines.has(engine.name) || engine.name === "zs" || engine.name === "zs:light") + throw new Error(`"${engine.name}" is a predefined selector engine`); + if (this._engines.has(engine.name)) + throw new Error(`"${engine.name}" selector engine has been already registered`); + this._engines.set(engine.name, engine); + } + testIdAttributeName() { + return this._testIdAttributeName; + } + setTestIdAttributeName(testIdAttributeName2) { + this._testIdAttributeName = testIdAttributeName2; + } + parseSelector(selector, strict) { + const parsed = typeof selector === "string" ? parseSelector(selector) : selector; + let needsMainWorld = false; + visitAllSelectorParts(parsed, (part) => { + const name = part.name; + const custom = this._engines.get(name); + if (!custom && !this._builtinEngines.has(name)) + throw new InvalidSelectorError(`Unknown engine "${name}" while parsing selector ${stringifySelector(parsed)}`); + if (custom && !custom.contentScript) + needsMainWorld = true; + if (this._builtinEnginesInMainWorld.has(name)) + needsMainWorld = true; + }); + return { + parsed, + world: needsMainWorld ? "main" : "utility", + strict + }; + } + }; + } +}); + +// packages/playwright-core/src/generated/storageScriptSource.ts +var source6; +var init_storageScriptSource = __esm({ + "packages/playwright-core/src/generated/storageScriptSource.ts"() { + "use strict"; + source6 = '\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/storageScript.ts\nvar storageScript_exports = {};\n__export(storageScript_exports, {\n StorageScript: () => StorageScript\n});\nmodule.exports = __toCommonJS(storageScript_exports);\n\n// packages/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}\nfunction isArrayBuffer(obj) {\n try {\n return obj instanceof ArrayBuffer || Object.prototype.toString.call(obj) === "[object ArrayBuffer]";\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 if ("ab" in value)\n return base64ToTypedArray(value.ab.b, Uint8Array).buffer;\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 if (isArrayBuffer(value))\n return { ab: { b: typedArrayToBase64(new Uint8Array(value)) } };\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/storageScript.ts\nvar StorageScript = class {\n constructor(isFirefox) {\n this._isFirefox = isFirefox;\n this._global = globalThis;\n }\n _idbRequestToPromise(request) {\n return new Promise((resolve, reject) => {\n request.addEventListener("success", () => resolve(request.result));\n request.addEventListener("error", () => reject(request.error));\n });\n }\n _isPlainObject(v) {\n const ctor = v == null ? void 0 : v.constructor;\n if (this._isFirefox) {\n const constructorImpl = ctor == null ? void 0 : ctor.toString();\n if ((constructorImpl == null ? void 0 : constructorImpl.startsWith("function Object() {")) && (constructorImpl == null ? void 0 : constructorImpl.includes("[native code]")))\n return true;\n }\n return ctor === Object;\n }\n _trySerialize(value) {\n let trivial = true;\n const encoded = serializeAsCallArgument(value, (v) => {\n const isTrivial = this._isPlainObject(v) || Array.isArray(v) || typeof v === "string" || typeof v === "number" || typeof v === "boolean" || Object.is(v, null);\n if (!isTrivial)\n trivial = false;\n return { fallThrough: v };\n });\n if (trivial)\n return { trivial: value };\n return { encoded };\n }\n async _collectDB(dbInfo) {\n if (!dbInfo.name)\n throw new Error("Database name is empty");\n if (!dbInfo.version)\n throw new Error("Database version is unset");\n const db = await this._idbRequestToPromise(indexedDB.open(dbInfo.name));\n if (db.objectStoreNames.length === 0)\n return { name: dbInfo.name, version: dbInfo.version, stores: [] };\n const transaction = db.transaction(db.objectStoreNames, "readonly");\n const stores = await Promise.all([...db.objectStoreNames].map(async (storeName) => {\n const objectStore = transaction.objectStore(storeName);\n const keys = await this._idbRequestToPromise(objectStore.getAllKeys());\n const records = await Promise.all(keys.map(async (key) => {\n const record = {};\n if (objectStore.keyPath === null) {\n const { encoded: encoded2, trivial: trivial2 } = this._trySerialize(key);\n if (trivial2)\n record.key = trivial2;\n else\n record.keyEncoded = encoded2;\n }\n const value = await this._idbRequestToPromise(objectStore.get(key));\n const { encoded, trivial } = this._trySerialize(value);\n if (trivial)\n record.value = trivial;\n else\n record.valueEncoded = encoded;\n return record;\n }));\n const indexes = [...objectStore.indexNames].map((indexName) => {\n const index = objectStore.index(indexName);\n return {\n name: index.name,\n keyPath: typeof index.keyPath === "string" ? index.keyPath : void 0,\n keyPathArray: Array.isArray(index.keyPath) ? index.keyPath : void 0,\n multiEntry: index.multiEntry,\n unique: index.unique\n };\n });\n return {\n name: storeName,\n records,\n indexes,\n autoIncrement: objectStore.autoIncrement,\n keyPath: typeof objectStore.keyPath === "string" ? objectStore.keyPath : void 0,\n keyPathArray: Array.isArray(objectStore.keyPath) ? objectStore.keyPath : void 0\n };\n }));\n return {\n name: dbInfo.name,\n version: dbInfo.version,\n stores\n };\n }\n async collect(recordIndexedDB) {\n const localStorage = Object.keys(this._global.localStorage).map((name) => ({ name, value: this._global.localStorage.getItem(name) }));\n if (!recordIndexedDB)\n return { localStorage };\n try {\n const databases = await this._global.indexedDB.databases();\n const indexedDB2 = await Promise.all(databases.map((db) => this._collectDB(db)));\n return { localStorage, indexedDB: indexedDB2 };\n } catch (e) {\n throw new Error("Unable to serialize IndexedDB: " + e.message);\n }\n }\n async _restoreDB(dbInfo) {\n const openRequest = this._global.indexedDB.open(dbInfo.name, dbInfo.version);\n openRequest.addEventListener("upgradeneeded", () => {\n var _a, _b;\n const db2 = openRequest.result;\n for (const store of dbInfo.stores) {\n const objectStore = db2.createObjectStore(store.name, { autoIncrement: store.autoIncrement, keyPath: (_a = store.keyPathArray) != null ? _a : store.keyPath });\n for (const index of store.indexes)\n objectStore.createIndex(index.name, (_b = index.keyPathArray) != null ? _b : index.keyPath, { unique: index.unique, multiEntry: index.multiEntry });\n }\n });\n const db = await this._idbRequestToPromise(openRequest);\n if (db.objectStoreNames.length === 0)\n return;\n const transaction = db.transaction(db.objectStoreNames, "readwrite");\n await Promise.all(dbInfo.stores.map(async (store) => {\n const objectStore = transaction.objectStore(store.name);\n await Promise.all(store.records.map(async (record) => {\n var _a, _b;\n await this._idbRequestToPromise(\n objectStore.add(\n (_a = record.value) != null ? _a : parseEvaluationResultValue(record.valueEncoded),\n (_b = record.key) != null ? _b : parseEvaluationResultValue(record.keyEncoded)\n )\n );\n }));\n }));\n }\n async restore(originState) {\n var _a, _b, _c;\n const registrations = this._global.navigator.serviceWorker ? await this._global.navigator.serviceWorker.getRegistrations() : [];\n await Promise.all(registrations.map(async (r) => {\n if (!r.installing && !r.waiting && !r.active)\n r.unregister().catch(() => {\n });\n else\n await r.unregister().catch(() => {\n });\n }));\n try {\n for (const db of await ((_b = (_a = this._global.indexedDB).databases) == null ? void 0 : _b.call(_a)) || []) {\n if (db.name)\n this._global.indexedDB.deleteDatabase(db.name);\n }\n await Promise.all(((_c = originState == null ? void 0 : originState.indexedDB) != null ? _c : []).map((dbInfo) => this._restoreDB(dbInfo)));\n } catch (e) {\n throw new Error("Unable to restore IndexedDB: " + e.message);\n }\n this._global.sessionStorage.clear();\n this._global.localStorage.clear();\n for (const { name, value } of (originState == null ? void 0 : originState.localStorage) || [])\n this._global.localStorage.setItem(name, value);\n }\n};\n'; + } +}); + +// packages/playwright-core/src/server/browserContext.ts +function validateBrowserContextOptions(options2, browserOptions) { + if (options2.noDefaultViewport && options2.deviceScaleFactor !== void 0) + throw new Error(`"deviceScaleFactor" option is not supported with null "viewport"`); + if (options2.noDefaultViewport && !!options2.isMobile) + throw new Error(`"isMobile" option is not supported with null "viewport"`); + if (options2.acceptDownloads === void 0 && browserOptions.name !== "electron") + options2.acceptDownloads = "accept"; + else if (options2.acceptDownloads === void 0 && browserOptions.name === "electron") + options2.acceptDownloads = "internal-browser-default"; + if (!options2.viewport && !options2.noDefaultViewport) + options2.viewport = { width: 1280, height: 720 }; + if (options2.proxy) + options2.proxy = normalizeProxySettings(options2.proxy); + verifyGeolocation(options2.geolocation); +} +function verifyGeolocation(geolocation) { + if (!geolocation) + return; + geolocation.accuracy = geolocation.accuracy || 0; + const { longitude, latitude, accuracy } = geolocation; + if (longitude < -180 || longitude > 180) + throw new Error(`geolocation.longitude: precondition -180 <= LONGITUDE <= 180 failed.`); + if (latitude < -90 || latitude > 90) + throw new Error(`geolocation.latitude: precondition -90 <= LATITUDE <= 90 failed.`); + if (accuracy < 0) + throw new Error(`geolocation.accuracy: precondition 0 <= ACCURACY failed.`); +} +function verifyClientCertificates(clientCertificates) { + if (!clientCertificates) + return; + for (const cert of clientCertificates) { + if (!cert.origin) + throw new Error(`clientCertificates.origin is required`); + if (!cert.cert && !cert.key && !cert.passphrase && !cert.pfx) + throw new Error("None of cert, key, passphrase or pfx is specified"); + if (cert.cert && !cert.key) + throw new Error("cert is specified without key"); + if (!cert.cert && cert.key) + throw new Error("key is specified without cert"); + if (cert.pfx && (cert.cert || cert.key)) + throw new Error("pfx is specified together with cert, key or passphrase"); + } +} +function normalizeProxySettings(proxy) { + let { server, bypass } = proxy; + let url2; + try { + url2 = new URL(server); + if (!url2.host || !url2.protocol) + url2 = new URL("http://" + server); + } catch (e) { + url2 = new URL("http://" + server); + } + if (url2.protocol === "socks4:" && (proxy.username || proxy.password)) + throw new Error(`Socks4 proxy protocol does not support authentication`); + if (url2.protocol === "socks5:" && (proxy.username || proxy.password)) + throw new Error(`Browser does not support socks5 proxy authentication`); + server = url2.protocol + "//" + url2.host; + if (bypass) + bypass = bypass.split(",").map((t) => t.trim()).join(","); + return { ...proxy, server, bypass }; +} +var import_fs31, BrowserContextEvent, BrowserContext, paramsThatAllowContextReuse, defaultNewContextParamValues; +var init_browserContext = __esm({ + "packages/playwright-core/src/server/browserContext.ts"() { + "use strict"; + import_fs31 = __toESM(require("fs")); + init_stackTrace(); + init_debug(); + init_clock(); + init_debugger(); + init_dialog(); + init_fetch(); + init_helper(); + init_instrumentation(); + init_network2(); + init_page(); + init_page(); + init_recorderApp(); + init_selectors(); + init_tracing(); + init_storageScriptSource(); + init_progress(); + BrowserContextEvent = { + Console: "console", + Close: "close", + 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 + PageError: "pageerror", + Request: "request", + Response: "response", + RequestFailed: "requestfailed", + RequestFinished: "requestfinished", + RequestAborted: "requestaborted", + RequestFulfilled: "requestfulfilled", + RequestContinued: "requestcontinued", + BeforeClose: "beforeclose", + RecorderEvent: "recorderevent", + PageClosed: "pageclosed", + InternalFrameNavigatedToNewDocument: "internalframenavigatedtonewdocument" + }; + BrowserContext = class _BrowserContext extends SdkObject { + constructor(browser, options2, browserContextId) { + super(browser, "browser-context"); + this._pageBindings = /* @__PURE__ */ new Map(); + this.requestInterceptors = []; + this._closedStatus = "open"; + this._permissions = /* @__PURE__ */ new Map(); + this._downloads = /* @__PURE__ */ new Set(); + this._origins = /* @__PURE__ */ new Set(); + this._tempDirs = []; + this._creatingStorageStatePage = false; + this.initScripts = []; + this._routesInFlight = /* @__PURE__ */ new Set(); + this._consoleApiExposed = false; + this.attribution.context = this; + this._browser = browser; + this._options = options2; + this._browserContextId = browserContextId; + this._isPersistentContext = !browserContextId; + this._closePromise = new Promise((fulfill) => this._closePromiseFulfill = fulfill); + this._selectors = new Selectors(options2.selectorEngines || [], options2.testIdAttributeName); + this.fetchRequest = new BrowserContextAPIRequestContext(this); + this.tracing = new Tracing(this, browser.options.tracesDir); + this.clock = new Clock(this); + this.dialogManager = new DialogManager(this.instrumentation); + } + static { + this.Events = BrowserContextEvent; + } + isPersistentContext() { + return this._isPersistentContext; + } + selectors() { + return this._selectors; + } + async initialize() { + if (this.attribution.playwright.options.isInternalPlaywright) + return; + this._debugger = new Debugger(this); + const shouldEnableDebugger = !this.attribution.playwright.options.isServer && (isUnderTest() || !!this._browser.options.headful); + if (shouldEnableDebugger) { + this._debugger.setPauseAt(); + this._debugger.on(Debugger.Events.PausedStateChanged, () => { + if (this._debugger.isPaused()) + RecorderApp.showInspectorNoReply(this); + }); + } + if (debugMode() === "inspector") { + this._debugger.setPauseAt({ next: true }); + await RecorderApp.show(this, { pauseOnNextStatement: true }); + } + if (debugMode() === "console") + await this._exposeConsoleApi(); + if (this._options.serviceWorkers === "block") + await this.addInitScript(nullProgress, ` +if (navigator.serviceWorker) navigator.serviceWorker.register = async () => { console.warn('Service Worker registration blocked by Playwright'); }; +`); + if (this._options.permissions) + await this.grantPermissions(this._options.permissions); + } + debugger() { + return this._debugger; + } + async exposeConsoleApi(progress2) { + await progress2.race(this._exposeConsoleApi()); + } + async _exposeConsoleApi() { + if (this._consoleApiExposed) + return; + this._consoleApiExposed = true; + await this.extendInjectedScript(` + function installConsoleApi(injectedScript) { injectedScript.consoleApi.install(); } + module.exports = { default: () => installConsoleApi }; + `); + } + canResetForReuse() { + if (this._closedStatus !== "open") + return false; + return true; + } + static reusableContextHash(params2) { + const paramsCopy = { ...params2 }; + if (paramsCopy.selectorEngines?.length === 0) + delete paramsCopy.selectorEngines; + for (const k of Object.keys(paramsCopy)) { + const key = k; + if (paramsCopy[key] === defaultNewContextParamValues[key]) + delete paramsCopy[key]; + } + for (const key of paramsThatAllowContextReuse) + delete paramsCopy[key]; + return JSON.stringify(paramsCopy); + } + async resetForReuse(progress2, params2) { + await this.tracing.resetForReuse(progress2); + if (params2) { + for (const key of paramsThatAllowContextReuse) + this._options[key] = params2[key]; + if (params2.testIdAttributeName) + this.selectors().setTestIdAttributeName(params2.testIdAttributeName); + } + let page = this.pages()[0]; + const otherPages = this.possiblyUninitializedPages().filter((p) => p !== page); + for (const p of otherPages) + await p.close(progress2); + if (page && page.hasCrashed()) { + await page.close(progress2); + page = void 0; + } + await page?.mainFrame().gotoImpl(progress2, "about:blank", {}); + await this.clock.uninstall(progress2); + await progress2.race(this.setUserAgent(this._options.userAgent)); + await progress2.race(this.doUpdateDefaultEmulatedMedia()); + await progress2.race(this.doUpdateDefaultViewport()); + await this.setStorageState(progress2, this._options.storageState, "resetForReuse"); + await page?.resetForReuse(progress2); + } + browserClosed() { + for (const page of this.pages()) + page._didClose(); + this._didCloseInternal(); + } + _didCloseInternal() { + if (this._closedStatus === "closed") { + return; + } + this._clientCertificatesProxy?.close().catch(() => { + }); + this.tracing.abort(); + if (this._isPersistentContext) + this.onClosePersistent(); + this._closePromiseFulfill(new Error("Context closed")); + this.emit(_BrowserContext.Events.Close); + } + pages() { + return this.possiblyUninitializedPages().filter((page) => page.initializedOrUndefined()); + } + async cookies(progress2, urls = []) { + return await progress2.race(this._cookies(urls)); + } + async _cookies(urls = []) { + if (urls && !Array.isArray(urls)) + urls = [urls]; + return await this.doGetCookies(urls); + } + async clearCookies(options2) { + const currentCookies = await this._cookies(); + await this.doClearCookies(); + const matches = (cookie, prop, value2) => { + if (!value2) + return true; + if (value2 instanceof RegExp) { + value2.lastIndex = 0; + return value2.test(cookie[prop]); + } + return cookie[prop] === value2; + }; + const cookiesToReadd = currentCookies.filter((cookie) => { + return !matches(cookie, "name", options2.name) || !matches(cookie, "domain", options2.domain) || !matches(cookie, "path", options2.path); + }); + await this.addCookies(cookiesToReadd); + } + setHTTPCredentials(progress2, httpCredentials) { + return progress2.race(this.innerSetHTTPCredentials(httpCredentials)); + } + innerSetHTTPCredentials(httpCredentials) { + return this.doSetHTTPCredentials(httpCredentials); + } + getBindingClient(name) { + return this._pageBindings.get(name)?.forClient; + } + async exposePlaywrightBindingIfNeeded() { + this._playwrightBindingExposed ??= (async () => { + await this.doExposePlaywrightBinding(); + this.bindingsInitScript = PageBinding.createInitScript(this); + this.initScripts.push(this.bindingsInitScript); + await this.doAddInitScript(this.bindingsInitScript); + await this.safeNonStallingEvaluateInAllFrames(this.bindingsInitScript.source, "main"); + })(); + return await this._playwrightBindingExposed; + } + needsPlaywrightBinding() { + return this._playwrightBindingExposed !== void 0; + } + async exposeBinding(progress2, name, playwrightBinding, forClient) { + if (this._pageBindings.has(name)) + throw new Error(`Function "${name}" has been already registered`); + for (const page of this.pages()) { + if (page.getBinding(name)) + throw new Error(`Function "${name}" has been already registered in one of the pages`); + } + await progress2.race(this.exposePlaywrightBindingIfNeeded()); + const binding = new PageBinding(this, name, playwrightBinding); + binding.forClient = forClient; + this._pageBindings.set(name, binding); + try { + await progress2.race(this.doAddInitScript(binding.initScript)); + await progress2.race(this.safeNonStallingEvaluateInAllFrames(binding.initScript.source, "main")); + return binding; + } catch (error) { + this._pageBindings.delete(name); + throw error; + } + } + async removeExposedBinding(binding) { + if (this._pageBindings.get(binding.name) !== binding) + return; + this._pageBindings.delete(binding.name); + await this.doRemoveInitScripts([binding.initScript]); + const cleanup = `{ ${binding.cleanupScript} };`; + await this.safeNonStallingEvaluateInAllFrames(cleanup, "main"); + } + async grantPermissions(permissions, origin) { + let resolvedOrigin = "*"; + if (origin) { + const url2 = new URL(origin); + resolvedOrigin = url2.origin; + } + const existing = new Set(this._permissions.get(resolvedOrigin) || []); + permissions.forEach((p) => existing.add(p)); + const list = [...existing.values()]; + this._permissions.set(resolvedOrigin, list); + await this.doGrantPermissions(resolvedOrigin, list); + } + async clearPermissions() { + this._permissions.clear(); + await this.doClearPermissions(); + } + async setExtraHTTPHeaders(progress2, headers) { + const oldHeaders = this._options.extraHTTPHeaders; + this._options.extraHTTPHeaders = headers; + try { + await progress2.race(this.doUpdateExtraHTTPHeaders()); + } catch (error) { + this._options.extraHTTPHeaders = oldHeaders; + this.doUpdateExtraHTTPHeaders().catch(() => { + }); + throw error; + } + } + async setOffline(progress2, offline) { + const oldOffline = this._options.offline; + this._options.offline = offline; + try { + await progress2.race(this.doUpdateOffline()); + } catch (error) { + this._options.offline = oldOffline; + this.doUpdateOffline().catch(() => { + }); + throw error; + } + } + async loadDefaultContextAsIs(progress2) { + if (!this.possiblyUninitializedPages().length) { + const waitForEvent2 = helper.waitForEvent(progress2, this, _BrowserContext.Events.Page); + await progress2.race(Promise.race([waitForEvent2.promise, this._closePromise])); + } + const page = this.possiblyUninitializedPages()[0]; + if (!page) + return; + const pageOrError = await progress2.race(page.waitForInitializedOrError()); + if (pageOrError instanceof Error) + throw pageOrError; + await page.mainFrame().waitForLoadState(progress2, "load"); + return page; + } + async loadDefaultContext(progress2) { + const defaultPage = await this.loadDefaultContextAsIs(progress2); + if (!defaultPage) + return; + const browserName = this._browser.options.name; + if (this._options.isMobile && browserName === "chromium" || this._options.locale && browserName === "webkit") { + await this.newPage(progress2); + await defaultPage.close(progress2); + } + } + authenticateProxyViaHeader() { + const proxy = this._options.proxy || this._browser.options.proxy || { username: void 0, password: void 0 }; + const { username, password } = proxy; + if (username) { + this._options.httpCredentials = { username, password }; + const token = Buffer.from(`${username}:${password}`).toString("base64"); + this._options.extraHTTPHeaders = mergeHeaders([ + this._options.extraHTTPHeaders, + singleHeader("Proxy-Authorization", `Basic ${token}`) + ]); + } + } + authenticateProxyViaCredentials() { + const proxy = this._options.proxy || this._browser.options.proxy; + if (!proxy) + return; + const { username, password } = proxy; + if (username) + this._options.httpCredentials = { username, password: password || "" }; + } + async addInitScript(progress2, source8) { + return await progress2.race(this._internalAddInitScript(source8)); + } + async _internalAddInitScript(source8) { + const initScript = new InitScript(this, source8); + this.initScripts.push(initScript); + try { + await this.doAddInitScript(initScript); + return initScript; + } catch (error) { + initScript.dispose().catch(() => { + }); + throw error; + } + } + async removeInitScript(initScript) { + this.initScripts = this.initScripts.filter((script) => initScript !== script); + await this.doRemoveInitScripts([initScript]); + } + async addRequestInterceptor(progress2, handler) { + this.requestInterceptors.push(handler); + await progress2.race(this.doUpdateRequestInterception()); + } + async removeRequestInterceptor(handler) { + const index = this.requestInterceptors.indexOf(handler); + if (index === -1) + return; + this.requestInterceptors.splice(index, 1); + await this.notifyRoutesInFlightAboutRemovedHandler(handler); + await this.doUpdateRequestInterception(); + } + isClosingOrClosed() { + return this._closedStatus !== "open"; + } + async _deleteAllDownloads() { + await Promise.all(Array.from(this._downloads).map((download) => download.artifact.deleteOnContextClose())); + } + async _deleteAllTempDirs() { + await Promise.all(this._tempDirs.map(async (dir) => await import_fs31.default.promises.unlink(dir).catch((e) => { + }))); + } + setCustomCloseHandler(handler) { + this._customCloseHandler = handler; + } + async close(progress2, options2) { + if (this._closedStatus === "open") { + if (options2.reason) + this._closeReason = options2.reason; + this.emit(_BrowserContext.Events.BeforeClose); + this._closedStatus = "closing"; + await progress2.race(this.tracing.flush()); + await progress2.race(Promise.all(this.pages().map((page) => page.screencast.handlePageOrContextClose()))); + if (this._customCloseHandler) { + await progress2.race(this._customCloseHandler()); + } else { + const disposition = await progress2.race(this.doClose(options2.reason)); + if (disposition === "close-browser") + await this._browser.close(progress2, { reason: options2.reason }); + } + const promises = []; + promises.push(this._deleteAllDownloads()); + promises.push(this._deleteAllTempDirs()); + await progress2.race(Promise.all(promises)); + if (!this._customCloseHandler) + this._didCloseInternal(); + } + await this._closePromise; + } + async newPage(progress2, forStorageState) { + let page; + try { + this._creatingStorageStatePage = !!forStorageState; + page = await progress2.race(this.doCreateNewPage()); + const pageOrError = await progress2.race(page.waitForInitializedOrError()); + if (pageOrError instanceof Page) { + if (pageOrError.isClosed()) + throw new Error("Page has been closed."); + return pageOrError; + } + throw pageOrError; + } catch (error) { + await page?.close(progress2, { reason: "Failed to create page" }).catch(() => { + }); + throw error; + } finally { + this._creatingStorageStatePage = false; + } + } + addVisitedOrigin(origin) { + this._origins.add(origin); + } + async storageState(progress2, indexedDB = false) { + const result2 = { + cookies: await this.cookies(progress2), + origins: [] + }; + const originsToSave = new Set(this._origins); + const collectScript = `(() => { + const module = {}; + ${source6} + const script = new (module.exports.StorageScript())(${this._browser.options.name === "firefox"}); + return script.collect(${indexedDB}); + })()`; + for (const page of this.pages()) { + const origin = page.mainFrame().origin(); + if (!origin || !originsToSave.has(origin)) + continue; + try { + const storage = await progress2.race(page.mainFrame().nonStallingEvaluateInExistingContext(collectScript, "utility")); + if (storage.localStorage.length || storage.indexedDB?.length) + result2.origins.push({ origin, localStorage: storage.localStorage, indexedDB: storage.indexedDB }); + originsToSave.delete(origin); + } catch { + } + } + if (originsToSave.size) { + const page = await this.newPage( + progress2, + true + /* forStorageState */ + ); + try { + await page.addRequestInterceptor(progress2, (route2) => { + route2.fulfill({ body: "" }).catch(() => { + }); + }, "prepend"); + for (const origin of originsToSave) { + const frame = page.mainFrame(); + await frame.gotoImpl(progress2, origin, {}); + const storage = await frame.evaluateExpression(progress2, collectScript, { world: "utility" }); + if (storage.localStorage.length || storage.indexedDB?.length) + result2.origins.push({ origin, localStorage: storage.localStorage, indexedDB: storage.indexedDB }); + } + } finally { + await page.close(progress2); + } + } + return result2; + } + isCreatingStorageStatePage() { + return this._creatingStorageStatePage; + } + async setStorageState(progress2, state, mode) { + let page; + let interceptor; + try { + if (mode !== "initial") { + await progress2.race(this.clearCache()); + await progress2.race(this.doClearCookies()); + } + if (state?.cookies) + await progress2.race(this.addCookies(state.cookies)); + const newOrigins = new Map(state?.origins?.map((p) => [p.origin, p]) || []); + const allOrigins = /* @__PURE__ */ new Set([...this._origins, ...newOrigins.keys()]); + if (allOrigins.size) { + if (mode === "resetForReuse") + page = this.pages()[0]; + if (!page) + page = await this.newPage( + progress2, + mode !== "resetForReuse" + /* forStorageState */ + ); + interceptor = (route2) => { + route2.fulfill({ body: "" }).catch(() => { + }); + }; + await page.addRequestInterceptor(progress2, interceptor, "prepend"); + for (const origin of allOrigins) { + const frame = page.mainFrame(); + await frame.gotoImpl(progress2, origin, {}); + const restoreScript = `(() => { + const module = {}; + ${source6} + const script = new (module.exports.StorageScript())(${this._browser.options.name === "firefox"}); + return script.restore(${JSON.stringify(newOrigins.get(origin))}); + })()`; + await frame.evaluateExpression(progress2, restoreScript, { world: "utility" }); + } + } + this._origins = /* @__PURE__ */ new Set([...newOrigins.keys()]); + } catch (error) { + rewriteErrorMessage(error, `Error setting storage state: +` + error.message); + throw error; + } finally { + if (mode !== "resetForReuse") + await page?.close(progress2); + else if (interceptor) + await page?.removeRequestInterceptor(interceptor); + } + } + async extendInjectedScript(source8, arg) { + const installInFrame = (frame) => frame.extendInjectedScript(source8, arg).catch(() => { + }); + const installInPage = (page) => { + page.on(Page.Events.InternalFrameNavigatedToNewDocument, installInFrame); + return Promise.all(page.frames().map(installInFrame)); + }; + this.on(_BrowserContext.Events.Page, installInPage); + return Promise.all(this.pages().map(installInPage)); + } + async safeNonStallingEvaluateInAllFrames(expression2, world, options2 = {}) { + await Promise.all(this.pages().map((page) => page.safeNonStallingEvaluateInAllFrames(expression2, world, options2))); + } + addRouteInFlight(route2) { + this._routesInFlight.add(route2); + } + removeRouteInFlight(route2) { + this._routesInFlight.delete(route2); + } + async notifyRoutesInFlightAboutRemovedHandler(handler) { + await Promise.all([...this._routesInFlight].map((route2) => route2.removeHandler(handler))); + } + }; + paramsThatAllowContextReuse = [ + "colorScheme", + "forcedColors", + "reducedMotion", + "contrast", + "screen", + "userAgent", + "viewport", + "testIdAttributeName" + ]; + defaultNewContextParamValues = { + noDefaultViewport: false, + ignoreHTTPSErrors: false, + javaScriptEnabled: true, + bypassCSP: false, + offline: false, + isMobile: false, + hasTouch: false, + acceptDownloads: "accept", + strictSelectors: false, + serviceWorkers: "allow", + locale: "en-US" + }; + } +}); + +// packages/playwright-core/src/server/download.ts +var import_path32, Download; +var init_download = __esm({ + "packages/playwright-core/src/server/download.ts"() { + "use strict"; + import_path32 = __toESM(require("path")); + init_assert(); + init_page(); + init_artifact(); + Download = class { + constructor(page, downloadsPath, uuid, url2, suggestedFilename, downloadFilename) { + const unaccessibleErrorMessage = page.browserContext._options.acceptDownloads === "deny" ? "Pass { acceptDownloads: true } when you are creating your browser context." : void 0; + const downloadPath = import_path32.default.join(downloadsPath, downloadFilename ?? uuid); + this.artifact = new Artifact(page, downloadPath, unaccessibleErrorMessage, () => this.cancel()); + this._page = page; + this.url = url2; + this._uuid = uuid; + this._suggestedFilename = suggestedFilename; + page.browserContext._downloads.add(this); + if (suggestedFilename !== void 0) + this._fireDownloadEvent(); + } + cancel() { + return this._page.browserContext.cancelDownload(this._uuid); + } + 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.Events.Download, this); + } + }; + } +}); + +// packages/playwright-core/src/remote/serverTransport.ts +var import_events12, WebSocketServerTransport, SocketServerTransport; +var init_serverTransport = __esm({ + "packages/playwright-core/src/remote/serverTransport.ts"() { + "use strict"; + import_events12 = require("events"); + WebSocketServerTransport = class { + constructor(ws3) { + this._ws = ws3; + } + send(message) { + this._ws.send(message); + } + close(reason) { + this._ws.close(reason?.code, reason?.reason); + } + on(event, handler) { + this._ws.on(event, handler); + } + isClosed() { + return this._ws.readyState === this._ws.CLOSING || this._ws.readyState === this._ws.CLOSED; + } + }; + SocketServerTransport = class extends import_events12.EventEmitter { + constructor(socket) { + super(); + this._closed = false; + this._pendingBuffers = []; + this._socket = socket; + socket.on("data", (buffer) => this._dispatch(buffer)); + socket.on("close", () => { + this._closed = true; + super.emit("close"); + }); + socket.on("error", (error) => { + super.emit("error", error); + }); + } + send(message) { + if (this._closed) + return; + this._socket.write(message); + this._socket.write("\0"); + } + close(reason) { + if (this._closed) + return; + this._closed = true; + this._socket.end(); + } + isClosed() { + return this._closed; + } + _dispatch(buffer) { + let end = buffer.indexOf("\0"); + if (end === -1) { + this._pendingBuffers.push(buffer); + return; + } + this._pendingBuffers.push(buffer.slice(0, end)); + const message = Buffer.concat(this._pendingBuffers).toString(); + super.emit("message", message); + let start3 = end + 1; + end = buffer.indexOf("\0", start3); + while (end !== -1) { + super.emit("message", buffer.toString(void 0, start3, end)); + start3 = end + 1; + end = buffer.indexOf("\0", start3); + } + this._pendingBuffers = [buffer.slice(start3)]; + } + }; + } +}); + +// packages/playwright-core/src/remote/playwrightPipeServer.ts +var import_net5, import_fs32, PlaywrightPipeServer; +var init_playwrightPipeServer = __esm({ + "packages/playwright-core/src/remote/playwrightPipeServer.ts"() { + "use strict"; + import_net5 = __toESM(require("net")); + import_fs32 = __toESM(require("fs")); + init_debugLogger(); + init_network(); + init_semaphore(); + init_playwrightConnection(); + init_serverTransport(); + init_browser(); + PlaywrightPipeServer = class { + constructor(browser) { + this._connections = /* @__PURE__ */ new Set(); + this._connectionId = 0; + this._browser = browser; + browser.on(Browser.Events.Disconnected, () => this.close()); + } + async listen(pipeName) { + if (!pipeName.startsWith("\\\\.\\pipe\\")) { + try { + import_fs32.default.unlinkSync(pipeName); + } catch { + } + } + this._server = import_net5.default.createServer((socket) => { + const id = String(++this._connectionId); + debugLogger.log("server", `[${id}] pipe client connected`); + const transport = new SocketServerTransport(socket); + const connection = new PlaywrightConnection( + new Semaphore(1), + transport, + false, + this._browser.attribution.playwright, + () => this._initPreLaunchedBrowserMode(id), + id + ); + this._connections.add(connection); + transport.on("close", () => this._connections.delete(connection)); + }); + decorateServer(this._server); + await new Promise((resolve, reject) => { + this._server.listen(pipeName, () => resolve()); + this._server.on("error", reject); + }); + debugLogger.log("server", `Pipe server listening at ${pipeName}`); + } + async _initPreLaunchedBrowserMode(id) { + debugLogger.log("server", `[${id}] engaged pre-launched (browser) pipe mode`); + return { + preLaunchedBrowser: this._browser, + sharedBrowser: true, + denyLaunch: true + }; + } + async close() { + if (!this._server) + return; + debugLogger.log("server", "closing pipe server"); + for (const connection of this._connections) + await connection.close({ code: 1001, reason: "Server closing" }); + this._connections.clear(); + await new Promise((f) => this._server.close(() => f())); + this._server = void 0; + debugLogger.log("server", "closed pipe server"); + } + }; + } +}); + +// packages/playwright-core/src/remote/playwrightWebSocketServer.ts +var PlaywrightWebSocketServer; +var init_playwrightWebSocketServer = __esm({ + "packages/playwright-core/src/remote/playwrightWebSocketServer.ts"() { + "use strict"; + init_debugLogger(); + init_wsServer(); + init_semaphore(); + init_playwrightConnection(); + init_serverTransport(); + init_browser(); + PlaywrightWebSocketServer = class { + constructor(browser, path59) { + this._browser = browser; + browser.on(Browser.Events.Disconnected, () => this.close()); + const semaphore = new Semaphore(Infinity); + this._wsServer = new WSServer({ + onRequest: (request2, response2) => { + response2.end("Running"); + }, + onUpgrade: () => void 0, + onHeaders: () => { + }, + onConnection: (request2, url2, ws3, id) => { + debugLogger.log("server", `[${id}] ws client connected`); + return new PlaywrightConnection( + semaphore, + new WebSocketServerTransport(ws3), + false, + this._browser.attribution.playwright, + () => this._initPreLaunchedBrowserMode(id), + id + ); + } + }); + } + async _initPreLaunchedBrowserMode(id) { + debugLogger.log("server", `[${id}] engaged pre-launched (browser) ws mode`); + return { + preLaunchedBrowser: this._browser, + sharedBrowser: true, + denyLaunch: true + }; + } + async listen(port = 0, hostname, path59) { + return await this._wsServer.listen(port, hostname, path59 || "/"); + } + async close() { + await this._wsServer.close(); + } + }; + } +}); + +// packages/playwright-core/src/serverRegistry.ts +async function canConnectTo(descriptor) { + if (!descriptor.endpoint) + return false; + if (descriptor.endpoint.startsWith("ws://") || descriptor.endpoint.startsWith("wss://")) { + return await new Promise((resolve) => { + const url2 = new URL(descriptor.endpoint); + const socket = import_net6.default.createConnection(Number(url2.port), url2.hostname, () => { + socket.destroy(); + resolve(true); + }); + socket.on("error", () => resolve(false)); + }); + } + return await new Promise((resolve) => { + const socket = import_net6.default.createConnection(descriptor.endpoint ?? descriptor.pipeName, () => { + socket.destroy(); + resolve(true); + }); + socket.on("error", () => resolve(false)); + }); +} +var import_events13, import_fs33, import_net6, import_path33, import_os16, chokidar, packageVersion, ServerRegistry, defaultCacheDirectory2, registryDirectory2, serverRegistry; +var init_serverRegistry = __esm({ + "packages/playwright-core/src/serverRegistry.ts"() { + "use strict"; + import_events13 = require("events"); + import_fs33 = __toESM(require("fs")); + import_net6 = __toESM(require("net")); + import_path33 = __toESM(require("path")); + import_os16 = __toESM(require("os")); + init_package(); + chokidar = require("./utilsBundle").chokidar; + packageVersion = packageJSON.version; + ServerRegistry = class extends import_events13.EventEmitter { + constructor() { + super(...arguments); + this._descriptors = /* @__PURE__ */ new Map(); + this._watcherRefs = 0; + } + on(event, listener) { + return super.on(event, listener); + } + off(event, listener) { + return super.off(event, listener); + } + watch() { + this._watcherRefs++; + if (!this._watcher) + this._startWatcher(); + let disposed = false; + return () => { + if (disposed) + return; + disposed = true; + this._watcherRefs--; + if (this._watcherRefs === 0) + this._stopWatcher(); + }; + } + ready() { + return this._ready ?? Promise.resolve(); + } + async list() { + const ownWatcher = !this._watcher; + let dispose; + if (ownWatcher) + dispose = this.watch(); + try { + await this._ready; + const statuses = await Promise.all( + [...this._descriptors.values()].map(async (descriptor) => { + const canConnect = await canConnectTo(descriptor); + return { descriptor, canConnect }; + }) + ); + const result2 = /* @__PURE__ */ new Map(); + for (const { descriptor, canConnect } of statuses) { + if (!canConnect) { + await import_fs33.default.promises.unlink(import_path33.default.join(this._browsersDir(), descriptor.browser.guid)).catch(() => { + }); + continue; + } + const key = descriptor.workspaceDir ?? ""; + let list = result2.get(key); + if (!list) { + list = []; + result2.set(key, list); + } + list.push(descriptor); + } + return result2; + } finally { + dispose?.(); + } + } + async create(browser, endpoint) { + const file = import_path33.default.join(this._browsersDir(), browser.guid); + await import_fs33.default.promises.mkdir(this._browsersDir(), { recursive: true }); + const descriptor = { + playwrightVersion: packageVersion, + playwrightLib: packageRoot, + title: endpoint.title, + browser, + endpoint: endpoint.endpoint, + workspaceDir: endpoint.workspaceDir + }; + await import_fs33.default.promises.writeFile(file, JSON.stringify(descriptor, null, 2), "utf-8"); + } + async delete(guid) { + const file = import_path33.default.join(this._browsersDir(), guid); + await import_fs33.default.promises.unlink(file).catch(() => { + }); + } + async deleteUserData(guid) { + const filePath = import_path33.default.join(this._browsersDir(), guid); + const content = await import_fs33.default.promises.readFile(filePath, "utf-8"); + const descriptor = JSON.parse(content); + if (descriptor.browser.userDataDir) + await import_fs33.default.promises.rm(descriptor.browser.userDataDir, { recursive: true, force: true }); + await import_fs33.default.promises.unlink(filePath); + } + readDescriptor(guid) { + const cached = this._descriptors.get(guid); + if (cached) + return cached; + const filePath = import_path33.default.join(this._browsersDir(), guid); + const content = import_fs33.default.readFileSync(filePath, "utf-8"); + return JSON.parse(content); + } + async find(name) { + const entries = await this.list(); + for (const [, browsers] of entries) { + for (const browser of browsers) { + if (browser.title === name) + return browser; + } + } + return null; + } + _browsersDir() { + return process.env.PLAYWRIGHT_SERVER_REGISTRY || registryDirectory2; + } + _startWatcher() { + const dir = this._browsersDir(); + try { + import_fs33.default.mkdirSync(dir, { recursive: true }); + } catch { + } + const watcher = chokidar.watch(dir, { + ignoreInitial: false, + depth: 0, + awaitWriteFinish: { stabilityThreshold: 50, pollInterval: 20 } + }); + this._watcher = watcher; + this._ready = new Promise((resolve, reject) => { + watcher.once("ready", () => resolve()); + watcher.once("error", reject); + }); + watcher.on("add", (file) => this._onAddOrChange(file, "added")); + watcher.on("change", (file) => this._onAddOrChange(file, "changed")); + watcher.on("unlink", (file) => { + const guid = import_path33.default.basename(file); + if (this._descriptors.delete(guid)) + this.emit("removed", guid); + }); + } + _onAddOrChange(file, event) { + const guid = import_path33.default.basename(file); + let descriptor; + try { + descriptor = JSON.parse(import_fs33.default.readFileSync(file, "utf-8")); + } catch { + return; + } + this._descriptors.set(guid, descriptor); + this.emit(event, descriptor); + } + _stopWatcher() { + const watcher = this._watcher; + this._watcher = void 0; + this._ready = void 0; + this._descriptors.clear(); + void watcher?.close(); + } + }; + defaultCacheDirectory2 = (() => { + if (process.platform === "linux") + return process.env.XDG_CACHE_HOME || import_path33.default.join(import_os16.default.homedir(), ".cache"); + if (process.platform === "darwin") + return import_path33.default.join(import_os16.default.homedir(), "Library", "Caches"); + if (process.platform === "win32") + return process.env.LOCALAPPDATA || import_path33.default.join(import_os16.default.homedir(), "AppData", "Local"); + throw new Error("Unsupported platform: " + process.platform); + })(); + registryDirectory2 = import_path33.default.join(defaultCacheDirectory2, "ms-playwright", "b"); + serverRegistry = new ServerRegistry(); + } +}); + +// packages/playwright-core/src/server/browser.ts +function asClientLaunchOptions(serverOptions) { + return { + ...serverOptions, + env: serverOptions.env ? Object.fromEntries(serverOptions.env.map(({ name, value: value2 }) => [name, value2])) : void 0 + }; +} +var import_fs34, Browser, BrowserServer; +var init_browser = __esm({ + "packages/playwright-core/src/server/browser.ts"() { + "use strict"; + import_fs34 = __toESM(require("fs")); + init_fileUtils(); + init_crypto(); + init_browserContext(); + init_download(); + init_instrumentation(); + init_socksClientCertificatesInterceptor(); + init_playwrightPipeServer(); + init_playwrightWebSocketServer(); + init_serverRegistry(); + init_progress(); + Browser = class _Browser extends SdkObject { + constructor(parent, options2) { + super(parent, "browser"); + this._downloads = /* @__PURE__ */ new Map(); + this._defaultContext = null; + this._startedClosing = false; + this._isCollocatedWithServer = true; + this.attribution.browser = this; + this.options = options2; + this.instrumentation.onBrowserOpen(this); + this._server = new BrowserServer(this); + } + static { + this.Events = { + Context: "context", + Disconnected: "disconnected" + }; + } + sdkLanguage() { + return this.options.sdkLanguage || this.attribution.playwright.options.sdkLanguage; + } + async newContext(progress2, options2) { + validateBrowserContextOptions(options2, this.options); + let clientCertificatesProxy; + let context2; + try { + if (options2.clientCertificates?.length) { + clientCertificatesProxy = await ClientCertificatesProxy.create(progress2, options2); + options2 = { ...options2 }; + options2.proxyOverride = clientCertificatesProxy.proxySettings(); + options2.internalIgnoreHTTPSErrors = true; + } + context2 = await progress2.race(this.doCreateNewContext(options2)); + context2._clientCertificatesProxy = clientCertificatesProxy; + if (options2.__testHookBeforeSetStorageState) + await progress2.race(options2.__testHookBeforeSetStorageState()); + await context2.setStorageState(progress2, options2.storageState, "initial"); + this.emit(_Browser.Events.Context, context2); + return context2; + } catch (error) { + await context2?.close(progress2, { reason: "Failed to create context" }).catch(() => { + }); + await clientCertificatesProxy?.close().catch(() => { + }); + throw error; + } + } + async newContextForReuse(progress2, params2) { + const hash = BrowserContext.reusableContextHash(params2); + if (!this._contextForReuse || hash !== this._contextForReuse.hash || !this._contextForReuse.context.canResetForReuse()) { + if (this._contextForReuse) + await this._contextForReuse.context.close(progress2, { reason: "Context reused" }); + this._contextForReuse = { context: await this.newContext(progress2, params2), hash }; + return this._contextForReuse.context; + } + await this._contextForReuse.context.resetForReuse(progress2, params2); + return this._contextForReuse.context; + } + contextForReuse() { + return this._contextForReuse?.context; + } + downloadCreated(page, uuid, url2, suggestedFilename, downloadFilename) { + const download = new Download(page, this.options.downloadsPath || "", uuid, url2, suggestedFilename, downloadFilename); + this._downloads.set(uuid, download); + } + downloadFilenameSuggested(uuid, suggestedFilename) { + const download = this._downloads.get(uuid); + if (!download) + return; + download.filenameSuggested(suggestedFilename); + } + downloadFinished(uuid, error) { + const download = this._downloads.get(uuid); + if (!download) + return; + download.artifact.reportFinished(error ? new Error(error) : void 0); + this._downloads.delete(uuid); + } + async startServer(progress2, title, options2) { + return await progress2.race(this._server.start(title, options2)); + } + async stopServer(progress2) { + await progress2.race(this._server.stop()); + } + didClose() { + for (const context2 of this.contexts()) + context2.browserClosed(); + if (this._defaultContext) + this._defaultContext.browserClosed(); + this.stopServer(nullProgress).catch(() => { + }); + this.emit(_Browser.Events.Disconnected); + this.instrumentation.onBrowserClose(this); + } + async close(progress2, options2) { + return await progress2.race(this._close(options2)); + } + 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(_Browser.Events.Disconnected, x)); + } + async killForTests(progress2) { + await progress2.race(this.options.browserProcess.kill()); + } + }; + BrowserServer = class { + constructor(browser) { + this._isStarted = false; + this._browser = browser; + } + async start(title, options2) { + if (this._isStarted) + throw new Error(`Server is already started.`); + this._isStarted = true; + let endpoint; + if (options2.host !== void 0 || options2.port !== void 0) { + this._wsServer = new PlaywrightWebSocketServer(this._browser, "/"); + endpoint = await this._wsServer.listen(options2.port ?? 0, options2.host, "/" + createGuid()); + } else { + this._pipeServer = new PlaywrightPipeServer(this._browser); + this._pipeSocketPath = await this._socketPath(); + await this._pipeServer.listen(this._pipeSocketPath); + endpoint = this._pipeSocketPath; + } + const browserInfo2 = { + guid: this._browser.guid, + browserName: this._browser.options.browserType, + launchOptions: asClientLaunchOptions(this._browser.options.originalLaunchOptions), + userDataDir: this._browser.options.userDataDir + }; + await serverRegistry.create(browserInfo2, { + title, + endpoint, + workspaceDir: options2.workspaceDir, + metadata: options2.metadata + }); + return { endpoint }; + } + async stop() { + if (!this._browser.options.userDataDir) + await serverRegistry.delete(this._browser.guid); + if (this._pipeSocketPath && process.platform !== "win32") + await import_fs34.default.promises.unlink(this._pipeSocketPath).catch(() => { + }); + await this._pipeServer?.close(); + await this._wsServer?.close(); + this._pipeServer = void 0; + this._wsServer = void 0; + this._isStarted = false; + } + async _socketPath() { + return makeSocketPath("browser", this._browser.guid.slice(0, 14)); + } + }; + } +}); + +// packages/playwright-core/src/server/dispatchers/cdpSessionDispatcher.ts +var CDPSessionDispatcher; +var init_cdpSessionDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/cdpSessionDispatcher.ts"() { + "use strict"; + init_dispatcher(); + init_crConnection(); + CDPSessionDispatcher = class extends Dispatcher { + constructor(scope, cdpSession) { + super(scope, cdpSession, "CDPSession", {}); + this._type_CDPSession = true; + this.addObjectListener(CDPSession.Events.Event, ({ method, params: params2 }) => this._dispatchEvent("event", { method, params: params2 })); + this.addObjectListener(CDPSession.Events.Closed, () => { + this._dispatchEvent("close"); + this._dispose(); + }); + } + async send(params2, progress2) { + return { result: await this._object.send(progress2, params2.method, params2.params) }; + } + async detach(_, progress2) { + progress2.metadata.potentiallyClosesScope = true; + await this._object.detach(progress2); + } + }; + } +}); + +// packages/playwright-core/src/server/dispatchers/debuggerDispatcher.ts +var DebuggerDispatcher; +var init_debuggerDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/debuggerDispatcher.ts"() { + "use strict"; + init_protocolFormatter(); + init_dispatcher(); + init_debugger(); + DebuggerDispatcher = class _DebuggerDispatcher extends Dispatcher { + constructor(scope, debugger_) { + super(scope, debugger_, "Debugger", {}); + this._type_EventTarget = true; + this._type_Debugger = true; + this.addObjectListener(Debugger.Events.PausedStateChanged, () => { + this._dispatchEvent("pausedStateChanged", { pausedDetails: this._serializePausedDetails() }); + }); + this._dispatchEvent("pausedStateChanged", { pausedDetails: this._serializePausedDetails() }); + } + static from(scope, debugger_) { + const result2 = scope.connection.existingDispatcher(debugger_); + return result2 || new _DebuggerDispatcher(scope, debugger_); + } + _serializePausedDetails() { + const details = this._object.pausedDetails(); + if (!details) + return void 0; + const { metadata } = details; + return { + location: { + file: metadata.location?.file ?? "", + line: metadata.location?.line, + column: metadata.location?.column + }, + title: renderTitleForCall(metadata) + }; + } + async requestPause(params2, progress2) { + this._object.requestPause(progress2); + } + async resume(params2, progress2) { + this._object.doResume(progress2); + } + async next(params2, progress2) { + this._object.next(progress2); + } + async runTo(params2, progress2) { + this._object.runTo(progress2, params2.location); + } + }; + } +}); + +// packages/playwright-core/src/server/dispatchers/streamDispatcher.ts +var StreamSdkObject, StreamDispatcher; +var init_streamDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/streamDispatcher.ts"() { + "use strict"; + init_manualPromise(); + init_dispatcher(); + init_instrumentation(); + StreamSdkObject = class extends SdkObject { + constructor(parent, stream3) { + super(parent, "stream"); + this.stream = stream3; + } + }; + StreamDispatcher = class extends Dispatcher { + constructor(scope, stream3) { + super(scope, new StreamSdkObject(scope._object, stream3), "Stream", {}); + this._type_Stream = true; + this._ended = false; + stream3.once("end", () => this._ended = true); + stream3.once("error", () => this._ended = true); + } + async read(params2, progress2) { + const stream3 = this._object.stream; + if (this._ended) + return { binary: Buffer.from("") }; + if (!stream3.readableLength) { + const readyPromise = new ManualPromise(); + const done = () => readyPromise.resolve(); + stream3.on("readable", done); + stream3.on("end", done); + stream3.on("error", done); + try { + await progress2.race(readyPromise); + } finally { + stream3.off("readable", done); + stream3.off("end", done); + stream3.off("error", done); + } + } + const buffer = stream3.read(Math.min(stream3.readableLength, params2.size || stream3.readableLength)); + return { binary: buffer || Buffer.from("") }; + } + async close(params2, progress2) { + this._object.stream.destroy(); + } + }; + } +}); + +// packages/playwright-core/src/server/dispatchers/artifactDispatcher.ts +var import_fs35, ArtifactDispatcher; +var init_artifactDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/artifactDispatcher.ts"() { + "use strict"; + import_fs35 = __toESM(require("fs")); + init_fileUtils(); + init_dispatcher(); + init_streamDispatcher(); + ArtifactDispatcher = 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 result2 = parentScope.connection.existingDispatcher(artifact); + return result2 || new _ArtifactDispatcher(parentScope, artifact); + } + async pathAfterFinished(params2, progress2) { + const path59 = await this._object.localPathAfterFinished(progress2); + return { value: path59 }; + } + async saveAs(params2, progress2) { + return await progress2.race(new Promise((resolve, reject) => { + this._object.saveAs(progress2, async (localPath, error) => { + if (error) { + reject(error); + return; + } + try { + await mkdirIfNeeded(params2.path); + await import_fs35.default.promises.copyFile(localPath, params2.path); + resolve(); + } catch (e) { + reject(e); + } + }); + })); + } + async saveAsStream(params2, progress2) { + return await progress2.race(new Promise((resolve, reject) => { + this._object.saveAs(progress2, async (localPath, error) => { + if (error) { + reject(error); + return; + } + try { + const readable = import_fs35.default.createReadStream(localPath, { highWaterMark: 1024 * 1024 }); + const stream3 = new StreamDispatcher(this, readable); + resolve({ stream: stream3 }); + await new Promise((resolve2) => { + readable.on("close", resolve2); + readable.on("end", resolve2); + readable.on("error", resolve2); + }); + } catch (e) { + reject(e); + } + }); + })); + } + async stream(params2, progress2) { + const fileName = await this._object.localPathAfterFinished(progress2); + const readable = import_fs35.default.createReadStream(fileName, { highWaterMark: 1024 * 1024 }); + return { stream: new StreamDispatcher(this, readable) }; + } + async failure(params2, progress2) { + const error = await this._object.failureError(progress2); + return { error: error || void 0 }; + } + async cancel(params2, progress2) { + await this._object.cancel(progress2); + } + async delete(params2, progress2) { + progress2.metadata.potentiallyClosesScope = true; + await this._object.delete(progress2); + this._dispose(); + } + }; + } +}); + +// packages/playwright-core/src/server/dispatchers/jsHandleDispatcher.ts +function parseArgument(arg) { + return parseSerializedValue(arg.value, arg.handles.map((a) => a._object)); +} +function serializeResult(arg) { + return serializeValue(arg, (value2) => ({ fallThrough: value2 })); +} +var JSHandleDispatcher; +var init_jsHandleDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/jsHandleDispatcher.ts"() { + "use strict"; + init_dispatcher(); + init_elementHandlerDispatcher(); + init_serializers(); + JSHandleDispatcher = 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(params2, progress2) { + const jsHandle = await this._object.evaluateExpression(progress2, params2.expression, { isFunction: params2.isFunction }, parseArgument(params2.arg)); + return { value: serializeResult(jsHandle) }; + } + async evaluateExpressionHandle(params2, progress2) { + const jsHandle = await this._object.evaluateExpressionHandle(progress2, params2.expression, { isFunction: params2.isFunction }, parseArgument(params2.arg)); + return { handle: ElementHandleDispatcher.fromJSOrElementHandle(this.parentScope(), jsHandle) }; + } + async getProperty(params2, progress2) { + const jsHandle = await this._object.getProperty(progress2, params2.name); + return { handle: ElementHandleDispatcher.fromJSOrElementHandle(this.parentScope(), jsHandle) }; + } + async getPropertyList(params2, progress2) { + const map = await this._object.getProperties(progress2); + const properties = []; + for (const [name, value2] of map) { + properties.push({ name, value: ElementHandleDispatcher.fromJSOrElementHandle(this.parentScope(), value2) }); + } + return { properties }; + } + async jsonValue(params2, progress2) { + return { value: serializeResult(await this._object.jsonValue(progress2)) }; + } + async dispose(_, progress2) { + progress2.metadata.potentiallyClosesScope = true; + this._object.dispose(); + this._dispose(); + } + }; + } +}); + +// packages/playwright-core/src/generated/webSocketMockSource.ts +var source7; +var init_webSocketMockSource = __esm({ + "packages/playwright-core/src/generated/webSocketMockSource.ts"() { + "use strict"; + source7 = ` +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); + const protocolsList = Array.isArray(protocols) ? [...protocols] : protocols ? [protocols] : []; + binding({ type: "onCreate", id: this._id, url: this.url, protocols: protocolsList }); + } + // --- 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 { + }; +} +`; + } +}); + +// packages/playwright-core/src/server/dispatchers/webSocketRouteDispatcher.ts +function matchesPattern(dispatcher, baseURL, url2) { + for (const pattern of dispatcher._webSocketInterceptionPatterns || []) { + if (urlMatches(baseURL, url2, deserializeURLMatch(pattern), true)) + return true; + } + return false; +} +var WebSocketRouteDispatcher, kBindingName2; +var init_webSocketRouteDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/webSocketRouteDispatcher.ts"() { + "use strict"; + init_urlMatch(); + init_eventsHelper(); + init_page(); + init_dispatcher(); + init_pageDispatcher(); + init_webSocketMockSource(); + init_instrumentation(); + WebSocketRouteDispatcher = class _WebSocketRouteDispatcher extends Dispatcher { + constructor(scope, id, url2, protocols, frame) { + super(scope, new SdkObject(scope._object, "webSocketRoute"), "WebSocketRoute", { url: url2, protocols }); + 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.Events.InternalFrameNavigatedToNewDocument, (frame2) => { + if (frame2 === this._frame) + this._executionContextGone(); + }), + eventsHelper.addEventListener(frame._page, Page.Events.FrameDetached, (frame2) => { + if (frame2 === this._frame) + this._executionContextGone(); + }), + eventsHelper.addEventListener(frame._page, Page.Events.Close, () => this._executionContextGone()), + eventsHelper.addEventListener(frame._page, Page.Events.Crash, () => this._executionContextGone()) + ); + _WebSocketRouteDispatcher._idToDispatcher.set(this._id, this); + scope._dispatchEvent("webSocketRoute", { webSocketRoute: this }); + } + static { + this._idToDispatcher = /* @__PURE__ */ new Map(); + } + static async install(progress2, connection, target) { + const context2 = target instanceof Page ? target.browserContext : target; + let data = context2.getBindingClient(kBindingName2); + if (data && data.connection !== connection) + throw new Error("Another client is already routing WebSockets"); + if (!data) { + data = { counter: 0, connection, binding: null }; + data.binding = await context2.exposeBinding(progress2, kBindingName2, (source8, payload) => { + if (payload.type === "onCreate") { + const contextDispatcher = connection.existingDispatcher(context2); + const pageDispatcher = contextDispatcher ? PageDispatcher.fromNullable(contextDispatcher, source8.page) : void 0; + let scope; + if (pageDispatcher && matchesPattern(pageDispatcher, context2._options.baseURL, payload.url)) + scope = pageDispatcher; + else if (contextDispatcher && matchesPattern(contextDispatcher, context2._options.baseURL, payload.url)) + scope = contextDispatcher; + if (scope) { + new _WebSocketRouteDispatcher(scope, payload.id, payload.url, payload.protocols, source8.frame); + } else { + const request2 = { id: payload.id, type: "passthrough" }; + source8.frame.evaluateExpression(progress2, `globalThis.__pwWebSocketDispatch(${JSON.stringify(request2)})`).catch(() => { + }); + } + return; + } + const dispatcher = _WebSocketRouteDispatcher._idToDispatcher.get(payload.id); + if (payload.type === "onMessageFromPage") + dispatcher?._dispatchEvent("messageFromPage", { message: payload.data.data, isBase64: payload.data.isBase64 }); + if (payload.type === "onMessageFromServer") + dispatcher?._dispatchEvent("messageFromServer", { message: payload.data.data, isBase64: payload.data.isBase64 }); + if (payload.type === "onClosePage") + dispatcher?._dispatchEvent("closePage", { code: payload.code, reason: payload.reason, wasClean: payload.wasClean }); + if (payload.type === "onCloseServer") + dispatcher?._dispatchEvent("closeServer", { code: payload.code, reason: payload.reason, wasClean: payload.wasClean }); + }, data); + } + ++data.counter; + return await target.addInitScript(progress2, ` + (() => { + const module = {}; + ${source7} + (module.exports.inject())(globalThis); + })(); + `); + } + static async uninstall(connection, target, initScript) { + const context2 = target instanceof Page ? target.browserContext : target; + const data = context2.getBindingClient(kBindingName2); + if (!data || data.connection !== connection) + return; + if (--data.counter <= 0) + await data.binding.dispose(); + await initScript.dispose(); + } + async connect(params2, progress2) { + await this._evaluateAPIRequest(progress2, { id: this._id, type: "connect" }); + } + async ensureOpened(params2, progress2) { + await this._evaluateAPIRequest(progress2, { id: this._id, type: "ensureOpened" }); + } + async sendToPage(params2, progress2) { + await this._evaluateAPIRequest(progress2, { id: this._id, type: "sendToPage", data: { data: params2.message, isBase64: params2.isBase64 } }); + } + async sendToServer(params2, progress2) { + await this._evaluateAPIRequest(progress2, { id: this._id, type: "sendToServer", data: { data: params2.message, isBase64: params2.isBase64 } }); + } + async closePage(params2, progress2) { + await this._evaluateAPIRequest(progress2, { id: this._id, type: "closePage", code: params2.code, reason: params2.reason, wasClean: params2.wasClean }); + } + async closeServer(params2, progress2) { + await this._evaluateAPIRequest(progress2, { id: this._id, type: "closeServer", code: params2.code, reason: params2.reason, wasClean: params2.wasClean }); + } + async _evaluateAPIRequest(progress2, request2) { + await this._frame.evaluateExpression(progress2, `globalThis.__pwWebSocketDispatch(${JSON.stringify(request2)})`).catch(() => { + }); + } + _onDispose() { + _WebSocketRouteDispatcher._idToDispatcher.delete(this._id); + } + _executionContextGone() { + if (!this._disposed) { + this._dispatchEvent("closePage", { wasClean: true }); + this._dispatchEvent("closeServer", { wasClean: true }); + } + } + }; + kBindingName2 = "__pwWebSocketBinding"; + } +}); + +// packages/playwright-core/src/server/dispatchers/disposableDispatcher.ts +var DisposableDispatcher; +var init_disposableDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/disposableDispatcher.ts"() { + "use strict"; + init_dispatcher(); + DisposableDispatcher = class extends Dispatcher { + constructor(scope, disposable) { + super(scope, disposable, "Disposable", {}); + this._type_Disposable = true; + } + async dispose(_, progress2) { + progress2.metadata.potentiallyClosesScope = true; + await progress2.race(this._object.dispose()); + this._dispose(); + } + }; + } +}); + +// packages/playwright-core/src/server/dispatchers/pageDispatcher.ts +function createVideoDispatcher(parentScope, video) { + return ArtifactDispatcher.from(parentScope.parentScope(), video); +} +var PageDispatcher, WorkerDispatcher, BindingCallDispatcher; +var init_pageDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/pageDispatcher.ts"() { + "use strict"; + init_urlMatch(); + init_page(); + init_dispatcher(); + init_errors(); + init_artifactDispatcher(); + init_elementHandlerDispatcher(); + init_frameDispatcher(); + init_jsHandleDispatcher(); + init_networkDispatchers(); + init_networkDispatchers(); + init_networkDispatchers(); + init_webSocketRouteDispatcher(); + init_disposableDispatcher(); + init_instrumentation(); + init_recorder(); + init_disposable2(); + init_videoRecorder(); + init_progress(); + PageDispatcher = class _PageDispatcher extends Dispatcher { + constructor(parentScope, page) { + const mainFrame = FrameDispatcher.from(parentScope, page.mainFrame()); + super(parentScope, page, "Page", { + mainFrame, + viewportSize: page.emulatedSize()?.viewport, + isClosed: page.isClosed(), + opener: _PageDispatcher.fromNullable(parentScope, page.opener()), + video: page.video ? createVideoDispatcher(parentScope, page.video) : void 0 + }); + this._type_EventTarget = true; + this._type_Page = true; + this._subscriptions = /* @__PURE__ */ new Set(); + this._webSocketInterceptionPatterns = []; + this._disposables = []; + this._interceptionUrlMatchers = []; + this._locatorHandlers = /* @__PURE__ */ new Set(); + this._jsCoverageActive = false; + this._cssCoverageActive = false; + this.adopt(mainFrame); + this._page = page; + this._requestInterceptor = (route2, request2) => { + const matchesSome = this._interceptionUrlMatchers.some((urlMatch) => urlMatches(this._page.browserContext._options.baseURL, request2.url(), urlMatch)); + if (!matchesSome) { + route2.continue({ isFallback: true }).catch(() => { + }); + return; + } + this._dispatchEvent("route", { route: new RouteDispatcher(RequestDispatcher.from(this.parentScope(), request2), route2) }); + }; + this.addObjectListener(Page.Events.Close, () => { + this._dispatchEvent("close"); + this._dispose(); + }); + this.addObjectListener(Page.Events.Crash, () => this._dispatchEvent("crash")); + this.addObjectListener(Page.Events.Download, (download) => { + this._dispatchEvent("download", { url: download.url, suggestedFilename: download.suggestedFilename(), artifact: ArtifactDispatcher.from(parentScope, download.artifact) }); + }); + this.addObjectListener(Page.Events.EmulatedSizeChanged, () => this._dispatchEvent("viewportSizeChanged", { viewportSize: page.emulatedSize()?.viewport })); + this.addObjectListener(Page.Events.FileChooser, (fileChooser) => this._dispatchEvent("fileChooser", { + element: ElementHandleDispatcher.from(mainFrame, fileChooser.element()), + isMultiple: fileChooser.isMultiple() + })); + this.addObjectListener(Page.Events.FrameAttached, (frame) => this._onFrameAttached(frame)); + this.addObjectListener(Page.Events.FrameDetached, (frame) => this._onFrameDetached(frame)); + this.addObjectListener(Page.Events.LocatorHandlerTriggered, (uid) => this._dispatchEvent("locatorHandlerTriggered", { uid })); + this.addObjectListener(Page.Events.WebSocket, (webSocket) => this._dispatchEvent("webSocket", { webSocket: new WebSocketDispatcher(this, webSocket) })); + this.addObjectListener(Page.Events.Worker, (worker) => this._dispatchEvent("worker", { worker: new WorkerDispatcher(this, worker) })); + 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 result2 = parentScope.connection.existingDispatcher(page); + return result2 || new _PageDispatcher(parentScope, page); + } + page() { + return this._page; + } + async exposeBinding(params2, progress2) { + const binding = await this._page.exposeBinding(progress2, params2.name, (source8, ...args) => { + if (this._disposed) + return; + const binding2 = new BindingCallDispatcher(this, params2.name, source8, args); + this._dispatchEvent("bindingCall", { binding: binding2 }); + return binding2.promise(); + }); + this._disposables.push(binding); + return { disposable: new DisposableDispatcher(this, binding) }; + } + async setExtraHTTPHeaders(params2, progress2) { + await this._page.setExtraHTTPHeaders(progress2, params2.headers); + } + async reload(params2, progress2) { + return { response: ResponseDispatcher.fromNullable(this.parentScope(), await this._page.reload(progress2, params2)) }; + } + async goBack(params2, progress2) { + return { response: ResponseDispatcher.fromNullable(this.parentScope(), await this._page.goBack(progress2, params2)) }; + } + async goForward(params2, progress2) { + return { response: ResponseDispatcher.fromNullable(this.parentScope(), await this._page.goForward(progress2, params2)) }; + } + async requestGC(params2, progress2) { + await this._page.requestGC(progress2); + } + async registerLocatorHandler(params2, progress2) { + const uid = this._page.registerLocatorHandler(params2.selector, params2.noWaitAfter); + this._locatorHandlers.add(uid); + return { uid }; + } + async resolveLocatorHandlerNoReply(params2, progress2) { + this._page.resolveLocatorHandler(params2.uid, params2.remove); + } + async unregisterLocatorHandler(params2, progress2) { + this._page.unregisterLocatorHandler(params2.uid); + this._locatorHandlers.delete(params2.uid); + } + async emulateMedia(params2, progress2) { + await this._page.emulateMedia(progress2, { + media: params2.media, + colorScheme: params2.colorScheme, + reducedMotion: params2.reducedMotion, + forcedColors: params2.forcedColors, + contrast: params2.contrast + }); + } + async setViewportSize(params2, progress2) { + await this._page.setViewportSize(progress2, params2.viewportSize); + } + async addInitScript(params2, progress2) { + const initScript = await this._page.addInitScript(progress2, params2.source); + this._disposables.push(initScript); + return { disposable: new DisposableDispatcher(this, initScript) }; + } + async setNetworkInterceptionPatterns(params2, progress2) { + const hadMatchers = this._interceptionUrlMatchers.length > 0; + if (!params2.patterns.length) { + if (hadMatchers) + await progress2.race(this._page.removeRequestInterceptor(this._requestInterceptor)); + this._interceptionUrlMatchers = []; + } else { + this._interceptionUrlMatchers = params2.patterns.map(deserializeURLMatch); + if (!hadMatchers) + await this._page.addRequestInterceptor(progress2, this._requestInterceptor); + } + } + async setWebSocketInterceptionPatterns(params2, progress2) { + this._webSocketInterceptionPatterns = params2.patterns; + if (params2.patterns.length && !this._routeWebSocketInitScript) + this._routeWebSocketInitScript = await WebSocketRouteDispatcher.install(progress2, this.connection, this._page); + } + async expectScreenshot(params2, progress2) { + const mask = (params2.mask || []).map(({ frame, selector }) => ({ + frame: frame._object, + selector + })); + const locator2 = params2.locator ? { + frame: params2.locator.frame._object, + selector: params2.locator.selector + } : void 0; + return await this._page.expectScreenshot(progress2, { + ...params2, + locator: locator2, + mask + }); + } + async screenshot(params2, progress2) { + const mask = (params2.mask || []).map(({ frame, selector }) => ({ + frame: frame._object, + selector + })); + return { binary: await this._page.screenshot(progress2, { ...params2, mask }) }; + } + async close(params2, progress2) { + if (!params2.runBeforeUnload) + progress2.metadata.potentiallyClosesScope = true; + await this._page.close(progress2, params2); + } + async updateSubscription(params2, progress2) { + if (params2.event === "fileChooser") + await this._page.setFileChooserInterceptedBy(progress2, params2.enabled, this); + if (params2.enabled) + this._subscriptions.add(params2.event); + else + this._subscriptions.delete(params2.event); + } + async keyboardDown(params2, progress2) { + await this._page.keyboard.apiDown(progress2, params2.key); + } + async keyboardUp(params2, progress2) { + await this._page.keyboard.apiUp(progress2, params2.key); + } + async keyboardInsertText(params2, progress2) { + await this._page.keyboard.apiInsertText(progress2, params2.text); + } + async keyboardType(params2, progress2) { + await this._page.keyboard.apiType(progress2, params2.text, params2); + } + async keyboardPress(params2, progress2) { + await this._page.keyboard.apiPress(progress2, params2.key, params2); + } + async clearConsoleMessages(params2, progress2) { + this._page.clearConsoleMessages(); + } + async consoleMessages(params2, progress2) { + this._subscriptions.add("console"); + return { messages: this._page.consoleMessages(params2.filter).map((message) => this.parentScope().serializeConsoleMessage(message, this)) }; + } + async clearPageErrors(params2, progress2) { + this._page.clearPageErrors(); + } + async pageErrors(params2, progress2) { + return { errors: this._page.pageErrors(params2.filter).map((error) => serializeError(error)) }; + } + async mouseMove(params2, progress2) { + await this._page.mouse.apiMove(progress2, params2.x, params2.y, params2); + } + async mouseDown(params2, progress2) { + await this._page.mouse.apiDown(progress2, params2); + } + async mouseUp(params2, progress2) { + await this._page.mouse.apiUp(progress2, params2); + } + async mouseClick(params2, progress2) { + await this._page.mouse.apiClick(progress2, params2.x, params2.y, params2); + } + async mouseWheel(params2, progress2) { + await this._page.mouse.apiWheel(progress2, params2.deltaX, params2.deltaY); + } + async touchscreenTap(params2, progress2) { + progress2.metadata.point = { x: params2.x, y: params2.y }; + await this._page.touchscreen.apiTap(progress2, params2.x, params2.y); + } + async pdf(params2, progress2) { + if (!this._page.pdf) + throw new Error("PDF generation is only supported for Headless Chromium"); + const buffer = await progress2.race(this._page.pdf(params2)); + return { pdf: buffer }; + } + async requests(params2, progress2) { + this._subscriptions.add("request"); + return { requests: this._page.networkRequests().map((request2) => RequestDispatcher.from(this.parentScope(), request2)) }; + } + async bringToFront(params2, progress2) { + await this._page.bringToFront(progress2); + } + async pickLocator(params2, progress2) { + const recorder = await progress2.race(Recorder.forContext(this._page.browserContext, { omitCallTracking: true, hideToolbar: true })); + const selector = await recorder.pickLocator(progress2, this._page); + return { selector }; + } + async cancelPickLocator(params2, progress2) { + const recorder = await progress2.race(Recorder.existingForContext(this._page.browserContext)); + if (recorder) + await progress2.race(recorder.setMode("none")); + } + async hideHighlight(params2, progress2) { + await progress2.race(this._page.hideHighlight()); + } + async screencastShowOverlay(params2) { + const id = await this._page.overlay.show(params2.html, params2.duration); + return { id }; + } + async screencastRemoveOverlay(params2) { + await this._page.overlay.remove(params2.id); + } + async screencastChapter(params2) { + await this._page.overlay.chapter(params2); + } + async screencastSetOverlayVisible(params2) { + await this._page.overlay.setVisible(params2.visible); + } + async screencastShowActions(params2) { + this._page.screencast.showActions({ duration: params2.duration, position: params2.position, fontSize: params2.fontSize }); + } + async screencastHideActions() { + this._page.screencast.hideActions(); + } + async screencastStart(params2, progress2) { + if (this._screencastClient || this._videoRecorder) + throw new Error("Screencast is already running"); + if (params2.sendFrames) { + this._screencastClient = { + onFrame: (frame) => { + this._dispatchEvent("screencastFrame", { data: frame.buffer, viewportWidth: frame.viewportWidth, viewportHeight: frame.viewportHeight }); + }, + dispose: () => { + }, + size: params2.size, + quality: params2.quality + }; + this._page.screencast.addClient(this._screencastClient); + } + let artifact; + if (params2.record) { + this._videoRecorder = new VideoRecorder(this._page.screencast); + artifact = this._videoRecorder.start(params2); + } + return { artifact: artifact ? createVideoDispatcher(this.parentScope(), artifact) : void 0 }; + } + async screencastStop(params2, progress2) { + if (this._videoRecorder) { + await this._videoRecorder.stop(); + this._videoRecorder = void 0; + } + const client = this._screencastClient; + this._screencastClient = void 0; + if (client) + this._page.screencast.removeClient(client); + } + async startJSCoverage(params2, progress2) { + const coverage = this._page.coverage; + await coverage.startJSCoverage(progress2, params2); + this._jsCoverageActive = true; + } + async stopJSCoverage(params2, progress2) { + this._jsCoverageActive = false; + const coverage = this._page.coverage; + return await progress2.race(coverage.stopJSCoverage()); + } + async startCSSCoverage(params2, progress2) { + const coverage = this._page.coverage; + await coverage.startCSSCoverage(progress2, params2); + this._cssCoverageActive = true; + } + async stopCSSCoverage(params2, progress2) { + this._cssCoverageActive = false; + const coverage = this._page.coverage; + return await progress2.race(coverage.stopCSSCoverage()); + } + _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(() => { + }); + disposeAll2(this._disposables).catch(() => { + }); + if (this._routeWebSocketInitScript) + WebSocketRouteDispatcher.uninstall(this.connection, this._page, this._routeWebSocketInitScript).catch(() => { + }); + this._routeWebSocketInitScript = void 0; + for (const uid of this._locatorHandlers) + this._page.unregisterLocatorHandler(uid); + this._locatorHandlers.clear(); + this._page.setFileChooserInterceptedBy(nullProgress, 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; + this.screencastStop({}, void 0).catch(() => { + }); + } + async setDockTile(params2) { + await this._page.setDockTile(params2.image); + } + }; + WorkerDispatcher = class _WorkerDispatcher extends Dispatcher { + constructor(scope, worker) { + super(scope, worker, "Worker", { + url: worker.url + }); + this._type_Worker = true; + this._type_EventTarget = true; + this._subscriptions = /* @__PURE__ */ new Set(); + this.addObjectListener(Worker.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(), + timestamp: message.timestamp() + }); + }); + this.addObjectListener(Worker.Events.Close, () => this._dispatchEvent("close")); + } + static fromNullable(scope, worker) { + if (!worker) + return void 0; + const result2 = scope.connection.existingDispatcher(worker); + return result2 || new _WorkerDispatcher(scope, worker); + } + async disconnect(params2, progress2) { + progress2.metadata.potentiallyClosesScope = true; + await this._object.disconnect(progress2, params2); + } + async evaluateExpression(params2, progress2) { + return { value: serializeResult(await this._object.evaluateExpression(progress2, params2.expression, params2.isFunction, parseArgument(params2.arg))) }; + } + async evaluateExpressionHandle(params2, progress2) { + return { handle: JSHandleDispatcher.fromJSHandle(this, await this._object.evaluateExpressionHandle(progress2, params2.expression, params2.isFunction, parseArgument(params2.arg))) }; + } + async updateSubscription(params2, progress2) { + if (params2.enabled) + this._subscriptions.add(params2.event); + else + this._subscriptions.delete(params2.event); + } + }; + BindingCallDispatcher = class extends Dispatcher { + constructor(scope, name, source8, args) { + const frameDispatcher = FrameDispatcher.from(scope.parentScope(), source8.frame); + super(scope, new SdkObject(scope._object, "bindingCall"), "BindingCall", { + frame: frameDispatcher, + name, + args: args.map(serializeResult) + }); + this._type_BindingCall = true; + this._promise = new Promise((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + }); + } + promise() { + return this._promise; + } + async resolve(params2, progress2) { + this._resolve(parseArgument(params2.result)); + this._dispose(); + } + async reject(params2, progress2) { + this._reject(parseError(params2.error)); + this._dispose(); + } + }; + } +}); + +// packages/playwright-core/src/server/dispatchers/dialogDispatcher.ts +var DialogDispatcher; +var init_dialogDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/dialogDispatcher.ts"() { + "use strict"; + init_dispatcher(); + init_pageDispatcher(); + DialogDispatcher = class 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(params2, progress2) { + await this._object.accept(progress2, params2.promptText); + } + async dismiss(params2, progress2) { + await this._object.dismiss(progress2); + } + }; + } +}); + +// packages/playwright-core/src/server/dispatchers/tracingDispatcher.ts +var TracingDispatcher; +var init_tracingDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/tracingDispatcher.ts"() { + "use strict"; + init_artifactDispatcher(); + init_dispatcher(); + init_progress(); + TracingDispatcher = class _TracingDispatcher extends Dispatcher { + constructor(scope, tracing) { + super(scope, tracing, "Tracing", {}); + this._type_Tracing = true; + this._started = false; + } + static from(scope, tracing) { + const result2 = scope.connection.existingDispatcher(tracing); + return result2 || new _TracingDispatcher(scope, tracing); + } + async tracingStart(params2, progress2) { + this._object.start(progress2, params2); + this._started = true; + } + async tracingStartChunk(params2, progress2) { + return await this._object.startChunk(progress2, params2); + } + async tracingGroup(params2, progress2) { + const { name, location: location2 } = params2; + this._object.group(progress2, name, location2); + } + async tracingGroupEnd(params2, progress2) { + this._object.groupEnd(progress2); + } + async tracingStopChunk(params2, progress2) { + const { artifact, entries } = await this._object.stopChunk(progress2, params2); + return { artifact: artifact ? ArtifactDispatcher.from(this, artifact) : void 0, entries }; + } + async tracingStop(params2, progress2) { + await this._object.stop(progress2); + } + async harStart(params2, progress2) { + const harId = this._object.harStart(params2.page ? params2.page._object : null, params2.options); + return { harId }; + } + async harExport(params2, progress2) { + const { artifact, entries } = await this._object.harExport(progress2, params2.harId, params2.mode); + return { + artifact: artifact ? ArtifactDispatcher.from(this, artifact) : void 0, + entries + }; + } + _onDispose() { + if (this._started) + this._object.stopChunk(nullProgress, { mode: "discard" }).then(() => this._object.stop(nullProgress)).catch(() => { + }); + this._started = false; + } + }; + } +}); + +// packages/playwright-core/src/server/dispatchers/writableStreamDispatcher.ts +var import_fs36, WritableStreamSdkObject, WritableStreamDispatcher; +var init_writableStreamDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/writableStreamDispatcher.ts"() { + "use strict"; + import_fs36 = __toESM(require("fs")); + init_dispatcher(); + init_instrumentation(); + WritableStreamSdkObject = class extends SdkObject { + constructor(parent, streamOrDirectory, lastModifiedMs) { + super(parent, "stream"); + this.streamOrDirectory = streamOrDirectory; + this.lastModifiedMs = lastModifiedMs; + } + }; + WritableStreamDispatcher = class extends Dispatcher { + constructor(scope, streamOrDirectory, lastModifiedMs) { + super(scope, new WritableStreamSdkObject(scope._object, streamOrDirectory, lastModifiedMs), "WritableStream", {}); + this._type_WritableStream = true; + } + async write(params2, progress2) { + if (typeof this._object.streamOrDirectory === "string") + throw new Error("Cannot write to a directory"); + const stream3 = this._object.streamOrDirectory; + await progress2.race(new Promise((fulfill, reject) => { + stream3.write(params2.binary, (error) => { + if (error) + reject(error); + else + fulfill(); + }); + })); + } + async close(params2, progress2) { + if (typeof this._object.streamOrDirectory === "string") + throw new Error("Cannot close a directory"); + const stream3 = this._object.streamOrDirectory; + await progress2.race(new Promise((fulfill) => stream3.end(fulfill))); + if (this._object.lastModifiedMs) + await progress2.race(import_fs36.default.promises.utimes(this.path(), new Date(this._object.lastModifiedMs), new Date(this._object.lastModifiedMs))); + } + path() { + if (typeof this._object.streamOrDirectory === "string") + return this._object.streamOrDirectory; + return this._object.streamOrDirectory.path; + } + }; + } +}); + +// packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts +var import_fs37, import_path34, BrowserContextDispatcher; +var init_browserContextDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts"() { + "use strict"; + import_fs37 = __toESM(require("fs")); + import_path34 = __toESM(require("path")); + init_urlMatch(); + init_crypto(); + init_browserContext(); + init_cdpSessionDispatcher(); + init_debuggerDispatcher(); + init_dialogDispatcher(); + init_dispatcher(); + init_frameDispatcher(); + init_networkDispatchers(); + init_pageDispatcher(); + init_crBrowser(); + init_errors(); + init_disposableDispatcher(); + init_tracingDispatcher(); + init_webSocketRouteDispatcher(); + init_writableStreamDispatcher(); + init_recorder(); + init_recorderApp(); + init_elementHandlerDispatcher(); + init_jsHandleDispatcher(); + init_disposable2(); + BrowserContextDispatcher = class _BrowserContextDispatcher extends Dispatcher { + constructor(parentScope, context2) { + const debugger_ = DebuggerDispatcher.from(parentScope, context2.debugger()); + const requestContext = APIRequestContextDispatcher.from(parentScope, context2.fetchRequest); + const tracing = TracingDispatcher.from(parentScope, context2.tracing); + super(parentScope, context2, "BrowserContext", { + debugger: debugger_, + requestContext, + tracing, + options: context2._options + }); + this._type_EventTarget = true; + this._type_BrowserContext = true; + this._subscriptions = /* @__PURE__ */ new Set(); + this._webSocketInterceptionPatterns = []; + this._disposables = []; + this._clockPaused = false; + this._interceptionUrlMatchers = []; + this.adopt(debugger_); + this.adopt(requestContext); + this.adopt(tracing); + this._requestInterceptor = (route2, request2) => { + const matchesSome = this._interceptionUrlMatchers.some((urlMatch) => urlMatches(this._context._options.baseURL, request2.url(), urlMatch)); + const routeDispatcher = this.connection.existingDispatcher(route2); + if (!matchesSome || routeDispatcher) { + route2.continue({ isFallback: true }).catch(() => { + }); + return; + } + this._dispatchEvent("route", { route: new RouteDispatcher(RequestDispatcher.from(this, request2), route2) }); + }; + this._context = context2; + for (const page of context2.pages()) + this._dispatchEvent("page", { page: PageDispatcher.from(this, page) }); + this.addObjectListener(BrowserContext.Events.Page, (page) => { + this._dispatchEvent("page", { page: PageDispatcher.from(this, page) }); + }); + this.addObjectListener(BrowserContext.Events.Close, () => { + this._dispatchEvent("close"); + this._dispose(); + }); + this.addObjectListener(BrowserContext.Events.PageError, (pageError, page) => { + this._dispatchEvent("pageError", { + error: serializeError(pageError.error), + page: PageDispatcher.from(this, page), + location: { + url: pageError.location.url, + line: pageError.location.lineNumber, + column: pageError.location.columnNumber + } + }); + }); + this.addObjectListener(BrowserContext.Events.Console, (message) => { + const pageDispatcher = PageDispatcher.fromNullable(this, message.page()); + const workerDispatcher = WorkerDispatcher.fromNullable(this, message.worker()); + if (this._shouldDispatchEvent(message.page(), "console") || workerDispatcher?._subscriptions.has("console")) { + this._dispatchEvent("console", { + page: pageDispatcher, + worker: workerDispatcher, + ...this.serializeConsoleMessage(message, workerDispatcher || pageDispatcher) + }); + } + }); + this._dialogHandler = (dialog) => { + if (!this._shouldDispatchEvent(dialog.page(), "dialog")) + return false; + this._dispatchEvent("dialog", { dialog: new DialogDispatcher(this, dialog) }); + return true; + }; + context2.dialogManager.addDialogHandler(this._dialogHandler); + if (context2._browser.options.name === "chromium" && this._object._browser instanceof CRBrowser) { + for (const serviceWorker of context2.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.Events.Request, (request2) => { + 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, request2.frame()?._page.initializedOrUndefined()) + }); + }); + this.addObjectListener(BrowserContext.Events.Response, (response2) => { + 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, response2.frame()?._page.initializedOrUndefined()) + }); + }); + this.addObjectListener(BrowserContext.Events.RequestFailed, (request2) => { + 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, request2.frame()?._page.initializedOrUndefined()) + }); + }); + this.addObjectListener(BrowserContext.Events.RequestFinished, ({ request: request2, response: response2 }) => { + 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, request2.frame()?._page.initializedOrUndefined()) + }); + }); + this.addObjectListener(BrowserContext.Events.RecorderEvent, ({ event, data, page, code }) => { + this._dispatchEvent("recorderEvent", { event, data, code, page: PageDispatcher.from(this, page) }); + }); + } + static from(parentScope, context2) { + const result2 = parentScope.connection.existingDispatcher(context2); + return result2 || new _BrowserContextDispatcher(parentScope, context2); + } + _shouldDispatchNetworkEvent(request2, event) { + return this._shouldDispatchEvent(request2.frame()?._page?.initializedOrUndefined(), event); + } + _shouldDispatchEvent(page, event) { + if (this._subscriptions.has(event)) + return true; + const pageDispatcher = page ? this.connection.existingDispatcher(page) : void 0; + if (pageDispatcher?._subscriptions.has(event)) + return true; + return false; + } + serializeConsoleMessage(message, jsScope) { + return { + 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(jsScope, a); + }), + location: message.location(), + timestamp: message.timestamp() + }; + } + async createTempFiles(params2, progress2) { + const dir = this._context._browser.options.artifactsDir; + const tmpDir = import_path34.default.join(dir, "upload-" + createGuid()); + const tempDirWithRootName = params2.rootDirName ? import_path34.default.join(tmpDir, import_path34.default.basename(params2.rootDirName)) : tmpDir; + await progress2.race(import_fs37.default.promises.mkdir(tempDirWithRootName, { recursive: true })); + this._context._tempDirs.push(tmpDir); + return { + rootDir: params2.rootDirName ? new WritableStreamDispatcher(this, tempDirWithRootName) : void 0, + writableStreams: await Promise.all(params2.items.map(async (item) => { + await progress2.race(import_fs37.default.promises.mkdir(import_path34.default.dirname(import_path34.default.join(tempDirWithRootName, item.name)), { recursive: true })); + const file = import_fs37.default.createWriteStream(import_path34.default.join(tempDirWithRootName, item.name)); + return new WritableStreamDispatcher(this, file, item.lastModifiedMs); + })) + }; + } + async exposeBinding(params2, progress2) { + const binding = await this._context.exposeBinding(progress2, params2.name, (source8, ...args) => { + if (this._disposed) + return; + const pageDispatcher = PageDispatcher.from(this, source8.page); + const binding2 = new BindingCallDispatcher(pageDispatcher, params2.name, source8, args); + this._dispatchEvent("bindingCall", { binding: binding2 }); + return binding2.promise(); + }); + this._disposables.push(binding); + return { disposable: new DisposableDispatcher(this, binding) }; + } + async newPage(params2, progress2) { + return { page: PageDispatcher.from(this, await this._context.newPage(progress2)) }; + } + async cookies(params2, progress2) { + return { cookies: await this._context.cookies(progress2, params2.urls) }; + } + async addCookies(params2, progress2) { + await progress2.race(this._context.addCookies(params2.cookies)); + } + async clearCookies(params2, progress2) { + const nameRe = params2.nameRegexSource !== void 0 && params2.nameRegexFlags !== void 0 ? new RegExp(params2.nameRegexSource, params2.nameRegexFlags) : void 0; + const domainRe = params2.domainRegexSource !== void 0 && params2.domainRegexFlags !== void 0 ? new RegExp(params2.domainRegexSource, params2.domainRegexFlags) : void 0; + const pathRe = params2.pathRegexSource !== void 0 && params2.pathRegexFlags !== void 0 ? new RegExp(params2.pathRegexSource, params2.pathRegexFlags) : void 0; + await progress2.race(this._context.clearCookies({ + name: nameRe || params2.name, + domain: domainRe || params2.domain, + path: pathRe || params2.path + })); + } + async grantPermissions(params2, progress2) { + await progress2.race(this._context.grantPermissions(params2.permissions, params2.origin)); + } + async clearPermissions(params2, progress2) { + await progress2.race(this._context.clearPermissions()); + } + async setGeolocation(params2, progress2) { + await progress2.race(this._context.setGeolocation(params2.geolocation)); + } + async setExtraHTTPHeaders(params2, progress2) { + await this._context.setExtraHTTPHeaders(progress2, params2.headers); + } + async setOffline(params2, progress2) { + await this._context.setOffline(progress2, params2.offline); + } + async setHTTPCredentials(params2, progress2) { + await this._context.setHTTPCredentials(progress2, params2.httpCredentials); + } + async addInitScript(params2, progress2) { + const initScript = await this._context.addInitScript(progress2, params2.source); + this._disposables.push(initScript); + return { disposable: new DisposableDispatcher(this, initScript) }; + } + async setNetworkInterceptionPatterns(params2, progress2) { + const hadMatchers = this._interceptionUrlMatchers.length > 0; + if (!params2.patterns.length) { + if (hadMatchers) + await progress2.race(this._context.removeRequestInterceptor(this._requestInterceptor)); + this._interceptionUrlMatchers = []; + } else { + this._interceptionUrlMatchers = params2.patterns.map(deserializeURLMatch); + if (!hadMatchers) + await this._context.addRequestInterceptor(progress2, this._requestInterceptor); + } + } + async setWebSocketInterceptionPatterns(params2, progress2) { + this._webSocketInterceptionPatterns = params2.patterns; + if (params2.patterns.length && !this._routeWebSocketInitScript) + this._routeWebSocketInitScript = await WebSocketRouteDispatcher.install(progress2, this.connection, this._context); + } + async storageState(params2, progress2) { + return await this._context.storageState(progress2, params2.indexedDB); + } + async setStorageState(params2, progress2) { + await this._context.setStorageState(progress2, params2.storageState, "api"); + } + async close(params2, progress2) { + progress2.metadata.potentiallyClosesScope = true; + await this._context.close(progress2, params2); + } + async enableRecorder(params2, progress2) { + await progress2.race(RecorderApp.show(this._context, params2)); + } + async disableRecorder(params2, progress2) { + const recorder = await progress2.race(Recorder.existingForContext(this._context)); + if (recorder) + await progress2.race(recorder.setMode("none")); + } + async exposeConsoleApi(params2, progress2) { + await this._context.exposeConsoleApi(progress2); + } + async pause(params2, progress2) { + } + async newCDPSession(params2, progress2) { + if (this._object._browser.options.browserType !== "chromium") + throw new Error(`CDP session is only available in Chromium`); + if (!params2.page && !params2.frame || params2.page && params2.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 progress2.race(crBrowserContext.newCDPSession((params2.page ? params2.page : params2.frame)._object))) }; + } + async clockFastForward(params2, progress2) { + await progress2.race(this._context.clock.fastForward(params2.ticksString ?? params2.ticksNumber ?? 0)); + } + async clockInstall(params2, progress2) { + await progress2.race(this._context.clock.install(params2.timeString ?? params2.timeNumber ?? void 0)); + } + async clockPauseAt(params2, progress2) { + await progress2.race(this._context.clock.pauseAt(params2.timeString ?? params2.timeNumber ?? 0)); + this._clockPaused = true; + } + async clockResume(params2, progress2) { + await this._context.clock.resume(progress2); + this._clockPaused = false; + } + async clockRunFor(params2, progress2) { + await progress2.race(this._context.clock.runFor(params2.ticksString ?? params2.ticksNumber ?? 0)); + } + async clockSetFixedTime(params2, progress2) { + await progress2.race(this._context.clock.setFixedTime(params2.timeString ?? params2.timeNumber ?? 0)); + } + async clockSetSystemTime(params2, progress2) { + await progress2.race(this._context.clock.setSystemTime(params2.timeString ?? params2.timeNumber ?? 0)); + } + async updateSubscription(params2, progress2) { + if (params2.enabled) + this._subscriptions.add(params2.event); + else + this._subscriptions.delete(params2.event); + } + async registerSelectorEngine(params2, progress2) { + this._object.selectors().register(params2.selectorEngine); + } + async setTestIdAttributeName(params2, progress2) { + this._object.selectors().setTestIdAttributeName(params2.testIdAttributeName); + } + _onDispose() { + if (this._context.isClosingOrClosed()) + return; + this._context.dialogManager.removeDialogHandler(this._dialogHandler); + this._interceptionUrlMatchers = []; + this._context.removeRequestInterceptor(this._requestInterceptor).catch(() => { + }); + disposeAll2(this._disposables).catch(() => { + }); + if (this._routeWebSocketInitScript) + WebSocketRouteDispatcher.uninstall(this.connection, this._context, this._routeWebSocketInitScript).catch(() => { + }); + this._routeWebSocketInitScript = void 0; + if (this._clockPaused) + this._context.clock.resumeNoReply(); + this._clockPaused = false; + } + }; + } +}); + +// packages/playwright-core/src/server/dispatchers/elementHandlerDispatcher.ts +var ElementHandleDispatcher; +var init_elementHandlerDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/elementHandlerDispatcher.ts"() { + "use strict"; + init_browserContextDispatcher(); + init_frameDispatcher(); + init_jsHandleDispatcher(); + ElementHandleDispatcher = 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 result2 = scope.connection.existingDispatcher(handle); + if (result2) + return result2; + const elementHandle = handle.asElement(); + if (!elementHandle) + return new JSHandleDispatcher(scope, handle); + return new _ElementHandleDispatcher(scope, elementHandle); + } + async ownerFrame(params2, progress2) { + const frame = await this._elementHandle.ownerFrame(progress2); + return { frame: frame ? FrameDispatcher.from(this._browserContextDispatcher(), frame) : void 0 }; + } + async contentFrame(params2, progress2) { + const frame = await this._elementHandle.contentFrame(progress2); + return { frame: frame ? FrameDispatcher.from(this._browserContextDispatcher(), frame) : void 0 }; + } + async getAttribute(params2, progress2) { + const value2 = await this._elementHandle.getAttribute(progress2, params2.name); + return { value: value2 === null ? void 0 : value2 }; + } + async inputValue(params2, progress2) { + const value2 = await this._elementHandle.inputValue(progress2); + return { value: value2 }; + } + async textContent(params2, progress2) { + const value2 = await this._elementHandle.textContent(progress2); + return { value: value2 === null ? void 0 : value2 }; + } + async innerText(params2, progress2) { + return { value: await this._elementHandle.innerText(progress2) }; + } + async innerHTML(params2, progress2) { + return { value: await this._elementHandle.innerHTML(progress2) }; + } + async isChecked(params2, progress2) { + return { value: await this._elementHandle.isChecked(progress2) }; + } + async isDisabled(params2, progress2) { + return { value: await this._elementHandle.isDisabled(progress2) }; + } + async isEditable(params2, progress2) { + return { value: await this._elementHandle.isEditable(progress2) }; + } + async isEnabled(params2, progress2) { + return { value: await this._elementHandle.isEnabled(progress2) }; + } + async isHidden(params2, progress2) { + return { value: await this._elementHandle.isHidden(progress2) }; + } + async isVisible(params2, progress2) { + return { value: await this._elementHandle.isVisible(progress2) }; + } + async dispatchEvent(params2, progress2) { + await this._elementHandle.dispatchEvent(progress2, params2.type, parseArgument(params2.eventInit)); + } + async scrollIntoViewIfNeeded(params2, progress2) { + await this._elementHandle.scrollIntoViewIfNeeded(progress2); + } + async hover(params2, progress2) { + return await this._elementHandle.hover(progress2, params2); + } + async click(params2, progress2) { + return await this._elementHandle.click(progress2, params2); + } + async dblclick(params2, progress2) { + return await this._elementHandle.dblclick(progress2, params2); + } + async tap(params2, progress2) { + return await this._elementHandle.tap(progress2, params2); + } + async selectOption(params2, progress2) { + const elements = (params2.elements || []).map((e) => e._elementHandle); + return { values: await this._elementHandle.selectOption(progress2, elements, params2.options || [], params2) }; + } + async fill(params2, progress2) { + return await this._elementHandle.fill(progress2, params2.value, params2); + } + async selectText(params2, progress2) { + await this._elementHandle.selectText(progress2, params2); + } + async setInputFiles(params2, progress2) { + return await this._elementHandle.setInputFiles(progress2, params2); + } + async focus(params2, progress2) { + await this._elementHandle.focus(progress2); + } + async type(params2, progress2) { + return await this._elementHandle.type(progress2, params2.text, params2); + } + async press(params2, progress2) { + return await this._elementHandle.press(progress2, params2.key, params2); + } + async check(params2, progress2) { + return await this._elementHandle.check(progress2, params2); + } + async uncheck(params2, progress2) { + return await this._elementHandle.uncheck(progress2, params2); + } + async boundingBox(params2, progress2) { + const value2 = await this._elementHandle.boundingBox(progress2); + return { value: value2 || void 0 }; + } + async screenshot(params2, progress2) { + const mask = (params2.mask || []).map(({ frame, selector }) => ({ + frame: frame._object, + selector + })); + return { binary: await this._elementHandle.screenshot(progress2, { ...params2, mask }) }; + } + async querySelector(params2, progress2) { + const handle = await this._elementHandle.querySelector(progress2, params2.selector, params2); + return { element: _ElementHandleDispatcher.fromNullable(this.parentScope(), handle) }; + } + async querySelectorAll(params2, progress2) { + const elements = await this._elementHandle.querySelectorAll(progress2, params2.selector); + return { elements: elements.map((e) => _ElementHandleDispatcher.from(this.parentScope(), e)) }; + } + async evalOnSelector(params2, progress2) { + return { value: serializeResult(await this._elementHandle.evalOnSelector(progress2, params2.selector, !!params2.strict, params2.expression, params2.isFunction, parseArgument(params2.arg))) }; + } + async evalOnSelectorAll(params2, progress2) { + return { value: serializeResult(await this._elementHandle.evalOnSelectorAll(progress2, params2.selector, params2.expression, params2.isFunction, parseArgument(params2.arg))) }; + } + async waitForElementState(params2, progress2) { + await this._elementHandle.waitForElementState(progress2, params2.state); + } + async waitForSelector(params2, progress2) { + return { element: _ElementHandleDispatcher.fromNullable(this.parentScope(), await this._elementHandle.waitForSelector(progress2, params2.selector, params2)) }; + } + _browserContextDispatcher() { + const parentScope = this.parentScope().parentScope(); + if (parentScope instanceof BrowserContextDispatcher) + return parentScope; + return parentScope.parentScope(); + } + }; + } +}); + +// packages/playwright-core/src/server/dispatchers/frameDispatcher.ts +var yaml2, FrameDispatcher; +var init_frameDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/frameDispatcher.ts"() { + "use strict"; + init_ariaSnapshot(); + init_frames(); + init_dispatcher(); + init_elementHandlerDispatcher(); + init_jsHandleDispatcher(); + init_networkDispatchers(); + init_networkDispatchers(); + yaml2 = require("./utilsBundle").yaml; + FrameDispatcher = 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.Events.AddLifecycle, (lifecycleEvent) => { + this._dispatchEvent("loadstate", { add: lifecycleEvent }); + }); + this.addObjectListener(Frame.Events.RemoveLifecycle, (lifecycleEvent) => { + this._dispatchEvent("loadstate", { remove: lifecycleEvent }); + }); + this.addObjectListener(Frame.Events.InternalNavigation, (event) => { + if (!event.isPublic) + return; + const params2 = { url: event.url, name: event.name, error: event.error ? event.error.message : void 0 }; + if (event.newDocument) + params2.newDocument = { request: RequestDispatcher.fromNullable(this._browserContextDispatcher, event.newDocument.request || null) }; + this._dispatchEvent("navigated", params2); + }); + } + static from(scope, frame) { + const result2 = scope.connection.existingDispatcher(frame); + return result2 || new _FrameDispatcher(scope, frame); + } + static fromNullable(scope, frame) { + if (!frame) + return; + return _FrameDispatcher.from(scope, frame); + } + async goto(params2, progress2) { + return { response: ResponseDispatcher.fromNullable(this._browserContextDispatcher, await this._frame.goto(progress2, params2.url, params2)) }; + } + async frameElement(params2, progress2) { + return { element: ElementHandleDispatcher.from(this, await this._frame.frameElement(progress2)) }; + } + async evaluateExpression(params2, progress2) { + return { value: serializeResult(await this._frame.evaluateExpression(progress2, params2.expression, { isFunction: params2.isFunction }, parseArgument(params2.arg))) }; + } + async evaluateExpressionHandle(params2, progress2) { + return { handle: ElementHandleDispatcher.fromJSOrElementHandle(this, await this._frame.evaluateExpressionHandle(progress2, params2.expression, { isFunction: params2.isFunction }, parseArgument(params2.arg))) }; + } + async waitForSelector(params2, progress2) { + return { element: ElementHandleDispatcher.fromNullable(this, await this._frame.waitForSelector(progress2, params2.selector, true, params2)) }; + } + async dispatchEvent(params2, progress2) { + return this._frame.dispatchEvent(progress2, params2.selector, params2.type, parseArgument(params2.eventInit), params2); + } + async evalOnSelector(params2, progress2) { + return { value: serializeResult(await this._frame.evalOnSelector(progress2, params2.selector, !!params2.strict, params2.expression, params2.isFunction, parseArgument(params2.arg))) }; + } + async evalOnSelectorAll(params2, progress2) { + return { value: serializeResult(await this._frame.evalOnSelectorAll(progress2, params2.selector, params2.expression, params2.isFunction, parseArgument(params2.arg))) }; + } + async querySelector(params2, progress2) { + return { element: ElementHandleDispatcher.fromNullable(this, await this._frame.querySelector(progress2, params2.selector, params2)) }; + } + async querySelectorAll(params2, progress2) { + const elements = await this._frame.querySelectorAll(progress2, params2.selector); + return { elements: elements.map((e) => ElementHandleDispatcher.from(this, e)) }; + } + async queryCount(params2, progress2) { + return { value: await this._frame.queryCount(progress2, params2.selector, params2) }; + } + async content(params2, progress2) { + return { value: await this._frame.content(progress2) }; + } + async setContent(params2, progress2) { + return await this._frame.setContent(progress2, params2.html, params2); + } + async addScriptTag(params2, progress2) { + return { element: ElementHandleDispatcher.from(this, await this._frame.addScriptTag(progress2, params2)) }; + } + async addStyleTag(params2, progress2) { + return { element: ElementHandleDispatcher.from(this, await this._frame.addStyleTag(progress2, params2)) }; + } + async ariaSnapshot(params2, progress2) { + return await this._frame.ariaSnapshot(progress2, params2); + } + async click(params2, progress2) { + progress2.metadata.potentiallyClosesScope = true; + return await this._frame.click(progress2, params2.selector, params2); + } + async dblclick(params2, progress2) { + return await this._frame.dblclick(progress2, params2.selector, params2); + } + async dragAndDrop(params2, progress2) { + return await this._frame.dragAndDrop(progress2, params2.source, params2.target, params2); + } + async drop(params2, progress2) { + return await this._frame.drop(progress2, params2.selector, params2, params2); + } + async tap(params2, progress2) { + return await this._frame.tap(progress2, params2.selector, params2); + } + async fill(params2, progress2) { + return await this._frame.fill(progress2, params2.selector, params2.value, params2); + } + async focus(params2, progress2) { + await this._frame.focus(progress2, params2.selector, params2); + } + async blur(params2, progress2) { + await this._frame.blur(progress2, params2.selector, params2); + } + async textContent(params2, progress2) { + const value2 = await this._frame.textContent(progress2, params2.selector, params2); + return { value: value2 === null ? void 0 : value2 }; + } + async innerText(params2, progress2) { + return { value: await this._frame.innerText(progress2, params2.selector, params2) }; + } + async innerHTML(params2, progress2) { + return { value: await this._frame.innerHTML(progress2, params2.selector, params2) }; + } + async resolveSelector(params2, progress2) { + return await this._frame.resolveSelector(progress2, params2.selector); + } + async getAttribute(params2, progress2) { + const value2 = await this._frame.getAttribute(progress2, params2.selector, params2.name, params2); + return { value: value2 === null ? void 0 : value2 }; + } + async inputValue(params2, progress2) { + const value2 = await this._frame.inputValue(progress2, params2.selector, params2); + return { value: value2 }; + } + async isChecked(params2, progress2) { + return { value: await this._frame.isChecked(progress2, params2.selector, params2) }; + } + async isDisabled(params2, progress2) { + return { value: await this._frame.isDisabled(progress2, params2.selector, params2) }; + } + async isEditable(params2, progress2) { + return { value: await this._frame.isEditable(progress2, params2.selector, params2) }; + } + async isEnabled(params2, progress2) { + return { value: await this._frame.isEnabled(progress2, params2.selector, params2) }; + } + async isHidden(params2, progress2) { + return { value: await this._frame.isHidden(progress2, params2.selector, params2) }; + } + async isVisible(params2, progress2) { + return { value: await this._frame.isVisible(progress2, params2.selector, params2) }; + } + async hover(params2, progress2) { + return await this._frame.hover(progress2, params2.selector, params2); + } + async selectOption(params2, progress2) { + const elements = (params2.elements || []).map((e) => e._elementHandle); + return { values: await this._frame.selectOption(progress2, params2.selector, elements, params2.options || [], params2) }; + } + async setInputFiles(params2, progress2) { + return await this._frame.setInputFiles(progress2, params2.selector, params2); + } + async type(params2, progress2) { + return await this._frame.type(progress2, params2.selector, params2.text, params2); + } + async press(params2, progress2) { + return await this._frame.press(progress2, params2.selector, params2.key, params2); + } + async check(params2, progress2) { + return await this._frame.check(progress2, params2.selector, params2); + } + async uncheck(params2, progress2) { + return await this._frame.uncheck(progress2, params2.selector, params2); + } + async waitForTimeout(params2, progress2) { + return await this._frame.waitForTimeout(progress2, params2.waitTimeout); + } + async waitForFunction(params2, progress2) { + return { handle: ElementHandleDispatcher.fromJSOrElementHandle(this, await this._frame.waitForFunctionExpression(progress2, params2.expression, params2.isFunction, parseArgument(params2.arg), params2)) }; + } + async title(params2, progress2) { + return { value: await this._frame.title(progress2) }; + } + async highlight(params2, progress2) { + return await this._frame.addHighlight(progress2, params2.selector, params2.style); + } + async hideHighlight(params2, progress2) { + return await this._frame.removeHighlight(progress2, params2.selector); + } + async expect(params2, progress2) { + progress2.metadata.potentiallyClosesScope = true; + let expectedValue = params2.expectedValue ? parseArgument(params2.expectedValue) : void 0; + if (params2.expression === "to.match.aria" && expectedValue) + expectedValue = parseAriaSnapshotUnsafe(yaml2, expectedValue); + const result2 = await this._frame.expect(progress2, params2.selector, { ...params2, expectedValue, timeoutForLogs: params2.timeout }); + const channelResult = { + matches: result2.matches, + log: result2.log, + timedOut: result2.timedOut, + errorMessage: result2.errorMessage + }; + if (result2.received !== void 0) { + channelResult.received = { + value: result2.received.value !== void 0 ? serializeResult(result2.received.value) : void 0, + ariaSnapshot: result2.received.ariaSnapshot + }; + } + return channelResult; + } + }; + } +}); + +// packages/playwright-core/src/server/dispatchers/networkDispatchers.ts +var RequestDispatcher, ResponseDispatcher, RouteDispatcher, WebSocketDispatcher, APIRequestContextDispatcher; +var init_networkDispatchers = __esm({ + "packages/playwright-core/src/server/dispatchers/networkDispatchers.ts"() { + "use strict"; + init_network2(); + init_dispatcher(); + init_frameDispatcher(); + init_pageDispatcher(); + init_tracingDispatcher(); + RequestDispatcher = class _RequestDispatcher extends Dispatcher { + static from(scope, request2) { + const result2 = scope.connection.existingDispatcher(request2); + return result2 || new _RequestDispatcher(scope, request2); + } + static fromNullable(scope, request2) { + return request2 ? _RequestDispatcher.from(scope, request2) : void 0; + } + constructor(scope, request2) { + const postData = request2.postDataBuffer(); + const frame = request2.frame(); + const page = request2.frame()?._page; + const pageDispatcher = page ? scope.connection.existingDispatcher(page) : null; + const frameDispatcher = FrameDispatcher.fromNullable(scope, frame); + super(pageDispatcher || frameDispatcher || scope, request2, "Request", { + frame: frameDispatcher, + 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; + ResponseDispatcher.fromNullable(scope, request2._existingResponse()); + } + async rawRequestHeaders(params2, progress2) { + return { headers: await this._object.rawRequestHeaders(progress2) }; + } + async response(params2, progress2) { + return { response: ResponseDispatcher.fromNullable(this._browserContextDispatcher, await this._object.response(progress2)) }; + } + }; + ResponseDispatcher = 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 requestDispatcher = RequestDispatcher.from(scope, response2.request()); + const result2 = scope.connection.existingDispatcher(response2); + return result2 || new _ResponseDispatcher(requestDispatcher, response2); + } + static fromNullable(scope, response2) { + return response2 ? _ResponseDispatcher.from(scope, response2) : void 0; + } + async body(params2, progress2) { + return { binary: await this._object.body(progress2) }; + } + async securityDetails(params2, progress2) { + return { value: await this._object.securityDetails(progress2) || void 0 }; + } + async serverAddr(params2, progress2) { + return { value: await this._object.serverAddr(progress2) || void 0 }; + } + async rawResponseHeaders(params2, progress2) { + return { headers: await this._object.rawResponseHeaders(progress2) }; + } + async httpVersion(params2, progress2) { + return { value: await this._object.httpVersion(progress2) }; + } + async sizes(params2, progress2) { + return { sizes: await this._object.sizes(progress2) }; + } + }; + RouteDispatcher = class extends Dispatcher { + constructor(scope, route2) { + super(scope, route2, "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(params2, progress2) { + this._checkNotHandled(); + await progress2.race(this._object.continue({ + url: params2.url, + method: params2.method, + headers: params2.headers, + postData: params2.postData, + isFallback: params2.isFallback + })); + } + async fulfill(params2, progress2) { + this._checkNotHandled(); + await progress2.race(this._object.fulfill(params2)); + } + async abort(params2, progress2) { + this._checkNotHandled(); + await progress2.race(this._object.abort(params2.errorCode || "failed")); + } + async redirectNavigationRequest(params2, progress2) { + this._checkNotHandled(); + this._object.redirectNavigationRequest(params2.url); + } + }; + WebSocketDispatcher = class extends Dispatcher { + constructor(scope, webSocket) { + super(scope, webSocket, "WebSocket", { + url: webSocket.url() + }); + this._type_EventTarget = true; + this._type_WebSocket = true; + this.addObjectListener(WebSocket.Events.FrameSent, (event) => this._dispatchEvent("frameSent", event)); + this.addObjectListener(WebSocket.Events.FrameReceived, (event) => this._dispatchEvent("frameReceived", event)); + this.addObjectListener(WebSocket.Events.SocketError, (error) => this._dispatchEvent("socketError", { error })); + this.addObjectListener(WebSocket.Events.Close, () => this._dispatchEvent("close", {})); + } + }; + APIRequestContextDispatcher = 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 result2 = scope.connection.existingDispatcher(request2); + return result2 || new _APIRequestContextDispatcher(scope, request2); + } + static fromNullable(scope, request2) { + return request2 ? _APIRequestContextDispatcher.from(scope, request2) : void 0; + } + async storageState(params2, progress2) { + return await this._object.storageState(progress2, params2.indexedDB); + } + async dispose(params2, progress2) { + progress2.metadata.potentiallyClosesScope = true; + await progress2.race(this._object.dispose(params2)); + this._dispose(); + } + async fetch(params2, progress2) { + const response2 = await this._object.fetch(progress2, params2); + return { response: response2 }; + } + async fetchResponseBody(params2, progress2) { + return { binary: this._object.fetchResponseBody(progress2, params2.fetchUid) }; + } + async fetchLog(params2, progress2) { + return { log: this._object.fetchLogForUid(progress2, params2.fetchUid) }; + } + async disposeAPIResponse(params2, progress2) { + this._object.disposeResponse(progress2, params2.fetchUid); + } + }; + } +}); + +// packages/playwright-core/src/server/dispatchers/androidDispatcher.ts +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); +} +var AndroidDispatcher, AndroidDeviceDispatcher, SocketSdkObject, AndroidSocketDispatcher, keyMap; +var init_androidDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/androidDispatcher.ts"() { + "use strict"; + init_eventsHelper(); + init_browserContextDispatcher(); + init_dispatcher(); + init_android(); + init_instrumentation(); + AndroidDispatcher = class extends Dispatcher { + constructor(scope, android, denyLaunch) { + super(scope, android, "Android", {}); + this._type_Android = true; + this._denyLaunch = denyLaunch; + } + async devices(params2, progress2) { + if (this._denyLaunch) + throw new Error(`Connecting to Android devices is not allowed.`); + const devices = await this._object.devices(progress2, params2); + return { + devices: devices.map((d) => AndroidDeviceDispatcher.from(this, d)) + }; + } + }; + AndroidDeviceDispatcher = 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.Events.WebViewAdded, (webView) => this._dispatchEvent("webViewAdded", { webView })); + this.addObjectListener(AndroidDevice.Events.WebViewRemoved, (socketName) => this._dispatchEvent("webViewRemoved", { socketName })); + this.addObjectListener(AndroidDevice.Events.Close, () => this._dispatchEvent("close")); + } + static from(scope, device) { + const result2 = scope.connection.existingDispatcher(device); + return result2 || new _AndroidDeviceDispatcher(scope, device); + } + async wait(params2, progress2) { + await this._object.send(progress2, "wait", params2); + } + async fill(params2, progress2) { + await this._object.send(progress2, "click", { selector: params2.androidSelector }); + await this._object.send(progress2, "fill", params2); + } + async tap(params2, progress2) { + await this._object.send(progress2, "click", params2); + } + async drag(params2, progress2) { + await this._object.send(progress2, "drag", params2); + } + async fling(params2, progress2) { + await this._object.send(progress2, "fling", params2); + } + async longTap(params2, progress2) { + await this._object.send(progress2, "longClick", params2); + } + async pinchClose(params2, progress2) { + await this._object.send(progress2, "pinchClose", params2); + } + async pinchOpen(params2, progress2) { + await this._object.send(progress2, "pinchOpen", params2); + } + async scroll(params2, progress2) { + await this._object.send(progress2, "scroll", params2); + } + async swipe(params2, progress2) { + await this._object.send(progress2, "swipe", params2); + } + async info(params2, progress2) { + const info = await this._object.send(progress2, "info", params2); + fixupAndroidElementInfo(info); + return { info }; + } + async inputType(params2, progress2) { + const text2 = params2.text; + const keyCodes = []; + for (let i = 0; i < text2.length; ++i) { + const code = keyMap.get(text2[i].toUpperCase()); + if (code === void 0) + throw new Error("No mapping for " + text2[i] + " found"); + keyCodes.push(code); + } + await progress2.race(Promise.all(keyCodes.map((keyCode) => this._object.send(progress2, "inputPress", { keyCode })))); + } + async inputPress(params2, progress2) { + if (!keyMap.has(params2.key)) + throw new Error("Unknown key: " + params2.key); + await this._object.send(progress2, "inputPress", { keyCode: keyMap.get(params2.key) }); + } + async inputTap(params2, progress2) { + await this._object.send(progress2, "inputClick", params2); + } + async inputSwipe(params2, progress2) { + await this._object.send(progress2, "inputSwipe", params2); + } + async inputDrag(params2, progress2) { + await this._object.send(progress2, "inputDrag", params2); + } + async screenshot(params2, progress2) { + return { binary: await this._object.screenshot(progress2) }; + } + async shell(params2, progress2) { + return { result: await this._object.shell(progress2, params2.command) }; + } + async open(params2, progress2) { + const socket = await this._object.open(progress2, params2.command); + return { socket: new AndroidSocketDispatcher(this, new SocketSdkObject(this._object, socket)) }; + } + async installApk(params2, progress2) { + await this._object.installApk(progress2, params2.file, { args: params2.args }); + } + async push(params2, progress2) { + await this._object.push(progress2, params2.file, params2.path, params2.mode); + } + async launchBrowser(params2, progress2) { + const context2 = await this._object.launchBrowser(progress2, params2.pkg, params2); + return { context: BrowserContextDispatcher.from(this, context2) }; + } + async close(params2, progress2) { + await this._object.close(progress2); + } + async connectToWebView(params2, progress2) { + return { context: BrowserContextDispatcher.from(this, await this._object.connectToWebView(progress2, params2.socketName)) }; + } + }; + SocketSdkObject = class extends SdkObject { + constructor(parent, socket) { + super(parent, "socket"); + this._socket = socket; + this._eventListeners = [ + eventsHelper.addEventListener(socket, "data", (data) => this.emit("data", data)), + eventsHelper.addEventListener(socket, "close", () => { + eventsHelper.removeEventListeners(this._eventListeners); + this.emit("close"); + }) + ]; + } + async write(data) { + await this._socket.write(data); + } + close() { + this._socket.close(); + } + }; + AndroidSocketDispatcher = class extends Dispatcher { + constructor(scope, socket) { + super(scope, socket, "AndroidSocket", {}); + this._type_AndroidSocket = true; + this.addObjectListener("data", (data) => this._dispatchEvent("data", { data })); + this.addObjectListener("close", () => { + this._dispatchEvent("close"); + this._dispose(); + }); + } + async write(params2, progress2) { + await progress2.race(this._object.write(params2.data)); + } + async close(params2, progress2) { + this._object.close(); + } + }; + 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], + ["MediaPlayPause", 85], + ["MediaStop", 86], + ["MediaNext", 87], + ["MediaPrevious", 88], + ["MediaRewind", 89], + ["MediaFastForward", 90], + ["MediaPlay", 126], + ["MediaPause", 127], + ["MediaClose", 128], + ["MediaEject", 129], + ["MediaRecord", 130], + ["ChannelUp", 166], + ["ChannelDown", 167], + ["AppSwitch", 187], + ["Assist", 219], + ["MediaAudioTrack", 222], + ["MediaTopMenu", 226], + ["MediaSkipForward", 272], + ["MediaSkipBackward", 273], + ["MediaStepForward", 274], + ["MediaStepBackward", 275], + ["Cut", 277], + ["Copy", 278], + ["Paste", 279] + ]); + } +}); + +// packages/playwright-core/src/server/dispatchers/browserDispatcher.ts +var BrowserDispatcher; +var init_browserDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/browserDispatcher.ts"() { + "use strict"; + init_browser(); + init_browserContextDispatcher(); + init_cdpSessionDispatcher(); + init_dispatcher(); + init_browserContext(); + init_artifactDispatcher(); + init_progress(); + BrowserDispatcher = class extends Dispatcher { + constructor(scope, browser, options2 = {}) { + super(scope, browser, "Browser", { version: browser.version(), name: browser.options.name, browserName: browser.options.browserType }); + this._type_Browser = true; + this._isolatedContexts = /* @__PURE__ */ new Set(); + this._options = options2; + if (!options2.isolateContexts) { + this.addObjectListener(Browser.Events.Context, (context2) => this._dispatchEvent("context", { context: BrowserContextDispatcher.from(this, context2) })); + this.addObjectListener(Browser.Events.Disconnected, () => this._didClose()); + if (browser._defaultContext) + this._dispatchEvent("context", { context: BrowserContextDispatcher.from(this, browser._defaultContext) }); + for (const context2 of browser.contexts()) + this._dispatchEvent("context", { context: BrowserContextDispatcher.from(this, context2) }); + } + } + _didClose() { + this._dispatchEvent("close"); + this._dispose(); + } + async newContext(params2, progress2) { + if (params2.recordVideo && this._object.attribution.playwright.options.isServer) + params2.recordVideo.dir = void 0; + if (!this._options.isolateContexts) { + const context3 = await this._object.newContext(progress2, params2); + const contextDispatcher2 = BrowserContextDispatcher.from(this, context3); + return { context: contextDispatcher2 }; + } + const context2 = await this._object.newContext(progress2, params2); + this._isolatedContexts.add(context2); + context2.on(BrowserContext.Events.Close, () => this._isolatedContexts.delete(context2)); + const contextDispatcher = BrowserContextDispatcher.from(this, context2); + this._dispatchEvent("context", { context: contextDispatcher }); + return { context: contextDispatcher }; + } + async newContextForReuse(params2, progress2) { + const context2 = await this._object.newContextForReuse(progress2, params2); + const contextDispatcher = BrowserContextDispatcher.from(this, context2); + this._dispatchEvent("context", { context: contextDispatcher }); + return { context: contextDispatcher }; + } + async disconnectFromReusedContext(params2, progress2) { + const context2 = this._object.contextForReuse(); + const contextDispatcher = context2 ? this.connection.existingDispatcher(context2) : void 0; + if (contextDispatcher) { + await progress2.race(contextDispatcher.stopPendingOperations(new Error(params2.reason))); + contextDispatcher._dispose(); + } + } + async close(params2, progress2) { + if (this._options.ignoreStopAndKill) + return; + progress2.metadata.potentiallyClosesScope = true; + await this._object.close(progress2, params2); + } + async killForTests(params2, progress2) { + if (this._options.ignoreStopAndKill) + return; + progress2.metadata.potentiallyClosesScope = true; + await this._object.killForTests(progress2); + } + async defaultUserAgentForTest() { + return { userAgent: this._object.userAgent() }; + } + async newBrowserCDPSession(params2, progress2) { + if (this._object.options.browserType !== "chromium") + throw new Error(`CDP session is only available in Chromium`); + const crBrowser = this._object; + return { session: new CDPSessionDispatcher(this, await progress2.race(crBrowser.newBrowserCDPSession())) }; + } + async startTracing(params2, progress2) { + if (this._object.options.browserType !== "chromium") + throw new Error(`Tracing is only available in Chromium`); + const crBrowser = this._object; + await progress2.race(crBrowser.startTracing(params2.page ? params2.page._object : void 0, params2)); + } + async stopTracing(params2, progress2) { + if (this._object.options.browserType !== "chromium") + throw new Error(`Tracing is only available in Chromium`); + const crBrowser = this._object; + return { artifact: ArtifactDispatcher.from(this, await progress2.race(crBrowser.stopTracing())) }; + } + async startServer(params2, progress2) { + return await this._object.startServer(progress2, params2.title, params2); + } + async stopServer(params2, progress2) { + await this._object.stopServer(progress2); + } + async cleanupContexts() { + await Promise.all(Array.from(this._isolatedContexts).map((context2) => context2.close(nullProgress, { reason: "Global context cleanup (connection terminated)" }))); + } + }; + } +}); + +// packages/playwright-core/src/server/dispatchers/browserTypeDispatcher.ts +var BrowserTypeDispatcher; +var init_browserTypeDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/browserTypeDispatcher.ts"() { + "use strict"; + init_browserContextDispatcher(); + init_browserDispatcher(); + init_pageDispatcher(); + init_dispatcher(); + BrowserTypeDispatcher = class extends Dispatcher { + constructor(scope, browserType, denyLaunch) { + super(scope, browserType, "BrowserType", { + executablePath: browserType.executablePath(), + name: browserType.name() + }); + this._type_BrowserType = true; + this._denyLaunch = denyLaunch; + } + async launch(params2, progress2) { + if (this._denyLaunch) + throw new Error(`Launching more browsers is not allowed.`); + const browser = await this._object.launch(progress2, params2); + return { browser: new BrowserDispatcher(this, browser) }; + } + async launchPersistentContext(params2, progress2) { + if (this._denyLaunch) + throw new Error(`Launching more browsers is not allowed.`); + const browserContext = await this._object.launchPersistentContext(progress2, params2.userDataDir, params2); + const browserDispatcher = new BrowserDispatcher(this, browserContext._browser); + const contextDispatcher = BrowserContextDispatcher.from(browserDispatcher, browserContext); + return { browser: browserDispatcher, context: contextDispatcher }; + } + async connectOverCDP(params2, progress2) { + if (this._denyLaunch) + throw new Error(`Launching more browsers is not allowed.`); + const browser = await this._object.connectOverCDP(progress2, params2.endpointURL, params2); + const browserDispatcher = new BrowserDispatcher(this, browser); + return { + browser: browserDispatcher, + defaultContext: browser._defaultContext ? BrowserContextDispatcher.from(browserDispatcher, browser._defaultContext) : void 0 + }; + } + async connectToWorker(params2, progress2) { + if (this._denyLaunch) + throw new Error(`Launching more browsers is not allowed.`); + const worker = await this._object.connectToWorker(progress2, params2.endpoint); + return { worker: new WorkerDispatcher(this, worker) }; + } + }; + } +}); + +// packages/playwright-core/src/server/dispatchers/electronDispatcher.ts +var ElectronDispatcher, ElectronApplicationDispatcher; +var init_electronDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/electronDispatcher.ts"() { + "use strict"; + init_browserContextDispatcher(); + init_dispatcher(); + init_jsHandleDispatcher(); + init_electron(); + ElectronDispatcher = class extends Dispatcher { + constructor(scope, electron, denyLaunch) { + super(scope, electron, "Electron", {}); + this._type_Electron = true; + this._denyLaunch = denyLaunch; + } + async launch(params2, progress2) { + if (this._denyLaunch) + throw new Error(`Launching more browsers is not allowed.`); + const electronApplication = await this._object.launch(progress2, params2); + return { electronApplication: new ElectronApplicationDispatcher(this, electronApplication) }; + } + }; + ElectronApplicationDispatcher = class 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.Events.Close, () => { + this._dispatchEvent("close"); + this._dispose(); + }); + this.addObjectListener(ElectronApplication.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(), + timestamp: message.timestamp() + }); + }); + } + async browserWindow(params2, progress2) { + const handle = await this._object.browserWindow(progress2, params2.page.page()); + return { handle: JSHandleDispatcher.fromJSHandle(this, handle) }; + } + async evaluateExpression(params2, progress2) { + const handle = await progress2.race(this._object._nodeElectronHandlePromise); + return { value: serializeResult(await handle.evaluateExpression(progress2, params2.expression, { isFunction: params2.isFunction }, parseArgument(params2.arg))) }; + } + async evaluateExpressionHandle(params2, progress2) { + const handle = await progress2.race(this._object._nodeElectronHandlePromise); + const result2 = await handle.evaluateExpressionHandle(progress2, params2.expression, { isFunction: params2.isFunction }, parseArgument(params2.arg)); + return { handle: JSHandleDispatcher.fromJSHandle(this, result2) }; + } + async updateSubscription(params2, progress2) { + if (params2.enabled) + this._subscriptions.add(params2.event); + else + this._subscriptions.delete(params2.event); + } + }; + } +}); + +// packages/playwright-core/src/server/harBackend.ts +function countMatchingHeaders(harHeaders, headers) { + const set = new Set(headers.map((h) => h.name.toLowerCase() + ":" + h.value)); + let matches = 0; + for (const h of harHeaders) { + if (set.has(h.name.toLowerCase() + ":" + h.value)) + ++matches; + } + return matches; +} +function multipartBoundary(headers) { + const contentType = headers.find((h) => h.name.toLowerCase() === "content-type"); + if (!contentType?.value.includes("multipart/form-data")) + return void 0; + const boundary = contentType.value.match(/boundary=(\S+)/); + if (boundary) + return boundary[1]; + return void 0; +} +var import_fs38, import_path35, redirectStatus2, HarBackend; +var init_harBackend = __esm({ + "packages/playwright-core/src/server/harBackend.ts"() { + "use strict"; + import_fs38 = __toESM(require("fs")); + import_path35 = __toESM(require("path")); + init_crypto(); + init_fileUtils(); + redirectStatus2 = [301, 302, 303, 307, 308]; + HarBackend = class { + 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 buffer = await this._loadContent(response2.content); + return { + action: "fulfill", + status: response2.status, + headers: response2.headers, + body: buffer + }; + } catch (e) { + return { action: "error", message: e.message }; + } + } + async _loadContent(content) { + const file = content._file; + let buffer; + if (file) { + if (this._zipFile) { + buffer = await this._zipFile.read(file); + } else { + const resolved = import_path35.default.resolve(this._baseDir, file); + if (!isPathInside(this._baseDir, resolved)) + throw new Error(`HAR entry _file escapes base directory: ${file}`); + buffer = await import_fs38.default.promises.readFile(resolved); + } + } else { + buffer = Buffer.from(content.text || "", content.encoding === "base64" ? "base64" : "utf-8"); + } + return buffer; + } + 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 buffer = await this._loadContent(candidate.request.postData); + if (!buffer.equals(postData)) { + const boundary = multipartBoundary(headers); + if (!boundary) + continue; + const candidataBoundary = multipartBoundary(candidate.request.headers); + if (!candidataBoundary) + continue; + if (postData.toString().replaceAll(boundary, "") !== buffer.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 (redirectStatus2.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() { + this._zipFile?.close(); + } + }; + } +}); + +// packages/playwright-core/src/server/localUtils.ts +async function zip(progress2, stackSessions, params2) { + const promise = new ManualPromise(); + const zipFile = new yazl2.ZipFile(); + zipFile.on("error", (error) => promise.reject(error)); + const addFile = (file, name) => { + try { + if (import_fs39.default.statSync(file).isFile()) + zipFile.addFile(file, name); + } catch (e) { + } + }; + for (const entry of params2.entries) + addFile(entry.value, entry.name); + const stackSession = params2.stacksId ? stackSessions.get(params2.stacksId) : void 0; + if (stackSession?.callStacks.length) { + await progress2.race(stackSession.writer); + const buffer = Buffer.from(JSON.stringify(serializeClientSideCallMetadata(stackSession.callStacks))); + zipFile.addBuffer(buffer, "trace.stacks"); + } + if (params2.includeSources) { + const sourceFiles = new Set(params2.additionalSources); + for (const { stack } of stackSession?.callStacks || []) { + if (!stack) + continue; + for (const { file } of stack) + sourceFiles.add(file); + } + for (const sourceFile of sourceFiles) + addFile(sourceFile, "resources/src@" + calculateSha1(sourceFile) + ".txt"); + } + if (params2.mode === "write") { + await progress2.race(import_fs39.default.promises.mkdir(import_path36.default.dirname(params2.zipFile), { recursive: true })); + zipFile.end(void 0, () => { + zipFile.outputStream.pipe(import_fs39.default.createWriteStream(params2.zipFile)).on("close", () => promise.resolve()).on("error", (error) => promise.reject(error)); + }); + await progress2.race(promise); + await deleteStackSession(progress2, stackSessions, params2.stacksId); + return; + } + const tempFile = params2.zipFile + ".tmp"; + await progress2.race(import_fs39.default.promises.rename(params2.zipFile, tempFile)); + yauzl3.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(import_fs39.default.createWriteStream(params2.zipFile)).on("close", () => { + import_fs39.default.promises.unlink(tempFile).then(() => { + promise.resolve(); + }).catch((error) => promise.reject(error)); + }); + }); + } + }); + }); + }); + await progress2.race(promise); + await deleteStackSession(progress2, stackSessions, params2.stacksId); +} +async function deleteStackSession(progress2, stackSessions, stacksId) { + const session2 = stacksId ? stackSessions.get(stacksId) : void 0; + if (!session2) + return; + await progress2.race(session2.writer); + stackSessions.delete(stacksId); + if (session2.tmpDir) + await progress2.race(removeFolders([session2.tmpDir])); +} +async function harOpen(progress2, harBackends, params2) { + let harBackend; + if (params2.file.endsWith(".zip")) { + const zipFile = new ZipFile(params2.file); + try { + const entryNames = await progress2.race(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 progress2.race(zipFile.read(harEntryName)); + const harFile = JSON.parse(har.toString()); + harBackend = new HarBackend(harFile, null, zipFile); + } catch (error) { + zipFile.close(); + throw error; + } + } else { + const harFile = JSON.parse(await progress2.race(import_fs39.default.promises.readFile(params2.file, "utf-8"))); + harBackend = new HarBackend(harFile, import_path36.default.dirname(params2.file), null); + } + harBackends.set(harBackend.id, harBackend); + return { harId: harBackend.id }; +} +async function harLookup(progress2, harBackends, params2) { + const harBackend = harBackends.get(params2.harId); + if (!harBackend) + return { action: "error", message: `Internal error: har was not opened` }; + return await progress2.race(harBackend.lookup(params2.url, params2.method, params2.headers, params2.postData, params2.isNavigationRequest)); +} +function harClose(harBackends, params2) { + const harBackend = harBackends.get(params2.harId); + if (harBackend) { + harBackends.delete(harBackend.id); + harBackend.dispose(); + } +} +async function harUnzip(progress2, params2) { + const resourcesDir = params2.resourcesDir ?? import_path36.default.dirname(params2.zipFile); + const zipFile = new ZipFile(params2.zipFile); + let resourcesDirCreated = false; + try { + for (const entry of await progress2.race(zipFile.entries())) { + const buffer = await progress2.race(zipFile.read(entry)); + if (entry === "har.har") { + await progress2.race(import_fs39.default.promises.writeFile(params2.harFile, buffer)); + } else { + if (!resourcesDirCreated) { + await progress2.race(import_fs39.default.promises.mkdir(resourcesDir, { recursive: true })); + resourcesDirCreated = true; + } + const outPath = resolveWithinRoot(resourcesDir, entry); + if (!outPath) + throw new Error(`HAR zip entry '${entry}' escapes output directory`); + await progress2.race(import_fs39.default.promises.writeFile(outPath, buffer)); + } + } + await progress2.race(import_fs39.default.promises.unlink(params2.zipFile)); + } finally { + zipFile.close(); + } +} +async function tracingStarted(progress2, stackSessions, params2) { + let tmpDir = void 0; + if (!params2.tracesDir) + tmpDir = await progress2.race(import_fs39.default.promises.mkdtemp(import_path36.default.join(import_os17.default.tmpdir(), "playwright-tracing-"))); + const traceStacksFile = import_path36.default.join(params2.tracesDir || tmpDir, params2.traceName + ".stacks"); + stackSessions.set(traceStacksFile, { callStacks: [], file: traceStacksFile, writer: Promise.resolve(), tmpDir, live: params2.live }); + return { stacksId: traceStacksFile }; +} +async function traceDiscarded(progress2, stackSessions, params2) { + await deleteStackSession(progress2, stackSessions, params2.stacksId); +} +function addStackToTracingNoReply(stackSessions, params2) { + for (const session2 of stackSessions.values()) { + session2.callStacks.push(params2.callData); + if (session2.live) { + session2.writer = session2.writer.then(() => { + const buffer = Buffer.from(JSON.stringify(serializeClientSideCallMetadata(session2.callStacks))); + return import_fs39.default.promises.writeFile(session2.file, buffer); + }); + } + } +} +var import_fs39, import_os17, import_path36, yauzl3, yazl2; +var init_localUtils = __esm({ + "packages/playwright-core/src/server/localUtils.ts"() { + "use strict"; + import_fs39 = __toESM(require("fs")); + import_os17 = __toESM(require("os")); + import_path36 = __toESM(require("path")); + yauzl3 = __toESM(require_yauzl()); + init_manualPromise(); + init_traceUtils(); + init_assert(); + init_crypto(); + init_zipFile(); + init_fileUtils(); + init_harBackend(); + yazl2 = require("./utilsBundle").yazl; + } +}); + +// packages/playwright-core/src/server/dispatchers/jsonPipeDispatcher.ts +var JsonPipeDispatcher; +var init_jsonPipeDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/jsonPipeDispatcher.ts"() { + "use strict"; + init_dispatcher(); + init_instrumentation(); + JsonPipeDispatcher = class extends Dispatcher { + constructor(scope) { + super(scope, new SdkObject(scope._object, "jsonPipe"), "JsonPipe", {}); + this._type_JsonPipe = true; + } + async send(params2, progress2) { + this.emit("message", params2.message); + } + async close(params2, progress2) { + 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(); + } + }; + } +}); + +// packages/playwright-core/src/server/socksInterceptor.ts +function tChannelForSocks(names, arg, path59, context2) { + throw new ValidationError(`${path59}: channels are not expected in SocksSupport`); +} +var import_events14, SocksInterceptor; +var init_socksInterceptor = __esm({ + "packages/playwright-core/src/server/socksInterceptor.ts"() { + "use strict"; + import_events14 = __toESM(require("events")); + init_socksProxy(); + init_debug(); + init_validator(); + SocksInterceptor = class { + constructor(transport, pattern, redirectPortForTest) { + this._ids = /* @__PURE__ */ new Set(); + this._handler = new SocksProxyHandler(pattern, redirectPortForTest); + let lastId = -1; + this._channel = new Proxy(new import_events14.default(), { + get: (obj, prop) => { + if (prop in obj || obj[prop] !== void 0 || typeof prop !== "string") + return obj[prop]; + return (params2) => { + try { + const id = --lastId; + this._ids.add(id); + const validator = findValidator("SocksSupport", prop, "Params"); + params2 = validator(params2, "", { tChannelImpl: tChannelForSocks, binary: "toBase64", isUnderTest }); + transport.send({ id, guid: this._socksSupportObjectGuid, method: prop, params: params2, 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 params2 = validator(message.params, "", { tChannelImpl: tChannelForSocks, binary: "fromBase64", isUnderTest }); + this._channel.emit(message.method, params2); + return true; + } + return false; + } + }; + } +}); + +// packages/playwright-core/src/server/dispatchers/localUtilsDispatcher.ts +async function urlToWSEndpoint2(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(progress2, { + url: fetchUrl.toString(), + method: "GET", + headers: { "User-Agent": getUserAgent() } + }, async (params2, 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://.`); + }); + 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(); +} +var import_net7, LocalUtilsDispatcher; +var init_localUtilsDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/localUtilsDispatcher.ts"() { + "use strict"; + import_net7 = __toESM(require("net")); + init_urlMatch(); + init_utils2(); + init_userAgent(); + init_dispatcher(); + init_instrumentation(); + init_localUtils(); + init_deviceDescriptors(); + init_jsonPipeDispatcher(); + init_pipeTransport2(); + init_socksInterceptor(); + init_transport(); + LocalUtilsDispatcher = class extends Dispatcher { + constructor(scope, playwright2) { + const localUtils = new SdkObject(playwright2, "localUtils", "localUtils"); + localUtils.logName = "browser"; + const deviceDescriptors2 = Object.entries(deviceDescriptors).map(([name, descriptor]) => ({ name, descriptor })); + super(scope, localUtils, "LocalUtils", { + deviceDescriptors: deviceDescriptors2 + }); + this._harBackends = /* @__PURE__ */ new Map(); + this._stackSessions = /* @__PURE__ */ new Map(); + this._type_LocalUtils = true; + } + async zip(params2, progress2) { + return await zip(progress2, this._stackSessions, params2); + } + async harOpen(params2, progress2) { + return await harOpen(progress2, this._harBackends, params2); + } + async harLookup(params2, progress2) { + return await harLookup(progress2, this._harBackends, params2); + } + async harClose(params2, progress2) { + harClose(this._harBackends, params2); + } + async harUnzip(params2, progress2) { + return await harUnzip(progress2, params2); + } + async tracingStarted(params2, progress2) { + return await tracingStarted(progress2, this._stackSessions, params2); + } + async traceDiscarded(params2, progress2) { + return await traceDiscarded(progress2, this._stackSessions, params2); + } + async addStackToTracingNoReply(params2, progress2) { + addStackToTracingNoReply(this._stackSessions, params2); + } + async connect(params2, progress2) { + if (URL.canParse(params2.endpoint)) + return await this._connectOverWebSocket(progress2, params2); + return await progress2.race(this._connectOverPipe(params2)); + } + async _connectOverWebSocket(progress2, params2) { + const wsHeaders = { + "User-Agent": getUserAgent(), + "x-playwright-proxy": params2.exposeNetwork ?? "", + ...params2.headers + }; + const wsEndpoint = await urlToWSEndpoint2(progress2, params2.endpoint); + const transport = await WebSocketTransport.connect(progress2, wsEndpoint, { headers: wsHeaders, followRedirects: true, debugLogHeader: "x-playwright-debug-log" }); + const socksInterceptor = new SocksInterceptor(transport, params2.exposeNetwork, params2.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 (params2.slowMo) + setTimeout(cb, params2.slowMo); + else + cb(); + }; + pipe.on("message", (message) => { + transport.send(message); + }); + transport.onclose = (reason) => { + socksInterceptor?.cleanup(); + pipe.wasClosed(reason); + }; + pipe.on("close", () => transport.close()); + return { pipe, headers: transport.headers }; + } + async _connectOverPipe(params2) { + const socket = await new Promise((resolve, reject) => { + const conn = import_net7.default.connect(params2.endpoint, () => resolve(conn)); + conn.on("error", reject); + }); + const transport = new PipeTransport2(socket, socket); + const pipe = new JsonPipeDispatcher(this); + transport.onmessage = (json) => { + const cb = () => { + try { + pipe.dispatch(json); + } catch (e) { + transport.close(); + } + }; + if (params2.slowMo) + setTimeout(cb, params2.slowMo); + else + cb(); + }; + pipe.on("message", (message) => { + transport.send(message); + }); + transport.onclose = (reason) => { + pipe.wasClosed(reason); + }; + pipe.on("close", () => socket.end()); + return { pipe, headers: [] }; + } + async globToRegex(params2, progress2) { + const regex = resolveGlobToRegexPattern(params2.baseURL, params2.glob, params2.webSocketUrl); + return { regex }; + } + }; + } +}); + +// packages/playwright-core/src/server/dispatchers/playwrightDispatcher.ts +var PlaywrightDispatcher, SocksSupportDispatcher; +var init_playwrightDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/playwrightDispatcher.ts"() { + "use strict"; + init_socksProxy(); + init_eventsHelper(); + init_fetch(); + init_androidDispatcher(); + init_androidDispatcher(); + init_browserDispatcher(); + init_browserTypeDispatcher(); + init_dispatcher(); + init_electronDispatcher(); + init_localUtilsDispatcher(); + init_networkDispatchers(); + init_instrumentation(); + PlaywrightDispatcher = class extends Dispatcher { + constructor(scope, playwright2, options2 = {}) { + const denyLaunch = options2.denyLaunch ?? false; + const chromium = new BrowserTypeDispatcher(scope, playwright2.chromium, denyLaunch); + const firefox = new BrowserTypeDispatcher(scope, playwright2.firefox, denyLaunch); + const webkit = new BrowserTypeDispatcher(scope, playwright2.webkit, denyLaunch); + const android = new AndroidDispatcher(scope, playwright2.android, denyLaunch); + const initializer = { + chromium, + firefox, + webkit, + android, + electron: new ElectronDispatcher(scope, playwright2.electron, denyLaunch), + utils: playwright2.options.isServer ? void 0 : new LocalUtilsDispatcher(scope, playwright2), + socksSupport: options2.socksProxy ? new SocksSupportDispatcher(scope, playwright2, options2.socksProxy) : void 0 + }; + let browserDispatcher; + if (options2.preLaunchedBrowser) { + const browserTypeDispatcher = initializer[options2.preLaunchedBrowser.options.name]; + browserDispatcher = new BrowserDispatcher(browserTypeDispatcher, options2.preLaunchedBrowser, { + ignoreStopAndKill: true, + isolateContexts: !options2.sharedBrowser + }); + initializer.preLaunchedBrowser = browserDispatcher; + } + if (options2.preLaunchedAndroidDevice) + initializer.preConnectedAndroidDevice = new AndroidDeviceDispatcher(android, options2.preLaunchedAndroidDevice); + super(scope, playwright2, "Playwright", initializer); + this._type_Playwright = true; + this._browserDispatcher = browserDispatcher; + this._denyLaunch = denyLaunch; + } + async newRequest(params2, progress2) { + if (this._denyLaunch) + throw new Error(`Creating new API request contexts is not allowed.`); + const request2 = new GlobalAPIRequestContext(this._object, params2); + return { request: APIRequestContextDispatcher.from(this.parentScope(), request2) }; + } + async cleanup() { + await this._browserDispatcher?.cleanupContexts(); + } + }; + SocksSupportDispatcher = class extends Dispatcher { + constructor(scope, parent, socksProxy) { + super(scope, new SdkObject(parent, "socksSupport"), "SocksSupport", {}); + this._type_SocksSupport = true; + this._socksProxy = socksProxy; + this._socksListeners = [ + eventsHelper.addEventListener(socksProxy, SocksProxy.Events.SocksRequested, (payload) => this._dispatchEvent("socksRequested", payload)), + eventsHelper.addEventListener(socksProxy, SocksProxy.Events.SocksData, (payload) => this._dispatchEvent("socksData", payload)), + eventsHelper.addEventListener(socksProxy, SocksProxy.Events.SocksClosed, (payload) => this._dispatchEvent("socksClosed", payload)) + ]; + } + async socksConnected(params2, progress2) { + this._socksProxy?.socketConnected(params2); + } + async socksFailed(params2, progress2) { + this._socksProxy?.socketFailed(params2); + } + async socksData(params2, progress2) { + this._socksProxy?.sendSocketData(params2); + } + async socksError(params2, progress2) { + this._socksProxy?.sendSocketError(params2); + } + async socksEnd(params2, progress2) { + this._socksProxy?.sendSocketEnd(params2); + } + _onDispose() { + eventsHelper.removeEventListeners(this._socksListeners); + } + }; + } +}); + +// packages/playwright-core/src/server/trace/viewer/traceViewer.ts +function validateTraceUrlOrPath(traceFileOrUrl) { + if (!traceFileOrUrl) + return traceFileOrUrl; + if (traceFileOrUrl.startsWith("http://") || traceFileOrUrl.startsWith("https://")) + return traceFileOrUrl; + let traceFile = traceFileOrUrl; + if (traceFile.endsWith(".json")) + return toFilePathUrl(traceFile); + try { + const stat = import_fs40.default.statSync(traceFile); + if (stat.isDirectory()) + traceFile = import_path37.default.join(traceFile, tracesDirMarker); + return toFilePathUrl(traceFile); + } catch { + throw new Error(`Trace file ${traceFileOrUrl} does not exist!`); + } +} +async function startTraceViewerServer(options2) { + const server = new HttpServer(); + const allowedRoots = (options2?.allowedFileRoots ?? [process.cwd()]).map((r) => import_path37.default.resolve(r)); + const isAllowed = (filePath) => allowedRoots.some((root) => isPathInside(root, filePath)); + const serveTraceDataRoute = (request2, response2, relativePath) => { + if (!relativePath.startsWith("/file")) + return false; + const url2 = new URL("http://localhost" + request2.url); + try { + const filePath = import_path37.default.resolve(url2.searchParams.get("path")); + if (!isAllowed(filePath)) { + response2.statusCode = 403; + response2.end(); + return true; + } + if (import_fs40.default.existsSync(filePath)) + return server.serveFile(request2, response2, filePath); + if (filePath.endsWith(".json")) { + const fullPrefix = filePath.substring(0, filePath.length - ".json".length); + return sendTraceDescriptor(response2, import_path37.default.dirname(fullPrefix), import_path37.default.basename(fullPrefix)); + } + if (filePath.endsWith(tracesDirMarker)) + return sendTraceDescriptor(response2, import_path37.default.dirname(filePath)); + } catch { + } + response2.statusCode = 404; + response2.end(); + return true; + }; + if (false) { + const traceViewerRoot = import_path37.default.resolve(__dirname, "..", "..", "trace-viewer"); + const devServer = await server.createViteDevServer({ root: traceViewerRoot, base: "/trace/" }); + server.routePrefix("/trace", (request2, response2) => { + const url2 = new URL("http://localhost" + request2.url); + const relativePath = url2.pathname.slice("/trace".length); + if (relativePath.startsWith("/file")) + return serveTraceDataRoute(request2, response2, relativePath); + if (relativePath === "/sw.bundle.js") + return server.serveFile(request2, response2, import_path37.default.join(libPath("vite", "traceViewer"), "sw.bundle.js")); + devServer.middlewares(request2, response2, HttpServer.notFoundFallback(response2)); + return true; + }); + } else { + server.routePrefix("/trace", (request2, response2) => { + const url2 = new URL("http://localhost" + request2.url); + const relativePath = url2.pathname.slice("/trace".length); + if (relativePath.startsWith("/file")) + return serveTraceDataRoute(request2, response2, relativePath); + const absolutePath = import_path37.default.join(libPath("vite", "traceViewer"), ...relativePath.split("/")); + return server.serveFile(request2, response2, absolutePath); + }); + } + const transport = options2?.transport || (options2?.isServer ? new StdinServer() : void 0); + if (transport) + server.createWebSocket(() => transport); + const { host, port } = options2 || {}; + await server.start({ preferredPort: port, host }); + return server; +} +async function installRootRedirect(server, traceUrl, options2) { + const params2 = new URLSearchParams(); + if (import_path37.default.sep !== import_path37.default.posix.sep) + params2.set("pathSeparator", import_path37.default.sep); + if (traceUrl) + params2.append("trace", traceUrl); + if (server.wsGuid()) + params2.append("ws", server.wsGuid()); + if (options2?.isServer) + params2.append("isServer", ""); + if (isUnderTest()) + params2.append("isUnderTest", "true"); + for (const arg of options2.args || []) + params2.append("arg", arg); + if (options2.grep) + params2.append("grep", options2.grep); + if (options2.grepInvert) + params2.append("grepInvert", options2.grepInvert); + for (const project of options2.project || []) + params2.append("project", project); + for (const reporter of options2.reporter || []) + params2.append("reporter", reporter); + const urlPath = `./trace/${options2.webApp || "index.html"}?${params2.toString()}`; + server.routePath("/", (_, response2) => { + response2.statusCode = 302; + response2.setHeader("Location", urlPath); + response2.end(); + return true; + }); +} +async function runTraceViewerApp(traceUrl, browserName, options2) { + traceUrl = validateTraceUrlOrPath(traceUrl); + const server = await startTraceViewerServer({ ...options2, allowedFileRoots: traceFileRoots(traceUrl, options2.allowedFileRoots) }); + await installRootRedirect(server, traceUrl, options2); + const page = await openTraceViewerApp(server.urlPrefix("precise"), browserName, options2); + page.on("close", () => gracefullyProcessExitDoNotHang(0)); + return page; +} +async function runTraceInBrowser(traceUrl, options2) { + traceUrl = validateTraceUrlOrPath(traceUrl); + const server = await startTraceViewerServer({ ...options2, allowedFileRoots: traceFileRoots(traceUrl, options2.allowedFileRoots) }); + await installRootRedirect(server, traceUrl, options2); + await openTraceInBrowser(server.urlPrefix("human-readable")); +} +function traceFileRoots(traceUrl, configured) { + if (configured) + return configured; + if (traceUrl?.startsWith("file://")) { + try { + return [import_path37.default.dirname(import_url.default.fileURLToPath(traceUrl))]; + } catch { + } + } + return [process.cwd()]; +} +async function openTraceViewerApp(url2, browserName, options2) { + const traceViewerPlaywright = createPlaywright({ sdkLanguage: "javascript", isInternalPlaywright: true }); + const traceViewerBrowser = isUnderTest() ? "chromium" : browserName; + const { context: context2, page } = await launchApp(traceViewerPlaywright[traceViewerBrowser], { + sdkLanguage: traceViewerPlaywright.options.sdkLanguage, + windowSize: { width: 1280, height: 800 }, + persistentContextOptions: { + ...options2?.persistentContextOptions, + args: isUnderTest() ? ["--remote-debugging-port=0"] : void 0, + headless: !!options2?.headless, + colorScheme: isUnderTest() ? "light" : void 0 + } + }); + const controller = new ProgressController(); + await controller.run(async (progress2) => { + await context2._browser._defaultContext.loadDefaultContextAsIs(progress2); + if (process.env.PWTEST_PRINT_WS_ENDPOINT) { + process.stderr.write("DevTools listening on: " + context2._browser.options.wsEndpoint + "\n"); + } + if (!isUnderTest()) + await progress2.race(syncLocalStorageWithSettings(page, "traceviewer")); + if (isUnderTest()) + page.on("close", () => context2.close(nullProgress, { reason: "Trace viewer closed" }).catch(() => { + })); + await page.mainFrame().goto(progress2, url2); + }); + return page; +} +async function openTraceInBrowser(url2) { + console.log("\nListening on " + url2); + if (!isUnderTest() && !isCodingAgent()) + await open4(url2.replace("0.0.0.0", "localhost")).catch(() => { + }); +} +function sendTraceDescriptor(response2, traceDir2, tracePrefix) { + response2.statusCode = 200; + response2.setHeader("Content-Type", "application/json"); + response2.end(JSON.stringify(traceDescriptor(traceDir2, tracePrefix))); + return true; +} +function traceDescriptor(traceDir2, tracePrefix) { + const result2 = { + entries: [] + }; + for (const name of import_fs40.default.readdirSync(traceDir2)) { + if (!tracePrefix || name.startsWith(tracePrefix)) + result2.entries.push({ name, path: toFilePathUrl(import_path37.default.join(traceDir2, name)) }); + } + const resourcesDir = import_path37.default.join(traceDir2, "resources"); + if (import_fs40.default.existsSync(resourcesDir)) { + for (const name of import_fs40.default.readdirSync(resourcesDir)) + result2.entries.push({ name: "resources/" + name, path: toFilePathUrl(import_path37.default.join(resourcesDir, name)) }); + } + return result2; +} +function toFilePathUrl(filePath) { + return `file?path=${encodeURIComponent(filePath)}`; +} +var import_fs40, import_path37, import_url, open4, tracesDirMarker, StdinServer; +var init_traceViewer = __esm({ + "packages/playwright-core/src/server/trace/viewer/traceViewer.ts"() { + "use strict"; + import_fs40 = __toESM(require("fs")); + import_path37 = __toESM(require("path")); + import_url = __toESM(require("url")); + init_httpServer(); + init_processLauncher(); + init_debug(); + init_env(); + init_fileUtils(); + init_package(); + init_launchApp(); + init_launchApp(); + init_playwright(); + init_progress(); + init_progress(); + open4 = require("./utilsBundle").open; + tracesDirMarker = "traces.dir"; + StdinServer = class { + constructor() { + process.stdin.on("data", (data) => { + const url2 = validateTraceUrlOrPath(data.toString().trim()); + if (!url2 || url2 === this._traceUrl) + return; + if (url2.endsWith(".json")) + this._pollLoadTrace(url2); + else + this._loadTrace(url2); + }); + process.stdin.on("close", () => gracefullyProcessExitDoNotHang(0)); + } + onconnect() { + } + async dispatch(method, params2) { + if (method === "initialize") { + if (this._traceUrl) + this._loadTrace(this._traceUrl); + } + } + onclose() { + } + _loadTrace(traceUrl) { + this._traceUrl = traceUrl; + clearTimeout(this._pollTimer); + this.sendEvent?.("loadTraceRequested", { traceUrl }); + } + _pollLoadTrace(url2) { + this._loadTrace(url2); + this._pollTimer = setTimeout(() => { + this._pollLoadTrace(url2); + }, 500); + } + }; + } +}); + +// packages/playwright-core/src/server/index.ts +var server_exports = {}; +__export(server_exports, { + Browser: () => Browser, + BrowserContext: () => BrowserContext, + DispatcherConnection: () => DispatcherConnection, + Page: () => Page, + PlaywrightDispatcher: () => PlaywrightDispatcher, + Request: () => Request, + RequestDispatcher: () => RequestDispatcher, + Response: () => Response2, + ResponseDispatcher: () => ResponseDispatcher, + RootDispatcher: () => RootDispatcher, + WebSocketTransport: () => WebSocketTransport, + createPlaywright: () => createPlaywright, + deviceDescriptors: () => deviceDescriptors, + findRepeatedSubsequencesForTest: () => findRepeatedSubsequencesForTest, + installRootRedirect: () => installRootRedirect, + nullProgress: () => nullProgress, + openTraceInBrowser: () => openTraceInBrowser, + openTraceViewerApp: () => openTraceViewerApp, + runTraceViewerApp: () => runTraceViewerApp, + setMaxDispatchersForTest: () => setMaxDispatchersForTest, + startTraceViewerServer: () => startTraceViewerServer +}); +var init_server = __esm({ + "packages/playwright-core/src/server/index.ts"() { + "use strict"; + init_browser(); + init_browserContext(); + init_callLog(); + init_deviceDescriptors(); + init_dispatcher(); + init_networkDispatchers(); + init_playwrightDispatcher(); + init_network2(); + init_page(); + init_playwright(); + init_progress(); + init_transport(); + init_traceViewer(); + } +}); + +// packages/playwright-core/src/server/dispatchers/debugControllerDispatcher.ts +var DebugControllerDispatcher; +var init_debugControllerDispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/debugControllerDispatcher.ts"() { + "use strict"; + init_eventsHelper(); + init_debugController(); + init_dispatcher(); + DebugControllerDispatcher = class extends Dispatcher { + constructor(connection, debugController) { + super(connection, debugController, "DebugController", {}); + this._type_DebugController = true; + this._listeners = [ + eventsHelper.addEventListener(this._object, DebugController.Events.StateChanged, (params2) => { + this._dispatchEvent("stateChanged", params2); + }), + eventsHelper.addEventListener(this._object, DebugController.Events.InspectRequested, ({ selector, locator: locator2, ariaSnapshot }) => { + this._dispatchEvent("inspectRequested", { selector, locator: locator2, ariaSnapshot }); + }), + eventsHelper.addEventListener(this._object, DebugController.Events.SourceChanged, ({ text: text2, header, footer, actions }) => { + this._dispatchEvent("sourceChanged", { text: text2, header, footer, actions }); + }), + eventsHelper.addEventListener(this._object, DebugController.Events.Paused, ({ paused }) => { + this._dispatchEvent("paused", { paused }); + }), + eventsHelper.addEventListener(this._object, DebugController.Events.SetModeRequested, ({ mode }) => { + this._dispatchEvent("setModeRequested", { mode }); + }) + ]; + } + async initialize(params2, progress2) { + this._object.initialize(progress2, params2.codegenId, params2.sdkLanguage); + } + async setReportStateChanged(params2, progress2) { + this._object.setReportStateChanged(progress2, params2.enabled); + } + async setRecorderMode(params2, progress2) { + await this._object.setRecorderMode(progress2, params2); + } + async highlight(params2, progress2) { + await this._object.highlight(progress2, params2); + } + async hideHighlight(params2, progress2) { + await this._object.hideHighlight(progress2); + } + async resume(params2, progress2) { + await this._object.resume(progress2); + } + async kill(params2, progress2) { + this._object.kill(progress2); + } + _onDispose() { + eventsHelper.removeEventListeners(this._listeners); + this._object.dispose(); + } + }; + } +}); + +// packages/playwright-core/src/remote/playwrightConnection.ts +var PlaywrightConnection; +var init_playwrightConnection = __esm({ + "packages/playwright-core/src/remote/playwrightConnection.ts"() { + "use strict"; + init_profiler(); + init_debugLogger(); + init_time(); + init_server(); + init_android(); + init_browser(); + init_debugControllerDispatcher(); + PlaywrightConnection = class { + constructor(semaphore, transport, controller, playwright2, initialize, id) { + this._cleanups = []; + this._transport = transport; + this._semaphore = semaphore; + this._id = id; + this._profileName = (/* @__PURE__ */ new Date()).toISOString(); + const lock2 = this._semaphore.acquire(); + this._dispatcherConnection = new DispatcherConnection(); + this._dispatcherConnection.onmessage = async (message) => { + await lock2; + if (!transport.isClosed()) { + const messageString = JSON.stringify(message); + if (debugLogger.isEnabled("server:channel")) + debugLogger.log("server:channel", `[${this._id}] ${monotonicTime() * 1e3} SEND \u25BA ${messageString}`); + if (debugLogger.isEnabled("server:metadata")) + this.logServerMetadata(message, messageString, "SEND"); + transport.send(messageString); + } + }; + transport.on("message", async (message) => { + await lock2; + const messageString = Buffer.from(message).toString(); + const jsonMessage = JSON.parse(messageString); + if (debugLogger.isEnabled("server:channel")) + debugLogger.log("server:channel", `[${this._id}] ${monotonicTime() * 1e3} \u25C0 RECV ${messageString}`); + if (debugLogger.isEnabled("server:metadata")) + this.logServerMetadata(jsonMessage, messageString, "RECV"); + this._dispatcherConnection.dispatch(jsonMessage); + }); + transport.on("close", () => this._onDisconnect()); + transport.on("error", (error) => this._onDisconnect(error)); + if (controller) { + debugLogger.log("server", `[${this._id}] engaged reuse controller mode`); + this._root = new DebugControllerDispatcher(this._dispatcherConnection, playwright2.debugController); + return; + } + this._root = new RootDispatcher(this._dispatcherConnection, async (scope, params2) => { + await startProfiling(); + const options2 = await initialize(); + if (options2.preLaunchedBrowser) { + const browser = options2.preLaunchedBrowser; + browser.options.sdkLanguage = params2.sdkLanguage; + browser.on(Browser.Events.Disconnected, () => { + this.close({ code: 1001, reason: "Browser closed" }); + }); + } + if (options2.preLaunchedAndroidDevice) { + const androidDevice = options2.preLaunchedAndroidDevice; + androidDevice.on(AndroidDevice.Events.Close, () => { + this.close({ code: 1001, reason: "Android device disconnected" }); + }); + } + if (options2.dispose) + this._cleanups.push(options2.dispose); + const dispatcher = new PlaywrightDispatcher(scope, playwright2, options2); + this._cleanups.push(() => dispatcher.cleanup()); + return dispatcher; + }); + } + _onDisconnect(error) { + if (!this._onDisconnectPromise) + this._onDisconnectPromise = this._doDisconnect(error); + return this._onDisconnectPromise; + } + async _doDisconnect(error) { + debugLogger.log("server", `[${this._id}] disconnected. error: ${error}`); + await this._root.stopPendingOperations(new Error("Disconnected")).catch(() => { + }); + this._root._dispose(); + debugLogger.log("server", `[${this._id}] starting cleanup`); + for (const cleanup of this._cleanups) + await cleanup().catch(() => { + }); + await stopProfiling(this._profileName); + this._semaphore.release(); + debugLogger.log("server", `[${this._id}] finished cleanup`); + } + logServerMetadata(message, messageString, direction) { + const serverLogMetadata = { + wallTime: Date.now(), + id: message.id, + guid: message.guid, + method: message.method, + payloadSizeInBytes: Buffer.byteLength(messageString, "utf-8") + }; + debugLogger.log("server:metadata", (direction === "SEND" ? "SEND \u25BA " : "\u25C0 RECV ") + JSON.stringify(serverLogMetadata)); + } + async close(reason) { + if (!this._onDisconnectPromise) { + debugLogger.log("server", `[${this._id}] force closing connection: ${reason?.reason || ""} (${reason?.code || 0})`); + try { + this._transport.close(reason); + } catch (e) { + } + } + await this._onDisconnect(); + } + }; + } +}); + +// packages/playwright-core/src/remote/playwrightServer.ts +var playwrightServer_exports = {}; +__export(playwrightServer_exports, { + PlaywrightServer: () => PlaywrightServer +}); +function userAgentVersionMatchesErrorMessage(userAgent) { + const match = userAgent.match(/^Playwright\/(\d+\.\d+\.\d+)/); + if (!match) { + return; + } + const received = match[1].split(".").slice(0, 2).join("."); + const expected = getPlaywrightVersion(true); + if (received !== expected) { + return wrapInASCIIBox([ + `Playwright version mismatch:`, + ` - server version: v${expected}`, + ` - client version: v${received}`, + ``, + `If you are using VSCode extension, restart VSCode.`, + ``, + `If you are connecting to a remote service,`, + `keep your local Playwright version in sync`, + `with the remote service version.`, + ``, + `<3 Playwright Team` + ].join("\n"), 1); + } +} +function launchOptionsHash(options2) { + const copy = { ...options2 }; + for (const k of Object.keys(copy)) { + const key = k; + if (copy[key] === defaultLaunchOptions[key]) + delete copy[key]; + } + for (const key of optionsThatAllowBrowserReuse) + delete copy[key]; + return JSON.stringify(copy); +} +function filterLaunchOptions(options2, allowUnsafe) { + return { + channel: options2.channel, + args: allowUnsafe ? options2.args : void 0, + ignoreAllDefaultArgs: allowUnsafe ? options2.ignoreAllDefaultArgs : void 0, + ignoreDefaultArgs: allowUnsafe ? options2.ignoreDefaultArgs : void 0, + timeout: options2.timeout, + headless: options2.headless, + proxy: options2.proxy, + chromiumSandbox: allowUnsafe ? options2.chromiumSandbox : void 0, + firefoxUserPrefs: allowUnsafe ? options2.firefoxUserPrefs : void 0, + slowMo: options2.slowMo, + executablePath: isUnderTest() || allowUnsafe ? options2.executablePath : void 0, + downloadsPath: allowUnsafe ? options2.downloadsPath : void 0, + artifactsDir: isUnderTest() || allowUnsafe ? options2.artifactsDir : void 0 + }; +} +var PlaywrightServer, defaultLaunchOptions, optionsThatAllowBrowserReuse; +var init_playwrightServer = __esm({ + "packages/playwright-core/src/remote/playwrightServer.ts"() { + "use strict"; + init_semaphore(); + init_time(); + init_wsServer(); + init_ascii(); + init_socksProxy(); + init_debugLogger(); + init_debug(); + init_userAgent(); + init_playwrightConnection(); + init_serverTransport(); + init_playwright(); + init_browser(); + init_progress(); + PlaywrightServer = class { + constructor(options2) { + this._dontReuseBrowsers = /* @__PURE__ */ new Set(); + this._options = options2; + if (options2.preLaunchedBrowser) { + this._playwright = options2.preLaunchedBrowser.attribution.playwright; + this._dontReuse(options2.preLaunchedBrowser); + } + if (options2.preLaunchedAndroidDevice) + this._playwright = options2.preLaunchedAndroidDevice._android.attribution.playwright; + this._playwright ??= createPlaywright({ sdkLanguage: "javascript", isServer: true }); + const browserSemaphore = new Semaphore(this._options.maxConnections); + const controllerSemaphore = new Semaphore(1); + const reuseBrowserSemaphore = new Semaphore(1); + this._wsServer = new WSServer({ + onRequest: (request2, response2) => { + if (request2.method === "GET" && request2.url === "/json") { + response2.setHeader("Content-Type", "application/json"); + response2.end(JSON.stringify({ + wsEndpointPath: this._options.path + })); + return; + } + response2.end("Running"); + }, + onUpgrade: (request2, socket) => { + const uaError = userAgentVersionMatchesErrorMessage(request2.headers["user-agent"] || ""); + if (uaError) + return { error: `HTTP/${request2.httpVersion} 428 Precondition Required\r +\r +${uaError}` }; + }, + onHeaders: (headers) => { + if (process.env.PWTEST_SERVER_WS_HEADERS) + headers.push(process.env.PWTEST_SERVER_WS_HEADERS); + }, + onConnection: (request2, url2, ws3, id) => { + const browserHeader = request2.headers["x-playwright-browser"]; + const browserName = url2.searchParams.get("browser") || (Array.isArray(browserHeader) ? browserHeader[0] : browserHeader) || null; + const proxyHeader = request2.headers["x-playwright-proxy"]; + const proxyValue = url2.searchParams.get("proxy") || (Array.isArray(proxyHeader) ? proxyHeader[0] : proxyHeader); + const launchOptionsHeader = request2.headers["x-playwright-launch-options"] || ""; + const launchOptionsHeaderValue = Array.isArray(launchOptionsHeader) ? launchOptionsHeader[0] : launchOptionsHeader; + const launchOptionsParam = url2.searchParams.get("launch-options"); + let launchOptions = { timeout: DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT }; + try { + launchOptions = JSON.parse(launchOptionsParam || launchOptionsHeaderValue); + if (!launchOptions.timeout) + launchOptions.timeout = DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT; + } catch (e) { + } + const isExtension = this._options.mode === "extension"; + launchOptions = filterLaunchOptions(launchOptions, isExtension || !!this._options.unsafe); + if (this._options.artifactsDir) + launchOptions.artifactsDir = this._options.artifactsDir; + if (isExtension) { + const connectFilter = url2.searchParams.get("connect"); + if (connectFilter) { + if (connectFilter !== "first") + throw new Error(`Unknown connect filter: ${connectFilter}`); + return new PlaywrightConnection( + browserSemaphore, + new WebSocketServerTransport(ws3), + false, + this._playwright, + () => this._initConnectMode(id, connectFilter, browserName, launchOptions), + id + ); + } + if (url2.searchParams.has("debug-controller")) { + return new PlaywrightConnection( + controllerSemaphore, + new WebSocketServerTransport(ws3), + true, + this._playwright, + async () => { + throw new Error("shouldnt be used"); + }, + id + ); + } + return new PlaywrightConnection( + reuseBrowserSemaphore, + new WebSocketServerTransport(ws3), + false, + this._playwright, + () => this._initReuseBrowsersMode(browserName, launchOptions, id), + id + ); + } + if (this._options.mode === "launchServer" || this._options.mode === "launchServerShared") { + if (this._options.preLaunchedBrowser) { + return new PlaywrightConnection( + browserSemaphore, + new WebSocketServerTransport(ws3), + false, + this._playwright, + () => this._initPreLaunchedBrowserMode(id), + id + ); + } + return new PlaywrightConnection( + browserSemaphore, + new WebSocketServerTransport(ws3), + false, + this._playwright, + () => this._initPreLaunchedAndroidMode(id), + id + ); + } + return new PlaywrightConnection( + browserSemaphore, + new WebSocketServerTransport(ws3), + false, + this._playwright, + () => this._initLaunchBrowserMode(browserName, proxyValue, launchOptions, id), + id + ); + } + }); + } + async _initReuseBrowsersMode(browserName, launchOptions, id) { + debugLogger.log("server", `[${id}] engaged reuse browsers mode for ${browserName}`); + const requestedOptions = launchOptionsHash(launchOptions); + let browser = this._playwright.allBrowsers().find((b) => { + if (b.options.name !== browserName) + return false; + if (this._dontReuseBrowsers.has(b)) + return false; + const existingOptions = launchOptionsHash({ ...b.options.originalLaunchOptions, timeout: DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT }); + return existingOptions === requestedOptions; + }); + for (const b of this._playwright.allBrowsers()) { + if (b === browser) + continue; + if (this._dontReuseBrowsers.has(b)) + continue; + if (b.options.name === browserName && b.options.channel === launchOptions.channel) + await b.close(nullProgress, { reason: "Connection terminated" }); + } + if (!browser) { + const browserType = this._playwright[browserName || "chromium"]; + const controller = new ProgressController(); + browser = await controller.run((progress2) => browserType.launch(progress2, { + ...launchOptions, + headless: !!process.env.PW_DEBUG_CONTROLLER_HEADLESS + }), launchOptions.timeout); + } + return { + preLaunchedBrowser: browser, + denyLaunch: true, + dispose: async () => { + for (const context2 of browser.contexts()) { + if (!context2.pages().length) + await context2.close(nullProgress, { reason: "Connection terminated" }); + } + } + }; + } + async _initConnectMode(id, filter, browserName, launchOptions) { + browserName ??= "chromium"; + debugLogger.log("server", `[${id}] engaged connect mode`); + let browser = this._playwright.allBrowsers().find((b) => b.options.name === browserName); + if (!browser) { + const browserType = this._playwright[browserName]; + const controller = new ProgressController(); + browser = await controller.run((progress2) => browserType.launch(progress2, launchOptions), launchOptions.timeout); + this._dontReuse(browser); + } + return { + preLaunchedBrowser: browser, + denyLaunch: true, + sharedBrowser: true + }; + } + async _initPreLaunchedBrowserMode(id) { + debugLogger.log("server", `[${id}] engaged pre-launched (browser) mode`); + const browser = this._options.preLaunchedBrowser; + for (const b of this._playwright.allBrowsers()) { + if (b !== browser) + await b.close(nullProgress, { reason: "Connection terminated" }); + } + return { + preLaunchedBrowser: browser, + socksProxy: this._options.preLaunchedSocksProxy, + sharedBrowser: this._options.mode === "launchServerShared", + denyLaunch: true + }; + } + async _initPreLaunchedAndroidMode(id) { + debugLogger.log("server", `[${id}] engaged pre-launched (Android) mode`); + const androidDevice = this._options.preLaunchedAndroidDevice; + return { + preLaunchedAndroidDevice: androidDevice, + denyLaunch: true + }; + } + async _initLaunchBrowserMode(browserName, proxyValue, launchOptions, id) { + debugLogger.log("server", `[${id}] engaged launch mode for "${browserName}"`); + let socksProxy; + if (proxyValue) { + socksProxy = new SocksProxy(); + socksProxy.setPattern(proxyValue); + launchOptions.socksProxyPort = await socksProxy.listen(0); + debugLogger.log("server", `[${id}] started socks proxy on port ${launchOptions.socksProxyPort}`); + } else { + launchOptions.socksProxyPort = void 0; + } + const browserType = this._playwright[browserName]; + const controller = new ProgressController(); + const browser = await controller.run((progress2) => browserType.launch(progress2, launchOptions), launchOptions.timeout); + this._dontReuseBrowsers.add(browser); + return { + preLaunchedBrowser: browser, + socksProxy, + denyLaunch: true, + dispose: async () => { + await browser.close(nullProgress, { reason: "Connection terminated" }); + socksProxy?.close(); + } + }; + } + _dontReuse(browser) { + this._dontReuseBrowsers.add(browser); + browser.on(Browser.Events.Disconnected, () => { + this._dontReuseBrowsers.delete(browser); + }); + } + async listen(port = 0, hostname) { + return this._wsServer.listen(port, hostname, this._options.path); + } + async close() { + await this._wsServer.close(); + for (const browser of this._playwright.allBrowsers()) + await browser.close(nullProgress, { reason: "Server closed" }); + } + }; + defaultLaunchOptions = { + ignoreAllDefaultArgs: false, + handleSIGINT: false, + handleSIGTERM: false, + handleSIGHUP: false, + headless: true + }; + optionsThatAllowBrowserReuse = [ + "headless", + "timeout", + "tracesDir", + "artifactsDir" + ]; + } +}); + +// packages/playwright-core/src/androidServerImpl.ts +var import_events15, AndroidServerLauncherImpl; +var init_androidServerImpl = __esm({ + "packages/playwright-core/src/androidServerImpl.ts"() { + "use strict"; + import_events15 = __toESM(require("events")); + init_crypto(); + init_playwrightServer(); + init_playwright(); + init_progress(); + AndroidServerLauncherImpl = class { + async launchServer(options2 = {}) { + const playwright2 = createPlaywright({ sdkLanguage: "javascript", isServer: true }); + const controller = new ProgressController(); + let devices = await controller.run((progress2) => playwright2.android.devices(progress2, { + host: options2.adbHost, + port: options2.adbPort, + omitDriverInstall: options2.omitDriverInstall + })); + if (devices.length === 0) + throw new Error("No devices found"); + if (options2.deviceSerialNumber) { + devices = devices.filter((d) => d.serial === options2.deviceSerialNumber); + if (devices.length === 0) + throw new Error(`No device with serial number '${options2.deviceSerialNumber}' was found`); + } + if (devices.length > 1) + throw new Error(`More than one device found. Please specify deviceSerialNumber`); + const device = devices[0]; + const path59 = options2.wsPath ? options2.wsPath.startsWith("/") ? options2.wsPath : `/${options2.wsPath}` : `/${createGuid()}`; + const server = new PlaywrightServer({ mode: "launchServer", path: path59, maxConnections: 1, preLaunchedAndroidDevice: device }); + const wsEndpoint = await server.listen(options2.port, options2.host); + const browserServer = new import_events15.default(); + browserServer.wsEndpoint = () => wsEndpoint; + browserServer.close = () => device.close(nullProgress); + browserServer.kill = () => device.close(nullProgress); + device.on("close", () => { + server.close(); + browserServer.emit("close"); + }); + return browserServer; + } + }; + } +}); + +// packages/playwright-core/src/browserServerImpl.ts +function toProtocolLogger(logger) { + return logger ? (direction, message) => { + if (logger.isEnabled("protocol", "verbose")) + logger.log("protocol", "verbose", (direction === "send" ? "SEND \u25BA " : "\u25C0 RECV ") + JSON.stringify(message), [], {}); + } : void 0; +} +function envObjectToArray(env) { + const result2 = []; + for (const name in env) { + if (!Object.is(env[name], void 0)) + result2.push({ name, value: String(env[name]) }); + } + return result2; +} +var import_events16, BrowserServerLauncherImpl; +var init_browserServerImpl = __esm({ + "packages/playwright-core/src/browserServerImpl.ts"() { + "use strict"; + import_events16 = __toESM(require("events")); + init_crypto(); + init_debug(); + init_stackTrace(); + init_time(); + init_playwrightServer(); + init_helper(); + init_playwright(); + init_validatorPrimitives(); + init_progress(); + BrowserServerLauncherImpl = class { + constructor(browserName) { + this._browserName = browserName; + } + async launchServer(options2 = {}) { + const playwright2 = createPlaywright({ sdkLanguage: "javascript", isServer: true }); + const metadata = { id: "", startTime: 0, endTime: 0, type: "Internal", method: "", params: {}, log: [], internal: true }; + const validatorContext = { + tChannelImpl: (names, arg, path60) => { + throw new ValidationError(`${path60}: channels are not expected in launchServer`); + }, + binary: "buffer", + isUnderTest + }; + let 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: options2.timeout ?? DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT + }; + let browser; + try { + const controller = new ProgressController(metadata); + browser = await controller.run(async (progress2) => { + if (options2._userDataDir !== void 0) { + const validator = scheme["BrowserTypeLaunchPersistentContextParams"]; + launchOptions = validator({ ...launchOptions, userDataDir: options2._userDataDir }, "", validatorContext); + const context2 = await playwright2[this._browserName].launchPersistentContext(progress2, options2._userDataDir, launchOptions); + return context2._browser; + } else { + const validator = scheme["BrowserTypeLaunchParams"]; + launchOptions = validator(launchOptions, "", validatorContext); + return await playwright2[this._browserName].launch(progress2, launchOptions, toProtocolLogger(options2.logger)); + } + }); + } catch (e) { + const log2 = helper.formatBrowserLogs(metadata.log); + rewriteErrorMessage(e, `${e.message} Failed to launch browser.${log2}`); + throw e; + } + const path59 = options2.wsPath ? options2.wsPath.startsWith("/") ? options2.wsPath : `/${options2.wsPath}` : `/${createGuid()}`; + const server = new PlaywrightServer({ mode: options2._sharedBrowser ? "launchServerShared" : "launchServer", path: path59, maxConnections: Infinity, preLaunchedBrowser: browser }); + const wsEndpoint = await server.listen(options2.port, options2.host); + const browserServer = new import_events16.default(); + browserServer.process = () => browser.options.browserProcess.process; + browserServer.wsEndpoint = () => wsEndpoint; + browserServer.close = () => browser.options.browserProcess.close(); + browserServer[Symbol.asyncDispose] = browserServer.close; + browserServer.kill = () => browser.options.browserProcess.kill(); + browserServer._disconnectForTest = () => server.close(); + browserServer._userDataDirForTest = browser._userDataDirForTest; + browser.options.browserProcess.onclose = (exitCode, signal) => { + server.close(); + browserServer.emit("close", exitCode, signal); + }; + return browserServer; + } + }; + } +}); + +// packages/playwright-core/src/client/clientStackTrace.ts +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])([^\d]+)\d?\.(.*)/); + if (!match) + return name; + return match[1].toLowerCase() + match[2] + "." + match[3]; + } + 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 + }; +} +var init_clientStackTrace = __esm({ + "packages/playwright-core/src/client/clientStackTrace.ts"() { + "use strict"; + init_stackTrace(); + } +}); + +// packages/playwright-core/src/client/channelOwner.ts +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, path59, context2) { + if (arg._object instanceof ChannelOwner && (names === "*" || names.includes(arg._object._type))) + return { guid: arg._object._guid }; + throw new ValidationError(`${path59}: expected channel ${names.toString()}`); +} +var ChannelOwner; +var init_channelOwner = __esm({ + "packages/playwright-core/src/client/channelOwner.ts"() { + "use strict"; + init_protocolMetainfo(); + init_stackTrace(); + init_eventEmitter(); + init_validator(); + init_clientStackTrace(); + ChannelOwner = class _ChannelOwner extends EventEmitter3 { + constructor(parent, type3, 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 = type3; + 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 EventEmitter3(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(base) { + const channel = new Proxy(base, { + get: (obj, prop) => { + if (typeof prop === "string") { + const validator = maybeFindValidator(this._type, prop, "Params"); + const { internal } = getMetainfo({ type: this._type, method: prop }) || {}; + if (validator) { + return async (params2) => { + return await this._wrapApiCall(async (apiZone) => { + const validatedParams = validator(params2, "", this._validatorToWireContext()); + if (!apiZone.internal && !apiZone.reported) { + apiZone.reported = true; + this._instrumentation.onApiCallBegin(apiZone, { type: this._type, method: prop, params: params2 }); + 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 stackTrace = captureLibraryStackTrace(this._platform); + const apiZone = { title: options2?.title, apiName: stackTrace.apiName, frames: stackTrace.frames, internal: options2?.internal ?? false, reported: false, userData: void 0, stepId: void 0 }; + try { + const result2 = await this._platform.zones.current().push(apiZone).run(async () => await func(apiZone)); + if (!options2?.internal) { + logApiCall(this._platform, logger, `<= ${apiZone.apiName} succeeded`); + this._instrumentation.onApiCallEnd(apiZone); + } + return result2; + } 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?.internal) { + apiZone.error = e; + logApiCall(this._platform, logger, `<= ${apiZone.apiName} failed`); + this._instrumentation.onApiCallEnd(apiZone); + } + throw e; + } + } + toJSON() { + return { + _type: this._type, + _guid: this._guid + }; + } + }; + } +}); + +// packages/playwright-core/src/client/cdpSession.ts +var CDPSession2; +var init_cdpSession = __esm({ + "packages/playwright-core/src/client/cdpSession.ts"() { + "use strict"; + init_channelOwner(); + CDPSession2 = class extends ChannelOwner { + static from(cdpSession) { + return cdpSession._object; + } + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + this._channel.on("event", (event) => { + this.emit(event.method, event.params); + this.emit("event", event); + }); + this._channel.on("close", () => { + this.emit("close", this); + }); + this.on = super.on; + this.addListener = super.addListener; + this.off = super.removeListener; + this.removeListener = super.removeListener; + this.once = super.once; + } + async send(method, params2) { + const result2 = await this._channel.send({ method, params: params2 }); + return result2.result; + } + async detach() { + return await this._channel.detach(); + } + }; + } +}); + +// packages/playwright-core/src/client/clientHelper.ts +function envObjectToArray2(env) { + const result2 = []; + for (const name in env) { + if (!Object.is(env[name], void 0)) + result2.push({ name, value: String(env[name]) }); + } + return result2; +} +async function evaluationScript(platform, fun, arg, addSourceUrl = true) { + if (typeof fun === "function") { + const source8 = fun.toString(); + const argString = Object.is(arg, void 0) ? "undefined" : JSON.stringify(arg); + return `(${source8})(${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 source8 = await platform.fs().promises.readFile(fun.path, "utf8"); + if (addSourceUrl) + source8 = addSourceUrlToScript(source8, fun.path); + return source8; + } + throw new Error("Either path or content property must be present"); +} +function addSourceUrlToScript(source8, path59) { + return `${source8} +//# sourceURL=${path59.replace(/\n/g, "")}`; +} +var init_clientHelper = __esm({ + "packages/playwright-core/src/client/clientHelper.ts"() { + "use strict"; + init_rtti(); + } +}); + +// packages/playwright-core/src/client/clock.ts +function parseTime2(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 parseTicks2(ticks) { + return { + ticksNumber: typeof ticks === "number" ? ticks : void 0, + ticksString: typeof ticks === "string" ? ticks : void 0 + }; +} +var Clock2; +var init_clock2 = __esm({ + "packages/playwright-core/src/client/clock.ts"() { + "use strict"; + Clock2 = class { + constructor(browserContext) { + this._browserContext = browserContext; + } + async install(options2 = {}) { + await this._browserContext._channel.clockInstall(options2.time !== void 0 ? parseTime2(options2.time) : {}); + } + async fastForward(ticks) { + await this._browserContext._channel.clockFastForward(parseTicks2(ticks)); + } + async pauseAt(time) { + await this._browserContext._channel.clockPauseAt(parseTime2(time)); + } + async resume() { + await this._browserContext._channel.clockResume({}); + } + async runFor(ticks) { + await this._browserContext._channel.clockRunFor(parseTicks2(ticks)); + } + async setFixedTime(time) { + await this._browserContext._channel.clockSetFixedTime(parseTime2(time)); + } + async setSystemTime(time) { + await this._browserContext._channel.clockSetSystemTime(parseTime2(time)); + } + }; + } +}); + +// packages/playwright-core/src/client/errors.ts +function isTargetClosedError2(error) { + return error instanceof TargetClosedError2; +} +function serializeError2(e) { + if (isError(e)) + return { error: { message: e.message, stack: e.stack, name: e.name } }; + return { value: serializeValue(e, (value2) => ({ fallThrough: value2 })) }; +} +function parseError2(error) { + if (!error.error) { + if (error.value === void 0) + throw new Error("Serialized error must have either an error or a value"); + return parseSerializedValue(error.value, void 0); + } + if (error.error.name === "TimeoutError") { + const e2 = new TimeoutError2(error.error.message); + e2.stack = error.error.stack || ""; + return e2; + } + if (error.error.name === "TargetClosedError") { + const e2 = new TargetClosedError2(error.error.message); + e2.stack = error.error.stack || ""; + return e2; + } + const e = new Error(error.error.message); + e.stack = error.error.stack || ""; + e.name = error.error.name; + return e; +} +var TimeoutError2, TargetClosedError2; +var init_errors2 = __esm({ + "packages/playwright-core/src/client/errors.ts"() { + "use strict"; + init_rtti(); + init_serializers(); + TimeoutError2 = class extends Error { + constructor(message) { + super(message); + this.name = "TimeoutError"; + } + }; + TargetClosedError2 = class extends Error { + constructor(cause) { + super(cause || "Target page, context or browser has been closed"); + } + }; + } +}); + +// packages/playwright-core/src/client/jsHandle.ts +function serializeArgument(arg) { + const handles = []; + const pushHandle = (channel) => { + handles.push(channel); + return handles.length - 1; + }; + const value2 = serializeValue(arg, (value3) => { + if (value3 instanceof JSHandle2) + return { h: pushHandle(value3._channel) }; + return { fallThrough: value3 }; + }); + return { value: value2, handles }; +} +function parseResult(value2) { + return parseSerializedValue(value2, void 0); +} +function assertMaxArguments(count, max) { + if (count > max) + throw new Error("Too many arguments. If you need to pass more than 1 argument to the function wrap them in an object."); +} +var JSHandle2; +var init_jsHandle = __esm({ + "packages/playwright-core/src/client/jsHandle.ts"() { + "use strict"; + init_channelOwner(); + init_errors2(); + init_serializers(); + JSHandle2 = class _JSHandle extends ChannelOwner { + static from(handle) { + return handle._object; + } + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + this._preview = this._initializer.preview; + this._channel.on("previewUpdated", ({ preview }) => this._preview = preview); + } + async evaluate(pageFunction, arg) { + const result2 = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return parseResult(result2.value); + } + async evaluateHandle(pageFunction, arg) { + const result2 = await this._channel.evaluateExpressionHandle({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return _JSHandle.from(result2.handle); + } + async getProperty(propertyName) { + const result2 = await this._channel.getProperty({ name: propertyName }); + return _JSHandle.from(result2.handle); + } + async getProperties() { + const map = /* @__PURE__ */ new Map(); + for (const { name, value: value2 } of (await this._channel.getPropertyList()).properties) + map.set(name, _JSHandle.from(value2)); + return map; + } + 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 (isTargetClosedError2(e)) + return; + throw e; + } + } + toString() { + return this._preview; + } + }; + } +}); + +// packages/playwright-core/src/client/consoleMessage.ts +var ConsoleMessage2; +var init_consoleMessage = __esm({ + "packages/playwright-core/src/client/consoleMessage.ts"() { + "use strict"; + init_jsHandle(); + ConsoleMessage2 = class { + constructor(platform, event, page, worker) { + this._page = page; + this._worker = worker; + this._event = event; + if (platform.inspectCustom) + this[platform.inspectCustom] = () => this._inspect(); + } + worker() { + return this._worker; + } + page() { + return this._page; + } + type() { + return this._event.type; + } + text() { + return this._event.text; + } + args() { + return this._event.args.map(JSHandle2.from); + } + location() { + const { url: url2, lineNumber, columnNumber } = this._event.location; + return { url: url2, line: lineNumber, column: columnNumber, lineNumber, columnNumber }; + } + timestamp() { + return this._event.timestamp; + } + _inspect() { + return this.text(); + } + }; + } +}); + +// packages/playwright-core/src/client/events.ts +var Events; +var init_events = __esm({ + "packages/playwright-core/src/client/events.ts"() { + "use strict"; + Events = { + AndroidDevice: { + WebView: "webview", + Close: "close" + }, + AndroidSocket: { + Data: "data", + Close: "close" + }, + AndroidWebView: { + Close: "close" + }, + Browser: { + Context: "context", + Disconnected: "disconnected" + }, + Debugger: { + PausedStateChanged: "pausedstatechanged" + }, + BrowserContext: { + Console: "console", + Close: "close", + Dialog: "dialog", + Download: "download", + FrameAttached: "frameattached", + FrameDetached: "framedetached", + FrameNavigated: "framenavigated", + Page: "page", + PageClose: "pageclose", + PageLoad: "pageload", + // 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", + // Deprecated in v1.56, never emitted anymore. + ServiceWorker: "serviceworker", + Request: "request", + Response: "response", + RequestFailed: "requestfailed", + RequestFinished: "requestfinished" + }, + BrowserServer: { + Close: "close" + }, + 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", + Console: "console" + }, + ElectronApplication: { + Close: "close", + Console: "console", + Window: "window" + } + }; + } +}); + +// packages/playwright-core/src/client/debugger.ts +var Debugger2; +var init_debugger2 = __esm({ + "packages/playwright-core/src/client/debugger.ts"() { + "use strict"; + init_channelOwner(); + init_events(); + Debugger2 = class extends ChannelOwner { + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + this._pausedDetails = null; + this._channel.on("pausedStateChanged", ({ pausedDetails }) => { + this._pausedDetails = pausedDetails ?? null; + this.emit(Events.Debugger.PausedStateChanged); + }); + } + static from(channel) { + return channel._object; + } + async requestPause() { + await this._channel.requestPause(); + } + async resume() { + await this._channel.resume(); + } + async next() { + await this._channel.next(); + } + async runTo(location2) { + await this._channel.runTo({ location: location2 }); + } + pausedDetails() { + return this._pausedDetails; + } + }; + } +}); + +// packages/playwright-core/src/client/stream.ts +var Stream; +var init_stream = __esm({ + "packages/playwright-core/src/client/stream.ts"() { + "use strict"; + init_channelOwner(); + Stream = class extends ChannelOwner { + static from(Stream2) { + return Stream2._object; + } + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + } + stream() { + return this._platform.streamReadable(this._channel); + } + }; + } +}); + +// packages/playwright-core/src/client/fileUtils.ts +async function mkdirIfNeeded2(platform, filePath) { + await platform.fs().promises.mkdir(platform.path().dirname(filePath), { recursive: true }).catch(() => { + }); +} +var fileUploadSizeLimit2; +var init_fileUtils2 = __esm({ + "packages/playwright-core/src/client/fileUtils.ts"() { + "use strict"; + fileUploadSizeLimit2 = 50 * 1024 * 1024; + } +}); + +// packages/playwright-core/src/client/artifact.ts +var Artifact2; +var init_artifact2 = __esm({ + "packages/playwright-core/src/client/artifact.ts"() { + "use strict"; + init_channelOwner(); + init_stream(); + init_fileUtils2(); + Artifact2 = class 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(path59) { + if (!this._connection.isRemote()) { + await this._channel.saveAs({ path: path59 }); + return; + } + const result2 = await this._channel.saveAsStream(); + const stream3 = Stream.from(result2.stream); + await mkdirIfNeeded2(this._platform, path59); + await new Promise((resolve, reject) => { + stream3.stream().pipe(this._platform.fs().createWriteStream(path59)).on("finish", resolve).on("error", reject); + }); + } + async failure() { + return (await this._channel.failure()).error || null; + } + async createReadStream() { + const result2 = await this._channel.stream(); + const stream3 = Stream.from(result2.stream); + return stream3.stream(); + } + async readIntoBuffer() { + const stream3 = await this.createReadStream(); + return await new Promise((resolve, reject) => { + const chunks = []; + stream3.on("data", (chunk) => { + chunks.push(chunk); + }); + stream3.on("end", () => { + resolve(Buffer.concat(chunks)); + }); + stream3.on("error", reject); + }); + } + async cancel() { + return await this._channel.cancel(); + } + async delete() { + return await this._channel.delete(); + } + }; + } +}); + +// packages/playwright-core/src/client/coverage.ts +var Coverage; +var init_coverage = __esm({ + "packages/playwright-core/src/client/coverage.ts"() { + "use strict"; + Coverage = class { + 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; + } + }; + } +}); + +// packages/playwright-core/src/client/disposable.ts +var DisposableObject2, DisposableStub; +var init_disposable3 = __esm({ + "packages/playwright-core/src/client/disposable.ts"() { + "use strict"; + init_channelOwner(); + init_errors2(); + DisposableObject2 = class extends ChannelOwner { + static from(channel) { + return channel._object; + } + async [Symbol.asyncDispose]() { + await this.dispose(); + } + async dispose() { + try { + await this._channel.dispose(); + } catch (e) { + if (isTargetClosedError2(e)) + return; + throw e; + } + } + }; + DisposableStub = class { + constructor(dispose) { + this._dispose = dispose; + } + async [Symbol.asyncDispose]() { + await this.dispose(); + } + async dispose() { + if (!this._dispose) + return; + try { + const dispose = this._dispose; + this._dispose = void 0; + await dispose(); + } catch (e) { + if (isTargetClosedError2(e)) + return; + throw e; + } + } + }; + } +}); + +// packages/playwright-core/src/client/download.ts +var Download2; +var init_download2 = __esm({ + "packages/playwright-core/src/client/download.ts"() { + "use strict"; + Download2 = class { + 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(path59) { + return await this._artifact.saveAs(path59); + } + 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(); + } + }; + } +}); + +// packages/isomorphic/locatorUtils.ts +function getByAttributeTextSelector(attrName, text2, options2) { + return `internal:attr=[${attrName}=${escapeForAttributeSelector(text2, options2?.exact || false)}]`; +} +function getByTestIdSelector(testIdAttributeName2, testId) { + return `internal:testid=[${testIdAttributeName2}=${escapeForAttributeSelector(testId, true)}]`; +} +function getByLabelSelector(text2, options2) { + return "internal:label=" + escapeForTextSelector(text2, !!options2?.exact); +} +function getByAltTextSelector(text2, options2) { + return getByAttributeTextSelector("alt", text2, options2); +} +function getByTitleSelector(text2, options2) { + return getByAttributeTextSelector("title", text2, options2); +} +function getByPlaceholderSelector(text2, options2) { + return getByAttributeTextSelector("placeholder", text2, options2); +} +function getByTextSelector(text2, options2) { + return "internal:text=" + escapeForTextSelector(text2, !!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.description !== void 0) + props.push(["description", escapeForAttributeSelector(options2.description, !!options2.exact)]); + if (options2.pressed !== void 0) + props.push(["pressed", String(options2.pressed)]); + return `internal:role=${role}${props.map(([n, v]) => `[${n}=${v}]`).join("")}`; +} +var init_locatorUtils = __esm({ + "packages/isomorphic/locatorUtils.ts"() { + "use strict"; + init_stringUtils(); + } +}); + +// packages/playwright-core/src/client/locator.ts +function testIdAttributeName() { + return _testIdAttributeName; +} +function setTestIdAttribute(attributeName) { + _testIdAttributeName = attributeName; +} +function cssObjectToString(style) { + return Object.entries(style).map(([key, value2]) => { + const property = key.startsWith("--") ? key : key.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase()); + return `${property}: ${value2}`; + }).join("; "); +} +var Locator, FrameLocator, _testIdAttributeName; +var init_locator = __esm({ + "packages/playwright-core/src/client/locator.ts"() { + "use strict"; + init_locatorGenerators(); + init_locatorUtils(); + init_stringUtils(); + init_rtti(); + init_time(); + init_elementHandle(); + init_disposable3(); + Locator = class _Locator { + constructor(frame, selector, options2) { + this._apiName = "Locator"; + this._frame = frame; + this._selector = selector; + if (options2?.hasText) + this._selector += ` >> internal:has-text=${escapeForTextSelector(options2.hasText, false)}`; + if (options2?.hasNotText) + this._selector += ` >> internal:has-not-text=${escapeForTextSelector(options2.hasNotText, false)}`; + if (options2?.has) { + const locator2 = options2.has; + if (locator2._frame !== frame) + throw new Error(`Inner "has" locator must belong to the same frame.`); + this._selector += ` >> internal:has=` + JSON.stringify(locator2._selector); + } + if (options2?.hasNot) { + const locator2 = options2.hasNot; + if (locator2._frame !== frame) + throw new Error(`Inner "hasNot" locator must belong to the same frame.`); + this._selector += ` >> internal:has-not=` + JSON.stringify(locator2._selector); + } + if (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 result2 = await this._frame._channel.waitForSelector({ selector: this._selector, strict: true, state: "attached", timeout }); + const handle = ElementHandle2.fromNullable(result2.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(locator2) { + return this._frame === locator2._frame && this._selector === locator2._selector; + } + page() { + return this._frame.page(); + } + async boundingBox(options2) { + return await this._withElement((h) => h.boundingBox(), { title: "Bounding box", timeout: 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(type3, eventInit = {}, options2) { + return await this._frame.dispatchEvent(this._selector, type3, eventInit, { strict: true, ...options2 }); + } + async dragTo(target, options2 = {}) { + return await this._frame.dragAndDrop(this._selector, target._selector, { + strict: true, + ...options2 + }); + } + async drop(payload, options2 = {}) { + await this._frame._drop(this._selector, payload, { strict: true, ...options2 }); + } + async evaluate(pageFunction, arg, options2) { + return await this._withElement((h) => h.evaluate(pageFunction, arg), { title: "Evaluate", timeout: 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?.timeout }); + } + async fill(value2, options2 = {}) { + return await this._frame.fill(this._selector, value2, { strict: true, ...options2 }); + } + async clear(options2 = {}) { + await this._frame._wrapApiCall(() => this.fill("", options2), { title: "Clear" }); + } + async _highlight() { + return await this._frame._highlight(this._selector); + } + async highlight(options2 = {}) { + const style = typeof options2.style === "object" ? cssObjectToString(options2.style) : options2.style; + await this._frame._highlight(this._selector, style); + return new DisposableStub(() => this.hideHighlight()); + } + async hideHighlight() { + await this._frame._hideHighlight(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(text2, options2) { + return this.locator(getByAltTextSelector(text2, options2)); + } + getByLabel(text2, options2) { + return this.locator(getByLabelSelector(text2, options2)); + } + getByPlaceholder(text2, options2) { + return this.locator(getByPlaceholderSelector(text2, options2)); + } + getByText(text2, options2) { + return this.locator(getByTextSelector(text2, options2)); + } + getByTitle(text2, options2) { + return this.locator(getByTitleSelector(text2, 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)); + } + description() { + return locatorCustomDescription(this._selector) || null; + } + first() { + return new _Locator(this._frame, this._selector + " >> nth=0"); + } + last() { + return new _Locator(this._frame, this._selector + ` >> nth=-1`); + } + nth(index) { + return new _Locator(this._frame, this._selector + ` >> nth=${index}`); + } + and(locator2) { + if (locator2._frame !== this._frame) + throw new Error(`Locators must belong to the same frame.`); + return new _Locator(this._frame, this._selector + ` >> internal:and=` + JSON.stringify(locator2._selector)); + } + or(locator2) { + if (locator2._frame !== this._frame) + throw new Error(`Locators must belong to the same frame.`); + return new _Locator(this._frame, this._selector + ` >> internal:or=` + JSON.stringify(locator2._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) }); + } + // options are only here for testing + async count(_options) { + return await this._frame._queryCount(this._selector, _options); + } + async normalize() { + const { resolvedSelector } = await this._frame._channel.resolveSelector({ selector: this._selector }); + return new _Locator(this._frame, resolvedSelector); + } + 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(key, options2 = {}) { + return await this._frame.press(this._selector, key, { 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 result2 = await this._frame._channel.ariaSnapshot({ timeout: this._frame._timeout(options2), mode: options2.mode, selector: this._selector, depth: options2.depth, boxes: options2.boxes }); + return result2.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(text2, options2 = {}) { + return await this._frame.type(this._selector, text2, { strict: true, ...options2 }); + } + async pressSequentially(text2, options2 = {}) { + return await this.type(text2, 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(expression2, options2) { + return this._frame._expect(expression2, { + ...options2, + selector: this._selector + }); + } + _inspect() { + return this.toString(); + } + toString() { + return asLocatorDescription("javascript", this._selector); + } + }; + FrameLocator = 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(text2, options2) { + return this.locator(getByAltTextSelector(text2, options2)); + } + getByLabel(text2, options2) { + return this.locator(getByLabelSelector(text2, options2)); + } + getByPlaceholder(text2, options2) { + return this.locator(getByPlaceholderSelector(text2, options2)); + } + getByText(text2, options2) { + return this.locator(getByTextSelector(text2, options2)); + } + getByTitle(text2, options2) { + return this.locator(getByTitleSelector(text2, 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(index) { + return new _FrameLocator(this._frame, this._frameSelector + ` >> nth=${index}`); + } + }; + _testIdAttributeName = "data-testid"; + } +}); + +// packages/playwright-core/src/client/timeoutSettings.ts +var TimeoutSettings; +var init_timeoutSettings = __esm({ + "packages/playwright-core/src/client/timeoutSettings.ts"() { + "use strict"; + init_time(); + TimeoutSettings = class { + 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; + } + }; + } +}); + +// packages/playwright-core/src/client/waiter.ts +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(log2) { + if (!log2.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)} +${log2.join("\n")} +${"=".repeat(headerLength)}`; +} +var Waiter; +var init_waiter = __esm({ + "packages/playwright-core/src/client/waiter.ts"() { + "use strict"; + init_stackTrace(); + init_errors2(); + Waiter = 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, error, predicate) { + const { promise, dispose } = waitForEvent(emitter, event, this._savedZone, predicate); + this._rejectOn(promise.then(() => { + throw typeof error === "function" ? error() : error; + }), dispose); + } + rejectOnTimeout(timeout, message) { + if (!timeout) + return; + const { promise, dispose } = waitForTimeout(timeout); + this._rejectOn(promise.then(() => { + throw new TimeoutError2(message); + }), dispose); + } + rejectImmediately(error) { + this._immediateError = error; + } + dispose() { + for (const dispose of this._dispose) + dispose(); + } + async waitForPromise(promise, dispose) { + try { + if (this._immediateError) + throw this._immediateError; + const result2 = await Promise.race([promise, ...this._failures]); + if (dispose) + dispose(); + return result2; + } 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); + } + }; + } +}); + +// packages/playwright-core/src/client/worker.ts +var Worker2; +var init_worker = __esm({ + "packages/playwright-core/src/client/worker.ts"() { + "use strict"; + init_manualPromise(); + init_channelOwner(); + init_consoleMessage(); + init_errors2(); + init_events(); + init_jsHandle(); + init_timeoutSettings(); + init_waiter(); + Worker2 = class _Worker extends ChannelOwner { + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + // Set for service workers. + this._closedScope = new LongStandingScope(); + this._setEventToSubscriptionMapping(/* @__PURE__ */ new Map([ + [Events.Worker.Console, "console"] + ])); + this._channel.on("console", (event) => { + this.emit(Events.Worker.Console, new ConsoleMessage2(this._platform, event, null, this)); + }); + 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, () => this._closedScope.close(this._closeErrorWithReason())); + } + static fromNullable(worker) { + return worker ? _Worker.from(worker) : null; + } + static from(worker) { + return worker._object; + } + _closeErrorWithReason() { + if (this._closeReason) + return new TargetClosedError2(this._closeReason); + return this._page?._closeErrorWithReason() || new TargetClosedError2(); + } + url() { + return this._initializer.url; + } + async evaluate(pageFunction, arg) { + assertMaxArguments(arguments.length, 2); + const result2 = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return parseResult(result2.value); + } + async evaluateHandle(pageFunction, arg) { + assertMaxArguments(arguments.length, 2); + const result2 = await this._channel.evaluateExpressionHandle({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return JSHandle2.from(result2.handle); + } + async waitForEvent(event, optionsOrPredicate = {}) { + return await this._wrapApiCall(async () => { + const timeoutSettings = this._page?._timeoutSettings ?? this._context?._timeoutSettings ?? new TimeoutSettings(this._platform); + const timeout = 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.Worker.Close) + waiter.rejectOnEvent(this, Events.Worker.Close, () => this._closeErrorWithReason()); + const result2 = await waiter.waitForEvent(this, event, predicate); + waiter.dispose(); + return result2; + }); + } + async _disconnect(options2 = {}) { + this._closeReason = options2.reason; + try { + await this._channel.disconnect(options2); + } catch (e) { + if (isTargetClosedError2(e)) + return; + throw e; + } + } + }; + } +}); + +// packages/playwright-core/src/client/tracing.ts +var Tracing2; +var init_tracing2 = __esm({ + "packages/playwright-core/src/client/tracing.ts"() { + "use strict"; + init_rtti(); + init_artifact2(); + init_channelOwner(); + init_disposable3(); + Tracing2 = class extends ChannelOwner { + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + this._includeSources = false; + this._additionalSources = /* @__PURE__ */ new Set(); + this._isLive = false; + this._isTracing = false; + this._harRecorders = /* @__PURE__ */ new Map(); + } + static from(channel) { + return channel._object; + } + async start(options2 = {}) { + await this._wrapApiCall(async () => { + this._includeSources = !!options2.sources; + this._isLive = !!options2.live; + 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, this._isLive); + }); + } + async startChunk(options2 = {}) { + await this._wrapApiCall(async () => { + const { traceName } = await this._channel.tracingStartChunk(options2); + await this._startCollectingStacks(traceName, this._isLive); + }); + } + async group(name, options2 = {}) { + if (options2.location) + this._additionalSources.add(options2.location.file); + await this._channel.tracingGroup({ name, location: options2.location }); + return new DisposableStub(() => this.groupEnd()); + } + async groupEnd() { + await this._channel.tracingGroupEnd(); + } + async _startCollectingStacks(traceName, live) { + if (!this._isTracing) { + this._isTracing = true; + this._connection.setIsTracing(true); + } + const result2 = await this._connection.localUtils()?.tracingStarted({ tracesDir: this._tracesDir, traceName, live }); + this._stacksId = result2?.stacksId; + } + async stopChunk(options2 = {}) { + await this._wrapApiCall(async () => { + await this._doStopChunk(options2.path); + }); + } + async stop(options2 = {}) { + await this._wrapApiCall(async () => { + await this._doStopChunk(options2.path); + await this._channel.tracingStop(); + }); + } + async startHar(path59, options2 = {}) { + await this._wrapApiCall(async () => { + if (this._harId) + throw new Error("HAR recording has already been started"); + if (options2.resourcesDir && path59.endsWith(".zip")) + throw new Error("resourcesDir option is not compatible with a .zip har file"); + const defaultContent = path59.endsWith(".zip") ? "attach" : "embed"; + this._harId = await this._recordIntoHAR(path59, null, { + url: options2.urlFilter, + updateContent: options2.content ?? defaultContent, + updateMode: options2.mode ?? "full", + resourcesDir: options2.resourcesDir + }); + }); + return new DisposableStub(() => this.stopHar()); + } + async stopHar() { + await this._wrapApiCall(async () => { + const harId = this._harId; + if (!harId) + throw new Error("HAR recording has not been started"); + this._harId = void 0; + await this._exportHAR(harId); + }); + } + async _recordIntoHAR(har, page, options2 = {}) { + const isZip = har.endsWith(".zip"); + const { harId } = await this._channel.harStart({ + page: page?._channel, + options: { + content: options2.updateContent ?? "attach", + urlGlob: isString(options2.url) ? options2.url : void 0, + urlRegexSource: isRegExp(options2.url) ? options2.url.source : void 0, + urlRegexFlags: isRegExp(options2.url) ? options2.url.flags : void 0, + mode: options2.updateMode ?? "minimal", + harPath: isZip ? void 0 : har, + resourcesDir: options2.resourcesDir + } + }); + this._harRecorders.set(harId, { path: har, resourcesDir: options2.resourcesDir }); + return harId; + } + async _exportHAR(harId) { + const harParams = this._harRecorders.get(harId); + if (!harParams) + return; + this._harRecorders.delete(harId); + const isLocal = !this._connection.isRemote(); + const isZip = harParams.path.endsWith(".zip"); + if (isLocal) { + const { entries } = await this._channel.harExport({ harId, mode: "entries" }); + if (!isZip) { + return; + } + const localUtils2 = this._connection.localUtils(); + if (!localUtils2) + throw new Error("Cannot save zipped HAR in thin clients"); + await localUtils2.zip({ zipFile: harParams.path, entries, mode: "write", includeSources: false, additionalSources: [] }); + return; + } + const { artifact: artifactChannel } = await this._channel.harExport({ harId, mode: "archive" }); + const artifact = Artifact2.from(artifactChannel); + if (isZip) { + await artifact.saveAs(harParams.path); + await artifact.delete(); + return; + } + 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, resourcesDir: harParams.resourcesDir }); + await artifact.delete(); + } + async _exportAllHars() { + await this._wrapApiCall(async () => { + await Promise.all([...this._harRecorders.keys()].map((harId) => this._exportHAR(harId))); + }, { internal: true }); + } + async _doStopChunk(filePath) { + this._resetStackCounter(); + const additionalSources = [...this._additionalSources]; + this._additionalSources.clear(); + 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 result3 = await this._channel.tracingStopChunk({ mode: "entries" }); + await localUtils.zip({ zipFile: filePath, entries: result3.entries, mode: "write", stacksId: this._stacksId, includeSources: this._includeSources, additionalSources }); + return; + } + const result2 = await this._channel.tracingStopChunk({ mode: "archive" }); + if (!result2.artifact) { + if (this._stacksId) + await localUtils.traceDiscarded({ stacksId: this._stacksId }); + return; + } + const artifact = Artifact2.from(result2.artifact); + await artifact.saveAs(filePath); + await artifact.delete(); + await localUtils.zip({ zipFile: filePath, entries: [], mode: "append", stacksId: this._stacksId, includeSources: this._includeSources, additionalSources }); + } + _resetStackCounter() { + if (this._isTracing) { + this._isTracing = false; + this._connection.setIsTracing(false); + } + } + }; + } +}); + +// packages/playwright-core/src/client/fetch.ts +async function toFormField(platform, name, value2) { + const typeOfValue = typeof value2; + if (isFilePayload(value2)) { + const payload = value2; + 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(value2) }; + } else { + return { name, file: await readStreamToJson(platform, value2) }; + } +} +function isJsonParsable(value2) { + if (typeof value2 !== "string") + return false; + try { + JSON.parse(value2); + return true; + } catch (e) { + if (e instanceof SyntaxError) + return false; + else + throw e; + } +} +function filePayloadToJson(payload) { + return { + name: payload.name, + mimeType: payload.mimeType, + buffer: payload.buffer + }; +} +async function readStreamToJson(platform, stream3) { + const buffer = await new Promise((resolve, reject) => { + const chunks = []; + stream3.on("data", (chunk) => chunks.push(chunk)); + stream3.on("end", () => resolve(Buffer.concat(chunks))); + stream3.on("error", (err) => reject(err)); + }); + const streamPath = Buffer.isBuffer(stream3.path) ? stream3.path.toString("utf8") : stream3.path; + return { + name: platform.path().basename(streamPath), + buffer + }; +} +function isJsonContentType(headers) { + if (!headers) + return false; + for (const { name, value: value2 } of headers) { + if (name.toLocaleLowerCase() === "content-type") + return value2 === "application/json"; + } + return false; +} +function objectToArray(map) { + if (!map) + return void 0; + const result2 = []; + for (const [name, value2] of Object.entries(map)) { + if (value2 !== void 0) + result2.push({ name, value: String(value2) }); + } + return result2; +} +function isFilePayload(value2) { + return typeof value2 === "object" && value2["name"] && value2["mimeType"] && value2["buffer"]; +} +var APIRequest, APIRequestContext2, APIResponse; +var init_fetch2 = __esm({ + "packages/playwright-core/src/client/fetch.ts"() { + "use strict"; + init_assert(); + init_headers(); + init_rtti(); + init_browserContext2(); + init_channelOwner(); + init_errors2(); + init_network3(); + init_tracing2(); + init_fileUtils2(); + init_timeoutSettings(); + APIRequest = class { + constructor(playwright2) { + this._contexts = /* @__PURE__ */ new Set(); + this._playwright = playwright2; + } + async newContext(options2 = {}) { + options2 = { ...options2 }; + await this._playwright._instrumentation.runBeforeCreateRequestContext(options2); + const storageState2 = typeof options2.storageState === "string" ? JSON.parse(await this._playwright._platform.fs().promises.readFile(options2.storageState, "utf8")) : options2.storageState; + const context2 = APIRequestContext2.from((await this._playwright._channel.newRequest({ + ...options2, + extraHTTPHeaders: options2.extraHTTPHeaders ? headersObjectToArray(options2.extraHTTPHeaders) : void 0, + storageState: storageState2, + tracesDir: this._playwright._defaultLaunchOptions?.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(context2); + context2._request = this; + context2._timeoutSettings.setDefaultTimeout(options2.timeout ?? this._playwright._defaultContextTimeout); + context2.tracing._tracesDir = this._playwright._defaultLaunchOptions?.tracesDir; + await context2._instrumentation.runAfterCreateRequestContext(context2); + return context2; + } + }; + APIRequestContext2 = class extends ChannelOwner { + static from(channel) { + return channel._object; + } + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + this.tracing = Tracing2.from(initializer.tracing); + this._timeoutSettings = new TimeoutSettings(this._platform); + } + async [Symbol.asyncDispose]() { + await this.dispose(); + } + async dispose(options2 = {}) { + this._closeReason = options2.reason; + await this._instrumentation.runBeforeCloseRequestContext(this); + await this.tracing._exportAllHars(); + try { + await this._channel.dispose(options2); + } catch (e) { + if (isTargetClosedError2(e)) + return; + throw e; + } + this.tracing._resetStackCounter(); + this._request?._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 () => { + 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 || options2.request?.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 || options2.request?.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, value2] of options2.form.entries()) { + if (typeof value2 !== "string") + throw new Error(`Expected string for options.form["${name}"], found File. Please use options.multipart instead.`); + formData.push({ name, value: value2 }); + } + } else { + formData = objectToArray(options2.form); + } + } else if (options2.multipart) { + multipartData = []; + if (globalThis.FormData && options2.multipart instanceof FormData) { + const form = options2.multipart; + for (const [name, value2] of form.entries()) { + if (isString(value2)) { + multipartData.push({ name, value: value2 }); + } else { + const file = { + name: value2.name, + mimeType: value2.type, + buffer: Buffer.from(await value2.arrayBuffer()) + }; + multipartData.push({ name, file }); + } + } + } else { + for (const [name, value2] of Object.entries(options2.multipart)) + multipartData.push(await toFormField(this._platform, name, value2)); + } + } + if (postDataBuffer === void 0 && jsonData === void 0 && formData === void 0 && multipartData === void 0) + postDataBuffer = options2.request?.postDataBuffer() || void 0; + const fixtures = { + __testHookLookup: options2.__testHookLookup + }; + const result2 = 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, result2.response); + }); + } + async storageState(options2 = {}) { + const state = await this._channel.storageState({ indexedDB: options2.indexedDB }); + if (options2.path) { + await mkdirIfNeeded2(this._platform, options2.path); + await this._platform.fs().promises.writeFile(options2.path, JSON.stringify(state, void 0, 2), "utf8"); + } + return state; + } + }; + APIResponse = class { + constructor(context2, initializer) { + this._apiName = "APIResponse"; + this._request = context2; + this._initializer = initializer; + this._headers = new RawHeaders(this._initializer.headers); + if (context2._platform.inspectCustom) + this[context2._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 result2 = await this._request._channel.fetchResponseBody({ fetchUid: this._fetchUid() }); + if (result2.binary === void 0) + throw new Error("Response has been disposed"); + return result2.binary; + } catch (e) { + if (isTargetClosedError2(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: value2 }) => ` ${name}: ${value2}`); + return `APIResponse: ${this.status()} ${this.statusText()} +${headers.join("\n")}`; + } + _fetchUid() { + return this._initializer.fetchUid; + } + async _fetchLog() { + const { log: log2 } = await this._request._channel.fetchLog({ fetchUid: this._fetchUid() }); + return log2; + } + }; + } +}); + +// packages/playwright-core/src/client/network.ts +function validateHeaders(headers) { + for (const key of Object.keys(headers)) { + const value2 = headers[key]; + if (!Object.is(value2, void 0) && !isString(value2)) + throw new Error(`Expected value of header "${key}" to be String, but "${typeof value2}" is found.`); + } +} +var Request2, Route2, WebSocketRoute, WebSocketRouteHandler, Response3, WebSocket2, RouteHandler, RawHeaders; +var init_network3 = __esm({ + "packages/playwright-core/src/client/network.ts"() { + "use strict"; + init_assert(); + init_headers(); + init_urlMatch(); + init_manualPromise(); + init_multimap(); + init_rtti(); + init_stackTrace(); + init_mimeType(); + init_worker(); + init_waiter(); + init_frame(); + init_fetch2(); + init_events(); + init_errors2(); + init_channelOwner(); + Request2 = class _Request extends ChannelOwner { + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + this._redirectedFrom = null; + this._redirectedTo = null; + this._failureText = null; + this._response = null; + this._fallbackOverrides = {}; + this._redirectedFrom = _Request.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 ? _Request.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() { + return (this._fallbackOverrides.postDataBuffer || this._initializer.postData)?.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?.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 Response3.fromNullable((await this._channel.response()).response); + } + async _internalResponse() { + return Response3.fromNullable((await this._channel.response()).response); + } + existingResponse() { + return this._response; + } + frame() { + if (!this._initializer.frame) { + assert(this.serviceWorker()); + throw new Error("Service Worker requests do not have an associated frame."); + } + const frame = Frame2.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() { + return Frame2.fromNullable(this._initializer.frame)?._page || null; + } + serviceWorker() { + return this._initializer.serviceWorker ? Worker2.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() { + return this.serviceWorker()?._closedScope || this._safePage()?._closedOrCrashedScope || new LongStandingScope(); + } + }; + Route2 = class extends ChannelOwner { + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + this._handlingPromise = null; + this._didThrow = false; + } + static from(route2) { + return route2._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 ??= options2.response.status(); + 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 buffer = await this._platform.fs().promises.readFile(options2.path); + body = buffer.toString("base64"); + isBase64 = true; + length = buffer.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 + })); + } + }; + WebSocketRoute = class extends ChannelOwner { + constructor(parent, type3, guid, initializer) { + super(parent, type3, 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; + }, + protocols: () => { + return [...this._initializer.protocols]; + }, + 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(route2) { + return route2._object; + } + url() { + return this._initializer.url; + } + protocols() { + return [...this._initializer.protocols]; + } + 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().catch(() => { + }); + } + }; + WebSocketRouteHandler = class { + constructor(baseURL, url2, handler) { + this._baseURL = baseURL; + this.url = url2; + this.handler = handler; + if (typeof url2 === "string") + resolveGlobToRegexPattern(baseURL, url2, true); + } + static prepareInterceptionPatterns(handlers) { + const patterns = []; + let all = false; + for (const handler of handlers) { + const serialized = serializeURLMatch(handler.url); + if (serialized) + patterns.push(serialized); + 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(); + } + }; + Response3 = class _Response extends ChannelOwner { + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + this._finishedPromise = new ManualPromise(); + this._provisionalHeaders = new RawHeaders(initializer.headers); + this._request = Request2.from(this._initializer.request); + this._request._response = this; + Object.assign(this._request._timing, this._initializer.timing); + } + static from(response2) { + return response2._object; + } + static fromNullable(response2) { + return response2 ? _Response.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; + } + async httpVersion() { + return (await this._channel.httpVersion()).value; + } + }; + WebSocket2 = class extends ChannelOwner { + static from(webSocket) { + return webSocket._object; + } + constructor(parent, type3, guid, initializer) { + super(parent, type3, 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 }) => this.emit(Events.WebSocket.Error, error)); + 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 result2 = await waiter.waitForEvent(this, event, predicate); + waiter.dispose(); + return result2; + }); + } + }; + RouteHandler = class { + 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(); + if (typeof url2 === "string") + resolveGlobToRegexPattern(baseURL, url2); + } + static prepareInterceptionPatterns(handlers) { + const patterns = []; + let all = false; + for (const handler of handlers) { + const serialized = serializeURLMatch(handler.url); + if (serialized) + patterns.push(serialized); + else + all = true; + } + if (all) + return [{ glob: "**/*" }]; + return patterns; + } + matches(requestURL) { + return urlMatches(this._baseURL, requestURL, this.url); + } + async handle(route2) { + return await this._savedZone.run(async () => this._handleImpl(route2)); + } + async _handleImpl(route2) { + const handlerInvocation = { complete: new ManualPromise(), route: route2 }; + this._activeInvocations.add(handlerInvocation); + try { + return await this._handleInternal(route2); + } catch (e) { + if (this._ignoreException) + return false; + if (isTargetClosedError2(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 promises = []; + for (const activation of this._activeInvocations) { + if (!activation.route._didThrow) + promises.push(activation.complete); + } + await Promise.all(promises); + } + } + async _handleInternal(route2) { + ++this.handledCount; + const handledPromise = route2._startHandling(); + const handler = this.handler; + const [handled] = await Promise.all([ + handledPromise, + handler(route2, route2.request()) + ]); + return handled; + } + willExpire() { + return this.handledCount + 1 >= this._times; + } + }; + RawHeaders = 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, value2]) => ({ + name, + value: value2 + })).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 result2 = {}; + for (const name of this._headersMap.keys()) + result2[name] = this.get(name); + return result2; + } + headersArray() { + return this._headersArray; + } + }; + } +}); + +// packages/playwright-core/src/client/types.ts +var kLifecycleEvents2; +var init_types2 = __esm({ + "packages/playwright-core/src/client/types.ts"() { + "use strict"; + kLifecycleEvents2 = /* @__PURE__ */ new Set(["load", "domcontentloaded", "networkidle", "commit"]); + } +}); + +// packages/playwright-core/src/client/frame.ts +function verifyLoadState(name, waitUntil) { + if (waitUntil === "networkidle0") + waitUntil = "networkidle"; + if (!kLifecycleEvents2.has(waitUntil)) + throw new Error(`${name}: expected one of (load|domcontentloaded|networkidle|commit)`); + return waitUntil; +} +var Frame2; +var init_frame = __esm({ + "packages/playwright-core/src/client/frame.ts"() { + "use strict"; + init_assert(); + init_locatorUtils(); + init_urlMatch(); + init_eventEmitter(); + init_channelOwner(); + init_clientHelper(); + init_elementHandle(); + init_events(); + init_jsHandle(); + init_locator(); + init_network3(); + init_types2(); + init_waiter(); + init_timeoutSettings(); + Frame2 = class _Frame extends ChannelOwner { + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + this._parentFrame = null; + this._url = ""; + this._name = ""; + this._detached = false; + this._childFrames = /* @__PURE__ */ new Set(); + this._eventEmitter = new EventEmitter3(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); + this._page.context().emit(Events.BrowserContext.PageLoad, 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); + this._page.context().emit(Events.BrowserContext.FrameNavigated, this); + } + }); + } + static from(frame) { + return frame._object; + } + static fromNullable(frame) { + return frame ? _Frame.from(frame) : null; + } + page() { + return this._page; + } + _timeout(options2) { + const timeoutSettings = this._page?._timeoutSettings || new TimeoutSettings(this._platform); + return timeoutSettings.timeout(options2 || {}); + } + _navigationTimeout(options2) { + const timeoutSettings = this._page?._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 Response3.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) => { + if (event.error) + return true; + waiter.log(` navigated to "${event.url}"`); + return urlMatches(this._page?.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(state = "load", options2 = {}) { + state = verifyLoadState("state", state); + return await this._page._wrapApiCall(async () => { + const waiter = this._setupNavigationWaiter(options2); + if (this._loadStates.has(state)) { + waiter.log(` not waiting, "${state}" event already fired`); + } else { + await waiter.waitForEvent(this._eventEmitter, "loadstate", (s) => { + waiter.log(` "${s}" event fired`); + return s === state; + }); + } + waiter.dispose(); + }, { title: `Wait for load state "${state}"` }); + } + async waitForURL(url2, options2 = {}) { + if (urlMatches(this._page?.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 result2 = await this._channel.evaluateExpressionHandle({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return JSHandle2.from(result2.handle); + } + async evaluate(pageFunction, arg) { + assertMaxArguments(arguments.length, 2); + const result2 = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return parseResult(result2.value); + } + async _evaluateExposeUtilityScript(pageFunction, arg) { + assertMaxArguments(arguments.length, 2); + const result2 = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return parseResult(result2.value); + } + async $(selector, options2) { + const result2 = await this._channel.querySelector({ selector, ...options2 }); + return ElementHandle2.fromNullable(result2.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 result2 = await this._channel.waitForSelector({ selector, ...options2, timeout: this._timeout(options2) }); + return ElementHandle2.fromNullable(result2.element); + } + async dispatchEvent(selector, type3, eventInit, options2 = {}) { + await this._channel.dispatchEvent({ selector, type: type3, eventInit: serializeArgument(eventInit), ...options2, timeout: this._timeout(options2) }); + } + async $eval(selector, pageFunction, arg) { + assertMaxArguments(arguments.length, 3); + const result2 = await this._channel.evalOnSelector({ selector, expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return parseResult(result2.value); + } + async $$eval(selector, pageFunction, arg) { + assertMaxArguments(arguments.length, 3); + const result2 = await this._channel.evalOnSelectorAll({ selector, expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return parseResult(result2.value); + } + async $$(selector) { + const result2 = await this._channel.querySelectorAll({ selector }); + return result2.elements.map((e) => ElementHandle2.from(e)); + } + async _queryCount(selector, options2) { + return (await this._channel.queryCount({ selector, ...options2 })).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(source8, target, options2 = {}) { + return await this._channel.dragAndDrop({ source: source8, target, ...options2, timeout: this._timeout(options2) }); + } + async _drop(selector, payload, options2 = {}) { + let fileParams = {}; + if (payload.files !== void 0) { + const converted = await convertInputFiles(this._platform, payload.files, this.page().context()); + if (converted.localDirectory || converted.directoryStream) + throw new Error("Dropping a directory is not supported \u2014 pass individual files."); + fileParams = { payloads: converted.payloads, localPaths: converted.localPaths, streams: converted.streams }; + } + const dataArray = payload.data ? Object.entries(payload.data).map(([mimeType, value2]) => ({ mimeType, value: value2 })) : void 0; + await this._channel.drop({ + selector, + ...fileParams, + data: dataArray, + ...options2, + timeout: this._timeout(options2) + }); + } + async tap(selector, options2 = {}) { + return await this._channel.tap({ selector, ...options2, timeout: this._timeout(options2) }); + } + async fill(selector, value2, options2 = {}) { + return await this._channel.fill({ selector, value: value2, ...options2, timeout: this._timeout(options2) }); + } + async _highlight(selector, style) { + return await this._channel.highlight({ selector, style }); + } + async _hideHighlight(selector) { + return await this._channel.hideHighlight({ selector }); + } + locator(selector, options2) { + return new Locator(this, selector, options2); + } + getByTestId(testId) { + return this.locator(getByTestIdSelector(testIdAttributeName(), testId)); + } + getByAltText(text2, options2) { + return this.locator(getByAltTextSelector(text2, options2)); + } + getByLabel(text2, options2) { + return this.locator(getByLabelSelector(text2, options2)); + } + getByPlaceholder(text2, options2) { + return this.locator(getByPlaceholderSelector(text2, options2)); + } + getByText(text2, options2) { + return this.locator(getByTextSelector(text2, options2)); + } + getByTitle(text2, options2) { + return this.locator(getByTitleSelector(text2, 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 value2 = (await this._channel.textContent({ selector, ...options2, timeout: this._timeout(options2) })).value; + return value2 === void 0 ? null : value2; + } + 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 value2 = (await this._channel.getAttribute({ selector, name, ...options2, timeout: this._timeout(options2) })).value; + return value2 === void 0 ? null : value2; + } + 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, text2, options2 = {}) { + await this._channel.type({ selector, text: text2, ...options2, timeout: this._timeout(options2) }); + } + async press(selector, key, options2 = {}) { + await this._channel.press({ selector, key, ...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({ waitTimeout: timeout }); + } + async waitForFunction(pageFunction, arg, options2 = {}) { + if (typeof options2.polling === "string") + assert(options2.polling === "raf", "Unknown polling option: " + options2.polling); + const result2 = 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(result2.handle); + } + async title() { + return (await this._channel.title()).value; + } + async _expect(expression2, options2) { + const params2 = { expression: expression2, ...options2, isNot: !!options2.isNot }; + params2.expectedValue = serializeArgument(options2.expectedValue); + const channelResult = await this._channel.expect(params2); + const result2 = { + matches: channelResult.matches, + log: channelResult.log, + timedOut: channelResult.timedOut, + errorMessage: channelResult.errorMessage + }; + if (channelResult.received !== void 0) { + result2.received = { + value: channelResult.received.value !== void 0 ? parseResult(channelResult.received.value) : void 0, + ariaSnapshot: channelResult.received.ariaSnapshot + }; + } + return result2; + } + }; + } +}); + +// packages/playwright-core/src/client/writableStream.ts +var WritableStream; +var init_writableStream = __esm({ + "packages/playwright-core/src/client/writableStream.ts"() { + "use strict"; + init_channelOwner(); + WritableStream = class extends ChannelOwner { + static from(Stream2) { + return Stream2._object; + } + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + } + stream() { + return this._platform.streamWritable(this._channel); + } + }; + } +}); + +// packages/playwright-core/src/client/elementHandle.ts +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) >= fileUploadSizeLimit2; +} +async function resolvePathsAndDirectoryForInputFiles(platform, items) { + let localPaths; + let localDirectory; + for (const item of items) { + const stat = await platform.fs().promises.stat(item); + if (stat.isDirectory()) { + if (localDirectory) + throw new Error("Multiple directories are not supported"); + localDirectory = platform.path().resolve(item); + } else { + localPaths ??= []; + localPaths.push(platform.path().resolve(item)); + } + } + if (localPaths?.length && localDirectory) + throw new Error("File paths must be all files or a single directory"); + return [localPaths, localDirectory]; +} +async function convertInputFiles(platform, files, context2) { + 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 (context2._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.parentPath, f.name)) : localPaths; + const { writableStreams, rootDir } = await context2._wrapApiCall(async () => context2._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 writable = WritableStream.from(writableStreams[i]); + await platform.streamFile(files2[i], writable.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; +} +var ElementHandle2; +var init_elementHandle = __esm({ + "packages/playwright-core/src/client/elementHandle.ts"() { + "use strict"; + init_assert(); + init_rtti(); + init_mimeType(); + init_frame(); + init_jsHandle(); + init_fileUtils2(); + init_writableStream(); + ElementHandle2 = class _ElementHandle extends JSHandle2 { + static from(handle) { + return handle._object; + } + static fromNullable(handle) { + return handle ? _ElementHandle.from(handle) : null; + } + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + this._frame = parent; + this._elementChannel = this._channel; + } + asElement() { + return this; + } + async ownerFrame() { + return Frame2.fromNullable((await this._elementChannel.ownerFrame()).frame); + } + async contentFrame() { + return Frame2.fromNullable((await this._elementChannel.contentFrame()).frame); + } + async getAttribute(name) { + const value2 = (await this._elementChannel.getAttribute({ name })).value; + return value2 === void 0 ? null : value2; + } + async inputValue() { + return (await this._elementChannel.inputValue()).value; + } + async textContent() { + const value2 = (await this._elementChannel.textContent()).value; + return value2 === void 0 ? null : value2; + } + 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(type3, eventInit = {}) { + await this._elementChannel.dispatchEvent({ type: type3, 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 result2 = await this._elementChannel.selectOption({ ...convertSelectOptionValues(values), ...options2, timeout: this._frame._timeout(options2) }); + return result2.values; + } + async fill(value2, options2 = {}) { + return await this._elementChannel.fill({ value: value2, ...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(text2, options2 = {}) { + await this._elementChannel.type({ text: text2, ...options2, timeout: this._frame._timeout(options2) }); + } + async press(key, options2 = {}) { + await this._elementChannel.press({ key, ...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 value2 = (await this._elementChannel.boundingBox()).value; + return value2 === void 0 ? null : value2; + } + 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((locator2) => ({ + frame: locator2._frame._channel, + selector: locator2._selector + })); + } + const result2 = await this._elementChannel.screenshot(copy); + if (options2.path) { + await mkdirIfNeeded2(this._platform, options2.path); + await this._platform.fs().promises.writeFile(options2.path, result2.binary); + } + return result2.binary; + } + async $(selector) { + return _ElementHandle.fromNullable((await this._elementChannel.querySelector({ selector })).element); + } + async $$(selector) { + const result2 = await this._elementChannel.querySelectorAll({ selector }); + return result2.elements.map((h) => _ElementHandle.from(h)); + } + async $eval(selector, pageFunction, arg) { + const result2 = await this._elementChannel.evalOnSelector({ selector, expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return parseResult(result2.value); + } + async $$eval(selector, pageFunction, arg) { + const result2 = await this._elementChannel.evalOnSelectorAll({ selector, expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return parseResult(result2.value); + } + async waitForElementState(state, options2 = {}) { + return await this._elementChannel.waitForElementState({ state, ...options2, timeout: this._frame._timeout(options2) }); + } + async waitForSelector(selector, options2 = {}) { + const result2 = await this._elementChannel.waitForSelector({ selector, ...options2, timeout: this._frame._timeout(options2) }); + return _ElementHandle.fromNullable(result2.element); + } + }; + } +}); + +// packages/playwright-core/src/client/fileChooser.ts +var FileChooser2; +var init_fileChooser2 = __esm({ + "packages/playwright-core/src/client/fileChooser.ts"() { + "use strict"; + FileChooser2 = class { + 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); + } + }; + } +}); + +// packages/playwright-core/src/client/harRouter.ts +var HarRouter; +var init_harRouter = __esm({ + "packages/playwright-core/src/client/harRouter.ts"() { + "use strict"; + HarRouter = class _HarRouter { + static async create(localUtils, file, notFoundAction, options2) { + const { harId, error } = await localUtils.harOpen({ file }); + if (error) + throw new Error(error); + 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(route2) { + const request2 = route2.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") { + route2._platform.log("api", `HAR: ${route2.request().url()} redirected to ${response2.redirectURL}`); + await route2._redirectNavigationRequest(response2.redirectURL); + return; + } + if (response2.action === "fulfill") { + if (response2.status === -1) + return; + const transformedHeaders = response2.headers.reduce((headersMap, { name, value: value2 }) => { + if (name.toLowerCase() !== "set-cookie") { + headersMap[name] = value2; + } else { + if (!headersMap["set-cookie"]) + headersMap["set-cookie"] = value2; + else + headersMap["set-cookie"] += ` +${value2}`; + } + return headersMap; + }, {}); + await route2.fulfill({ + status: response2.status, + headers: transformedHeaders, + body: response2.body + }); + return; + } + if (response2.action === "error") + route2._platform.log("api", "HAR: " + response2.message); + if (this._notFoundAction === "abort") { + await route2.abort(); + return; + } + await route2.fallback(); + } + async addContextRoute(context2) { + await context2.route(this._options.urlMatch || "**/*", (route2) => this._handle(route2)); + } + async addPageRoute(page) { + await page.route(this._options.urlMatch || "**/*", (route2) => this._handle(route2)); + } + async [Symbol.asyncDispose]() { + await this.dispose(); + } + dispose() { + this._localUtils.harClose({ harId: this._harId }).catch(() => { + }); + } + }; + } +}); + +// packages/playwright-core/src/client/input.ts +var Keyboard2, Mouse2, Touchscreen2; +var init_input2 = __esm({ + "packages/playwright-core/src/client/input.ts"() { + "use strict"; + Keyboard2 = class { + constructor(page) { + this._page = page; + } + async down(key) { + await this._page._channel.keyboardDown({ key }); + } + async up(key) { + await this._page._channel.keyboardUp({ key }); + } + async insertText(text2) { + await this._page._channel.keyboardInsertText({ text: text2 }); + } + async type(text2, options2 = {}) { + await this._page._channel.keyboardType({ text: text2, ...options2 }); + } + async press(key, options2 = {}) { + await this._page._channel.keyboardPress({ key, ...options2 }); + } + }; + Mouse2 = class { + 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 }); + } + }; + Touchscreen2 = class { + constructor(page) { + this._page = page; + } + async tap(x, y) { + await this._page._channel.touchscreenTap({ x, y }); + } + }; + } +}); + +// packages/playwright-core/src/client/video.ts +var Video; +var init_video = __esm({ + "packages/playwright-core/src/client/video.ts"() { + "use strict"; + init_eventEmitter(); + Video = class extends EventEmitter3 { + constructor(page, connection, artifact) { + super(page._platform); + this._isRemote = false; + this._isRemote = connection.isRemote(); + this._artifact = artifact; + } + async path() { + if (this._isRemote) + throw new Error(`Path is not available when connecting remotely. Use saveAs() to save a local copy.`); + if (!this._artifact) + throw new Error("Video recording has not been started."); + return this._artifact._initializer.absolutePath; + } + async saveAs(path59) { + if (!this._artifact) + throw new Error("Video recording has not been started."); + return await this._artifact.saveAs(path59); + } + async delete() { + if (this._artifact) + await this._artifact.delete(); + } + }; + } +}); + +// packages/playwright-core/src/client/screencast.ts +var Screencast2; +var init_screencast2 = __esm({ + "packages/playwright-core/src/client/screencast.ts"() { + "use strict"; + init_artifact2(); + init_disposable3(); + Screencast2 = class { + constructor(page) { + this._started = false; + this._onFrame = null; + this._page = page; + this._page._channel.on("screencastFrame", ({ data, viewportWidth, viewportHeight }) => { + void this._onFrame?.({ data, viewportWidth, viewportHeight }); + }); + } + async start(options2 = {}) { + if (this._started) + throw new Error("Screencast is already started"); + this._started = true; + if (options2.onFrame) + this._onFrame = options2.onFrame; + const result2 = await this._page._channel.screencastStart({ + size: options2.size, + quality: options2.quality, + sendFrames: !!options2.onFrame, + record: !!options2.path + }); + if (result2.artifact) { + this._artifact = Artifact2.from(result2.artifact); + this._savePath = options2.path; + } + return new DisposableStub(() => this.stop()); + } + async stop() { + await this._page._wrapApiCall(async () => { + this._started = false; + this._onFrame = null; + await this._page._channel.screencastStop(); + if (this._savePath) + await this._artifact?.saveAs(this._savePath); + this._artifact = void 0; + this._savePath = void 0; + }); + } + async showActions(options2) { + await this._page._channel.screencastShowActions({ duration: options2?.duration, position: options2?.position, fontSize: options2?.fontSize }); + return new DisposableStub(() => this._page._channel.screencastHideActions()); + } + async hideActions() { + await this._page._channel.screencastHideActions(); + } + async showOverlay(html, options2) { + const { id } = await this._page._channel.screencastShowOverlay({ html, duration: options2?.duration }); + return new DisposableStub(() => this._page._channel.screencastRemoveOverlay({ id })); + } + async showChapter(title, options2) { + await this._page._channel.screencastChapter({ title, ...options2 }); + } + async showOverlays() { + await this._page._channel.screencastSetOverlayVisible({ visible: true }); + } + async hideOverlays() { + await this._page._channel.screencastSetOverlayVisible({ visible: false }); + } + }; + } +}); + +// packages/playwright-core/src/client/page.ts +function trimUrl(param) { + if (isRegExp(param)) + return `/${trimStringWithEllipsis(param.source, 50)}/${param.flags}`; + if (isString(param)) + return `"${trimStringWithEllipsis(param, 50)}"`; +} +var Page2, BindingCall; +var init_page2 = __esm({ + "packages/playwright-core/src/client/page.ts"() { + "use strict"; + init_assert(); + init_headers(); + init_stringUtils(); + init_urlMatch(); + init_manualPromise(); + init_rtti(); + init_artifact2(); + init_channelOwner(); + init_clientHelper(); + init_coverage(); + init_disposable3(); + init_download2(); + init_elementHandle(); + init_errors2(); + init_events(); + init_fileChooser2(); + init_frame(); + init_harRouter(); + init_input2(); + init_jsHandle(); + init_network3(); + init_video(); + init_screencast2(); + init_waiter(); + init_worker(); + init_timeoutSettings(); + init_fileUtils2(); + init_consoleMessage(); + Page2 = class _Page extends ChannelOwner { + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + this._apiName = "Page"; + 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._closeWasCalled = false; + this._harRouters = []; + this._locatorHandlers = /* @__PURE__ */ new Map(); + this._instrumentation.onPage(this); + this._browserContext = parent; + this._timeoutSettings = new TimeoutSettings(this._platform, this._browserContext._timeoutSettings); + 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 = Frame2.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._video = new Video(this, this._connection, initializer.video ? Artifact2.from(initializer.video) : void 0); + this.screencast = new Screencast2(this); + this._channel.on("bindingCall", ({ binding }) => this._onBinding(BindingCall.from(binding))); + 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); + const download = new Download2(this, url2, suggestedFilename, artifactObject); + this.emit(Events.Page.Download, download); + this._browserContext.emit(Events.BrowserContext.Download, download); + }); + this._channel.on("fileChooser", ({ element: element2, isMultiple }) => this.emit(Events.Page.FileChooser, new FileChooser2(this, ElementHandle2.from(element2), isMultiple))); + this._channel.on("frameAttached", ({ frame }) => this._onFrameAttached(Frame2.from(frame))); + this._channel.on("frameDetached", ({ frame }) => this._onFrameDetached(Frame2.from(frame))); + this._channel.on("locatorHandlerTriggered", ({ uid }) => this._onLocatorHandlerTriggered(uid)); + this._channel.on("route", ({ route: route2 }) => this._onRoute(Route2.from(route2))); + this._channel.on("webSocketRoute", ({ webSocketRoute }) => this._onWebSocketRoute(WebSocketRoute.from(webSocketRoute))); + this._channel.on("viewportSizeChanged", ({ viewportSize }) => this._viewportSize = viewportSize); + this._channel.on("webSocket", ({ webSocket }) => this.emit(Events.Page.WebSocket, WebSocket2.from(webSocket))); + this._channel.on("worker", ({ worker }) => this._onWorker(Worker2.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); + this._browserContext.emit(Events.BrowserContext.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); + this._browserContext.emit(Events.BrowserContext.FrameDetached, frame); + } + async _onRoute(route2) { + route2._context = this.context(); + const routeHandlers = this._routes.slice(); + for (const routeHandler of routeHandlers) { + if (this._closeWasCalled || this._browserContext.isClosed()) + return; + if (!routeHandler.matches(route2.request().url())) + continue; + const index = this._routes.indexOf(routeHandler); + if (index === -1) + continue; + if (routeHandler.willExpire()) + this._routes.splice(index, 1); + const handled = await routeHandler.handle(route2); + if (!this._routes.length) + this._updateInterceptionPatterns({ internal: true }).catch(() => { + }); + if (handled) + return; + } + await this._browserContext._onRoute(route2); + } + async _onWebSocketRoute(webSocketRoute) { + const routeHandler = this._webSocketRoutes.find((route2) => route2.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._disposeHarRouters(); + this.emit(Events.Page.Close, this); + this._browserContext.emit(Events.BrowserContext.PageClose, 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); + } + video() { + if (!this._browserContext._options.recordVideo) + return null; + return this._video; + } + async pickLocator() { + const { selector } = await this._channel.pickLocator({}); + return this.locator(selector); + } + async cancelPickLocator() { + await this._channel.cancelPickLocator({}); + } + async hideHighlight() { + await this._channel.hideHighlight({}); + } + async $(selector, options2) { + return await this._mainFrame.$(selector, options2); + } + async waitForSelector(selector, options2) { + return await this._mainFrame.waitForSelector(selector, options2); + } + async dispatchEvent(selector, type3, eventInit, options2) { + return await this._mainFrame.dispatchEvent(selector, type3, 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) { + const result2 = await this._channel.exposeBinding({ name }); + const binding = (source8, ...args) => callback(...args); + this._bindings.set(name, binding); + return DisposableObject2.from(result2.disposable); + } + async exposeBinding(name, callback) { + const result2 = await this._channel.exposeBinding({ name }); + this._bindings.set(name, callback); + return DisposableObject2.from(result2.disposable); + } + 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 Response3.fromNullable((await this._channel.reload({ ...options2, waitUntil, timeout: this._timeoutSettings.navigationTimeout(options2) })).response); + } + async addLocatorHandler(locator2, handler, options2 = {}) { + if (locator2._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: locator2._selector, noWaitAfter: options2.noWaitAfter }); + this._locatorHandlers.set(uid, { locator: locator2, 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?.times === 0; + } finally { + if (remove) + this._locatorHandlers.delete(uid); + this._channel.resolveLocatorHandlerNoReply({ uid, remove }).catch(() => { + }); + } + } + async removeLocatorHandler(locator2) { + for (const [uid, data] of this._locatorHandlers) { + if (data.locator._equals(locator2)) { + this._locatorHandlers.delete(uid); + await this._channel.unregisterLocatorHandler({ uid }).catch(() => { + }); + } + } + } + async waitForLoadState(state, options2) { + return await this._mainFrame.waitForLoadState(state, 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(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(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 result2 = await waiter.waitForEvent(this, event, predicate); + waiter.dispose(); + return result2; + }); + } + async goBack(options2 = {}) { + const waitUntil = verifyLoadState("waitUntil", options2.waitUntil === void 0 ? "load" : options2.waitUntil); + return Response3.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 Response3.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 source8 = await evaluationScript(this._platform, script, arg); + return DisposableObject2.from((await this._channel.addInitScript({ source: source8 })).disposable); + } + async route(url2, handler, options2 = {}) { + this._routes.unshift(new RouteHandler(this._platform, this._browserContext._options.baseURL, url2, handler, options2.times)); + await this._updateInterceptionPatterns({ title: "Route requests" }); + return new DisposableStub(() => this.unroute(url2, handler)); + } + 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.tracing._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({ title: "Route WebSockets" }); + } + _disposeHarRouters() { + this._harRouters.forEach((router) => router.dispose()); + this._harRouters = []; + } + async unrouteAll(options2) { + await this._unrouteInternal(this._routes, [], options2?.behavior); + this._disposeHarRouters(); + } + async unroute(url2, handler) { + const removed = []; + const remaining = []; + for (const route2 of this._routes) { + if (urlMatchesEqual(route2.url, url2) && (!handler || route2.handler === handler)) + removed.push(route2); + else + remaining.push(route2); + } + await this._unrouteInternal(removed, remaining, "default"); + } + async _unrouteInternal(removed, remaining, behavior) { + this._routes = remaining; + if (behavior && behavior !== "default") { + const promises = removed.map((routeHandler) => routeHandler.stop(behavior)); + await Promise.all(promises); + } + await this._updateInterceptionPatterns({ title: "Unroute requests" }); + } + async _updateInterceptionPatterns(options2) { + const patterns = RouteHandler.prepareInterceptionPatterns(this._routes); + await this._wrapApiCall(() => this._channel.setNetworkInterceptionPatterns({ patterns }), options2); + } + async _updateWebSocketInterceptionPatterns(options2) { + const patterns = WebSocketRouteHandler.prepareInterceptionPatterns(this._webSocketRoutes); + await this._wrapApiCall(() => this._channel.setWebSocketInterceptionPatterns({ patterns }), options2); + } + 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((locator2) => ({ + frame: locator2._frame._channel, + selector: locator2._selector + })); + } + const result2 = await this._channel.screenshot(copy); + if (options2.path) { + await mkdirIfNeeded2(this._platform, options2.path); + await this._platform.fs().promises.writeFile(options2.path, result2.binary); + } + return result2.binary; + } + async _expectScreenshot(options2) { + const mask = options2?.mask ? options2?.mask.map((locator3) => ({ + frame: locator3._frame._channel, + selector: locator3._selector + })) : void 0; + const locator2 = options2.locator ? { + frame: options2.locator._frame._channel, + selector: options2.locator._selector + } : void 0; + return await this._channel.expectScreenshot({ + ...options2, + isNot: !!options2.isNot, + locator: locator2, + 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; + if (!options2.runBeforeUnload) + this._closeWasCalled = true; + try { + if (this._ownedContext) + await this._ownedContext.close(); + else + await this._channel.close(options2); + } catch (e) { + if (isTargetClosedError2(e) && !options2.runBeforeUnload) + return; + throw e; + } + } + isClosed() { + return this._closed; + } + async click(selector, options2) { + return await this._mainFrame.click(selector, options2); + } + async dragAndDrop(source8, target, options2) { + return await this._mainFrame.dragAndDrop(source8, 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, value2, options2) { + return await this._mainFrame.fill(selector, value2, options2); + } + async clearConsoleMessages() { + await this._channel.clearConsoleMessages(); + } + async consoleMessages(options2) { + const { messages } = await this._channel.consoleMessages({ filter: options2?.filter }); + return messages.map((message) => new ConsoleMessage2(this._platform, message, this, null)); + } + async clearPageErrors() { + await this._channel.clearPageErrors(); + } + async pageErrors(options2) { + const { errors } = await this._channel.pageErrors({ filter: options2?.filter }); + return errors.map((error) => parseError2(error)); + } + locator(selector, options2) { + return this.mainFrame().locator(selector, options2); + } + getByTestId(testId) { + return this.mainFrame().getByTestId(testId); + } + getByAltText(text2, options2) { + return this.mainFrame().getByAltText(text2, options2); + } + getByLabel(text2, options2) { + return this.mainFrame().getByLabel(text2, options2); + } + getByPlaceholder(text2, options2) { + return this.mainFrame().getByPlaceholder(text2, options2); + } + getByText(text2, options2) { + return this.mainFrame().getByText(text2, options2); + } + getByTitle(text2, options2) { + return this.mainFrame().getByTitle(text2, 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, text2, options2) { + return await this._mainFrame.type(selector, text2, options2); + } + async press(selector, key, options2) { + return await this._mainFrame.press(selector, key, 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); + } + async requests() { + const { requests: requests2 } = await this._channel.requests(); + return requests2.map((request2) => Request2.from(request2)); + } + workers() { + return [...this._workers]; + } + async pause(_options) { + 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); + this._instrumentation?.onWillPause({ keepTestTimeout: !!_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 index = margin; + if (options2.margin && typeof options2.margin[index] === "number") + transportOptions.margin[index] = transportOptions.margin[index] + "px"; + } + const result2 = 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, result2.pdf); + } + return result2.pdf; + } + async ariaSnapshot(options2 = {}) { + const result2 = await this.mainFrame()._channel.ariaSnapshot({ timeout: this._timeoutSettings.timeout(options2), track: options2._track, mode: options2.mode, depth: options2.depth, boxes: options2.boxes }); + return result2.snapshot; + } + async _setDockTile(image) { + await this._channel.setDockTile({ image }); + } + }; + BindingCall = class extends ChannelOwner { + static from(channel) { + return channel._object; + } + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + } + async call(func) { + try { + const frame = Frame2.from(this._initializer.frame); + const source8 = { + context: frame._page.context(), + page: frame._page, + frame + }; + const result2 = await func(source8, ...this._initializer.args.map(parseResult)); + this._channel.resolve({ result: serializeArgument(result2) }).catch(() => { + }); + } catch (e) { + this._channel.reject({ error: serializeError2(e) }).catch(() => { + }); + } + } + }; + } +}); + +// packages/playwright-core/src/client/dialog.ts +var Dialog2; +var init_dialog2 = __esm({ + "packages/playwright-core/src/client/dialog.ts"() { + "use strict"; + init_channelOwner(); + init_page2(); + init_errors2(); + Dialog2 = class extends ChannelOwner { + static from(dialog) { + return dialog._object; + } + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + this._page = Page2.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() { + try { + await this._channel.dismiss(); + } catch (e) { + if (isTargetClosedError2(e)) + return; + throw e; + } + } + }; + } +}); + +// packages/playwright-core/src/client/webError.ts +var WebError; +var init_webError = __esm({ + "packages/playwright-core/src/client/webError.ts"() { + "use strict"; + WebError = class { + constructor(page, error, location2) { + this._page = page; + this._error = error; + this._location = location2; + } + page() { + return this._page; + } + error() { + return this._error; + } + location() { + return this._location; + } + }; + } +}); + +// packages/playwright-core/src/client/browserContext.ts +async function prepareStorageState(platform, storageState2) { + if (typeof storageState2 !== "string") + return storageState2; + try { + return JSON.parse(await platform.fs().promises.readFile(storageState2, "utf8")); + } catch (e) { + rewriteErrorMessage(e, `Error reading storage state from ${storageState2}: +` + e.message); + throw e; + } +} +async function prepareBrowserContextParams(platform, options2) { + 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: options2.storageState ? await prepareStorageState(platform, options2.storageState) : void 0, + 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 && 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 (value2, path59) => { + if (value2) + return value2; + if (path59) + return await platform.fs().promises.readFile(path59); + }; + 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 + }))); +} +var BrowserContext2; +var init_browserContext2 = __esm({ + "packages/playwright-core/src/client/browserContext.ts"() { + "use strict"; + init_headers(); + init_urlMatch(); + init_rtti(); + init_stackTrace(); + init_cdpSession(); + init_channelOwner(); + init_clientHelper(); + init_clock2(); + init_consoleMessage(); + init_debugger2(); + init_dialog2(); + init_disposable3(); + init_errors2(); + init_events(); + init_fetch2(); + init_frame(); + init_harRouter(); + init_network3(); + init_page2(); + init_tracing2(); + init_waiter(); + init_webError(); + init_worker(); + init_timeoutSettings(); + init_fileUtils2(); + BrowserContext2 = class _BrowserContext extends ChannelOwner { + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + this._pages = /* @__PURE__ */ new Set(); + this._routes = []; + this._webSocketRoutes = []; + // Browser is null for browser contexts created outside of normal browser, e.g. android or electron. + this._browser = null; + this._bindings = /* @__PURE__ */ new Map(); + this._forReuse = false; + this._serviceWorkers = /* @__PURE__ */ new Set(); + this._closingStatus = "none"; + this._harRouters = []; + this._options = initializer.options; + this._timeoutSettings = new TimeoutSettings(this._platform); + this.debugger = Debugger2.from(initializer.debugger); + this.tracing = Tracing2.from(initializer.tracing); + this.request = APIRequestContext2.from(initializer.requestContext); + this.request._timeoutSettings = this._timeoutSettings; + this.clock = new Clock2(this); + this._channel.on("bindingCall", ({ binding }) => this._onBinding(BindingCall.from(binding))); + this._channel.on("close", () => this._onClose()); + this._channel.on("page", ({ page }) => this._onPage(Page2.from(page))); + this._channel.on("route", ({ route: route2 }) => this._onRoute(Route2.from(route2))); + this._channel.on("webSocketRoute", ({ webSocketRoute }) => this._onWebSocketRoute(WebSocketRoute.from(webSocketRoute))); + this._channel.on("serviceWorker", ({ worker }) => { + const serviceWorker = Worker2.from(worker); + serviceWorker._context = this; + this._serviceWorkers.add(serviceWorker); + this.emit(Events.BrowserContext.ServiceWorker, serviceWorker); + }); + this._channel.on("console", (event) => { + const worker = Worker2.fromNullable(event.worker); + const page = Page2.fromNullable(event.page); + const consoleMessage = new ConsoleMessage2(this._platform, event, page, worker); + worker?.emit(Events.Worker.Console, consoleMessage); + page?.emit(Events.Page.Console, consoleMessage); + if (worker && this._serviceWorkers.has(worker)) { + const scope = this._serviceWorkerScope(worker); + for (const page2 of this._pages) { + if (scope && page2.url().startsWith(scope)) + page2.emit(Events.Page.Console, consoleMessage); + } + } + this.emit(Events.BrowserContext.Console, consoleMessage); + }); + this._channel.on("pageError", ({ error, page, location: location2 }) => { + const pageObject = Page2.from(page); + const parsedError = parseError2(error); + this.emit(Events.BrowserContext.WebError, new WebError(pageObject, parsedError, location2)); + 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), Page2.fromNullable(page))); + this._channel.on("requestFailed", ({ request: request2, failureText, responseEndTiming, page }) => this._onRequestFailed(Request2.from(request2), responseEndTiming, failureText, Page2.fromNullable(page))); + this._channel.on("requestFinished", (params2) => this._onRequestFinished(params2)); + this._channel.on("response", ({ response: response2, page }) => this._onResponse(Response3.from(response2), Page2.fromNullable(page))); + this._channel.on("recorderEvent", ({ event, data, page, code }) => { + if (event === "actionAdded") + this._onRecorderEventSink?.actionAdded?.(Page2.from(page), data, code); + else if (event === "actionUpdated") + this._onRecorderEventSink?.actionUpdated?.(Page2.from(page), data, code); + else if (event === "signalAdded") + this._onRecorderEventSink?.signalAdded?.(Page2.from(page), data); + }); + 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(context2) { + return context2._object; + } + static fromNullable(context2) { + return context2 ? _BrowserContext.from(context2) : null; + } + async _initializeHarFromOptions(recordHar) { + if (!recordHar) + return; + const defaultContent = recordHar.path.endsWith(".zip") ? "attach" : "embed"; + await this.tracing._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(params2) { + const { responseEndTiming } = params2; + const request2 = Request2.from(params2.request); + const response2 = Response3.fromNullable(params2.response); + const page = Page2.fromNullable(params2.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(route2) { + route2._context = this; + const page = route2.request()._safePage(); + const routeHandlers = this._routes.slice(); + for (const routeHandler of routeHandlers) { + if (page?._closeWasCalled || this.isClosed()) + return; + if (!routeHandler.matches(route2.request().url())) + continue; + const index = this._routes.indexOf(routeHandler); + if (index === -1) + continue; + if (routeHandler.willExpire()) + this._routes.splice(index, 1); + const handled = await routeHandler.handle(route2); + if (!this._routes.length) + this._updateInterceptionPatterns({ internal: true }).catch(() => { + }); + if (handled) + return; + } + await route2._innerContinue( + true + /* isFallback */ + ).catch(() => { + }); + } + async _onWebSocketRoute(webSocketRoute) { + const routeHandler = this._webSocketRoutes.find((route2) => route2.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); + } + _serviceWorkerScope(serviceWorker) { + try { + let url2 = new URL(".", serviceWorker.url()).href; + if (!url2.endsWith("/")) + url2 += "/"; + return url2; + } catch { + return null; + } + } + setDefaultNavigationTimeout(timeout) { + this._timeoutSettings.setDefaultNavigationTimeout(timeout); + } + setDefaultTimeout(timeout) { + this._timeoutSettings.setDefaultTimeout(timeout); + } + browser() { + return this._browser; + } + pages() { + return [...this._pages]; + } + isClosed() { + return this._closingStatus !== "none"; + } + async newPage() { + if (this._ownerPage) + throw new Error("Please use browser.newContext()"); + return Page2.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(options2.name) ? options2.name.source : void 0, + nameRegexFlags: isRegExp(options2.name) ? options2.name.flags : void 0, + domain: isString(options2.domain) ? options2.domain : void 0, + domainRegexSource: isRegExp(options2.domain) ? options2.domain.source : void 0, + domainRegexFlags: isRegExp(options2.domain) ? options2.domain.flags : void 0, + path: isString(options2.path) ? options2.path : void 0, + pathRegexSource: isRegExp(options2.path) ? options2.path.source : void 0, + pathRegexFlags: isRegExp(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 source8 = await evaluationScript(this._platform, script, arg); + return DisposableObject2.from((await this._channel.addInitScript({ source: source8 })).disposable); + } + async exposeBinding(name, callback) { + const result2 = await this._channel.exposeBinding({ name }); + this._bindings.set(name, callback); + return DisposableObject2.from(result2.disposable); + } + async exposeFunction(name, callback) { + const result2 = await this._channel.exposeBinding({ name }); + const binding = (source8, ...args) => callback(...args); + this._bindings.set(name, binding); + return DisposableObject2.from(result2.disposable); + } + async route(url2, handler, options2 = {}) { + this._routes.unshift(new RouteHandler(this._platform, this._options.baseURL, url2, handler, options2.times)); + await this._updateInterceptionPatterns({ title: "Route requests" }); + return new DisposableStub(() => this.unroute(url2, handler)); + } + async routeWebSocket(url2, handler) { + this._webSocketRoutes.unshift(new WebSocketRouteHandler(this._options.baseURL, url2, handler)); + await this._updateWebSocketInterceptionPatterns({ title: "Route WebSockets" }); + } + 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.tracing._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?.behavior); + this._disposeHarRouters(); + } + async unroute(url2, handler) { + const removed = []; + const remaining = []; + for (const route2 of this._routes) { + if (urlMatchesEqual(route2.url, url2) && (!handler || route2.handler === handler)) + removed.push(route2); + else + remaining.push(route2); + } + await this._unrouteInternal(removed, remaining, "default"); + } + async _unrouteInternal(removed, remaining, behavior) { + this._routes = remaining; + if (behavior && behavior !== "default") { + const promises = removed.map((routeHandler) => routeHandler.stop(behavior)); + await Promise.all(promises); + } + await this._updateInterceptionPatterns({ title: "Unroute requests" }); + } + async _updateInterceptionPatterns(options2) { + const patterns = RouteHandler.prepareInterceptionPatterns(this._routes); + await this._wrapApiCall(() => this._channel.setNetworkInterceptionPatterns({ patterns }), options2); + } + async _updateWebSocketInterceptionPatterns(options2) { + const patterns = WebSocketRouteHandler.prepareInterceptionPatterns(this._webSocketRoutes); + await this._wrapApiCall(() => this._channel.setWebSocketInterceptionPatterns({ patterns }), options2); + } + _effectiveCloseReason() { + return this._closeReason || this._browser?._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 result2 = await waiter.waitForEvent(this, event, predicate); + waiter.dispose(); + return result2; + }); + } + async storageState(options2 = {}) { + const state = await this._channel.storageState({ indexedDB: options2.indexedDB }); + if (options2.path) { + await mkdirIfNeeded2(this._platform, options2.path); + await this._platform.fs().promises.writeFile(options2.path, JSON.stringify(state, void 0, 2), "utf8"); + } + return state; + } + async setStorageState(storageState2) { + const state = await prepareStorageState(this._platform, storageState2); + await this._channel.setStorageState({ storageState: state }); + } + backgroundPages() { + return []; + } + serviceWorkers() { + return [...this._serviceWorkers]; + } + async newCDPSession(page) { + if (!(page instanceof Page2) && !(page instanceof Frame2)) + throw new Error("page: expected Page or Frame"); + const result2 = await this._channel.newCDPSession(page instanceof Page2 ? { page: page._channel } : { frame: page._channel }); + return CDPSession2.from(result2.session); + } + _onClose() { + this._closingStatus = "closed"; + this._browser?._contexts.delete(this); + this._browser?._browserType._contexts.delete(this); + this._browser?._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.isClosed()) + return; + this._closeReason = options2.reason; + this._closingStatus = "closing"; + await this.request.dispose(options2); + await this._instrumentation.runBeforeCloseBrowserContext(this); + await this.tracing._exportAllHars(); + await this._channel.close(options2); + await this._closedPromise; + } + async _enableRecorder(params2, eventSink) { + if (eventSink) + this._onRecorderEventSink = eventSink; + await this._channel.enableRecorder(params2); + } + async _disableRecorder() { + this._onRecorderEventSink = void 0; + await this._channel.disableRecorder(); + } + async _exposeConsoleApi() { + await this._channel.exposeConsoleApi(); + } + }; + } +}); + +// packages/playwright-core/src/client/browser.ts +var Browser2; +var init_browser2 = __esm({ + "packages/playwright-core/src/client/browser.ts"() { + "use strict"; + init_artifact2(); + init_browserContext2(); + init_cdpSession(); + init_channelOwner(); + init_errors2(); + init_events(); + init_fileUtils2(); + Browser2 = class extends ChannelOwner { + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + this._contexts = /* @__PURE__ */ new Set(); + this._isConnected = true; + this._shouldCloseConnectionOnClose = false; + this._options = {}; + this._name = initializer.name; + this._browserName = initializer.browserName; + this._channel.on("context", ({ context: context2 }) => this._didCreateContext(BrowserContext2.from(context2))); + this._channel.on("close", () => this._didClose()); + this._closedPromise = new Promise((f) => this.once(Events.Browser.Disconnected, f)); + } + static from(browser) { + return browser._object; + } + browserType() { + return this._browserType; + } + async newContext(options2 = {}) { + return await this._innerNewContext(options2, false); + } + async _newContextForReuse(options2 = {}) { + return await this._innerNewContext(options2, true); + } + async _disconnectFromReusedContext(reason) { + const context2 = [...this._contexts].find((context3) => context3._forReuse); + if (!context2) + return; + await this._instrumentation.runBeforeCloseBrowserContext(context2); + for (const page of context2.pages()) + page._onClose(); + context2._onClose(); + await this._channel.disconnectFromReusedContext({ reason }); + } + async _innerNewContext(userOptions = {}, forReuse) { + const options2 = this._browserType._playwright.selectors._withSelectorOptions(userOptions); + await this._instrumentation.runBeforeCreateBrowserContext(options2); + const contextOptions = await prepareBrowserContextParams(this._platform, options2); + const response2 = forReuse ? await this._channel.newContextForReuse(contextOptions) : await this._channel.newContext(contextOptions); + const context2 = BrowserContext2.from(response2.context); + if (forReuse) + context2._forReuse = true; + if (options2.logger) + context2._logger = options2.logger; + await context2._initializeHarFromOptions(options2.recordHar); + await this._instrumentation.runAfterCreateBrowserContext(context2); + return context2; + } + _connectToBrowserType(browserType, browserOptions, logger) { + this._browserType = browserType; + this._options = browserOptions; + this._logger = logger; + for (const context2 of this._contexts) + this._setupBrowserContext(context2); + } + _didCreateContext(context2) { + context2._browser = this; + this._contexts.add(context2); + if (this._browserType) + this._setupBrowserContext(context2); + this.emit(Events.Browser.Context, context2); + } + _setupBrowserContext(context2) { + context2._logger = this._logger; + context2.tracing._tracesDir = this._options.tracesDir; + this._browserType._contexts.add(context2); + this._browserType._playwright.selectors._contextsForSelectors.add(context2); + context2.setDefaultTimeout(this._browserType._playwright._defaultContextTimeout); + context2.setDefaultNavigationTimeout(this._browserType._playwright._defaultContextNavigationTimeout); + } + contexts() { + return [...this._contexts]; + } + version() { + return this._initializer.version; + } + async bind(title, options2 = {}) { + const { endpoint } = await this._channel.startServer({ title, ...options2 }); + return { endpoint }; + } + async unbind() { + await this._channel.stopServer(); + } + async newPage(options2 = {}) { + return await this._wrapApiCall(async () => { + const context2 = await this.newContext(options2); + const page = await context2.newPage(); + page._ownedContext = context2; + context2._ownerPage = page; + return page; + }, { title: "Create page" }); + } + isConnected() { + return this._isConnected; + } + async newBrowserCDPSession() { + return CDPSession2.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 buffer = await artifact.readIntoBuffer(); + await artifact.delete(); + if (this._path) { + await mkdirIfNeeded2(this._platform, this._path); + await this._platform.fs().promises.writeFile(this._path, buffer); + this._path = void 0; + } + return buffer; + } + 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 (isTargetClosedError2(e)) + return; + throw e; + } + } + _didClose() { + this._isConnected = false; + this.emit(Events.Browser.Disconnected, this); + } + }; + } +}); + +// packages/playwright-core/src/client/connect.ts +async function connectToBrowser(playwright2, params2) { + const deadline = params2.timeout ? monotonicTime() + params2.timeout : 0; + const nameParam = params2.browserName ? { "x-playwright-browser": params2.browserName } : {}; + const headers = { ...nameParam, ...params2.headers }; + const connectParams = { + endpoint: params2.endpoint, + headers, + exposeNetwork: params2.exposeNetwork, + slowMo: params2.slowMo, + timeout: params2.timeout || 0 + }; + if (params2.__testHookRedirectPortForwarding) + connectParams.socksProxyRedirectPortForTest = params2.__testHookRedirectPortForwarding; + const connection = await connectToEndpoint(playwright2._connection, connectParams); + let browser; + connection.on("close", () => { + for (const context2 of browser?.contexts() || []) { + for (const page of context2.pages()) + page._onClose(); + context2._onClose(); + } + setTimeout(() => browser?._didClose(), 0); + }); + const result2 = await raceAgainstDeadline(async () => { + if (params2.__testHookBeforeCreateBrowser) + await params2.__testHookBeforeCreateBrowser(); + const playwright3 = await connection.initializePlaywright(); + if (!playwright3._initializer.preLaunchedBrowser) { + connection.close(); + throw new Error("Malformed endpoint. Did you use BrowserType.launchServer method?"); + } + playwright3.selectors = playwright3.selectors; + browser = Browser2.from(playwright3._initializer.preLaunchedBrowser); + browser._shouldCloseConnectionOnClose = true; + browser.on(Events.Browser.Disconnected, () => connection.close()); + return browser; + }, deadline); + if (!result2.timedOut) { + return result2.result; + } else { + connection.close(); + throw new Error(`Timeout ${params2.timeout}ms exceeded`); + } +} +async function connectToEndpoint(parentConnection, params2) { + const localUtils = parentConnection.localUtils(); + const transport = localUtils ? new JsonPipeTransport(localUtils) : new WebSocketTransport2(); + const connectHeaders = await transport.connect(params2); + 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; +} +var JsonPipeTransport, WebSocketTransport2; +var init_connect = __esm({ + "packages/playwright-core/src/client/connect.ts"() { + "use strict"; + init_time(); + init_timeoutRunner(); + init_browser2(); + init_connection(); + init_events(); + JsonPipeTransport = class { + constructor(owner) { + this._owner = owner; + } + async connect(params2) { + const { pipe, headers: connectHeaders } = await this._owner._channel.connect(params2); + 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(() => { + }); + } + }; + WebSocketTransport2 = class { + async connect(params2) { + this._ws = new window.WebSocket(params2.endpoint); + 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(); + } + }; + } +}); + +// packages/playwright-core/src/client/android.ts +async function loadFile(platform, file) { + if (isString(file)) + return await platform.fs().promises.readFile(file); + return file; +} +function toSelectorChannel(selector) { + const { + checkable, + checked, + clazz, + clickable, + depth, + desc, + enabled, + focusable, + focused, + hasChild, + hasDescendant, + longClickable, + pkg, + res, + scrollable, + selected, + text: text2 + } = selector; + const toRegex = (value2) => { + if (value2 === void 0) + return void 0; + if (isRegExp(value2)) + return value2.source; + return "^" + value2.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d") + "$"; + }; + return { + checkable, + checked, + clazz: toRegex(clazz), + pkg: toRegex(pkg), + desc: toRegex(desc), + res: toRegex(res), + text: toRegex(text2), + 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 + }; +} +var Android2, AndroidDevice2, AndroidSocket, AndroidInput, AndroidWebView; +var init_android2 = __esm({ + "packages/playwright-core/src/client/android.ts"() { + "use strict"; + init_rtti(); + init_time(); + init_timeoutRunner(); + init_eventEmitter(); + init_browserContext2(); + init_channelOwner(); + init_errors2(); + init_events(); + init_waiter(); + init_timeoutSettings(); + init_connect(); + Android2 = class extends ChannelOwner { + static from(android) { + return android._object; + } + constructor(parent, type3, guid, initializer) { + super(parent, type3, 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) => AndroidDevice2.from(d)); + } + async launchServer(options2 = {}) { + if (!this._serverLauncher) + throw new Error("Launching server is not supported"); + return await this._serverLauncher.launchServer(options2); + } + async connect(endpoint, options2 = {}) { + return await this._wrapApiCall(async () => { + const deadline = options2.timeout ? monotonicTime() + options2.timeout : 0; + const headers = { "x-playwright-browser": "android", ...options2.headers }; + const connectParams = { endpoint, headers, slowMo: options2.slowMo, timeout: options2.timeout || 0 }; + const connection = await connectToEndpoint(this._connection, connectParams); + let device; + connection.on("close", () => { + device?._didClose(); + }); + const result2 = 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 = AndroidDevice2.from(playwright2._initializer.preConnectedAndroidDevice); + device._shouldCloseConnectionOnClose = true; + device.on(Events.AndroidDevice.Close, () => connection.close()); + return device; + }, deadline); + if (!result2.timedOut) { + return result2.result; + } else { + connection.close(); + throw new Error(`Timeout ${options2.timeout}ms exceeded`); + } + }); + } + }; + AndroidDevice2 = class extends ChannelOwner { + constructor(parent, type3, guid, initializer) { + super(parent, type3, 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, text2, options2 = {}) { + await this._channel.fill({ androidSelector: toSelectorChannel(selector), text: text2, ...options2, timeout: this._timeoutSettings.timeout(options2) }); + } + async press(selector, key, options2 = {}) { + await this.tap(selector, options2); + await this.input.press(key); + } + 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 } = await this._channel.screenshot(); + if (options2.path) + await this._platform.fs().promises.writeFile(options2.path, binary); + return binary; + } + async [Symbol.asyncDispose]() { + await this.close(); + } + async close() { + try { + if (this._shouldCloseConnectionOnClose) + this._connection.close(); + else + await this._channel.close(); + } catch (e) { + if (isTargetClosedError2(e)) + return; + throw e; + } + } + _didClose() { + this.emit(Events.AndroidDevice.Close, this); + } + async shell(command) { + const { result: result2 } = await this._channel.shell({ command }); + return result2; + } + async open(command) { + return AndroidSocket.from((await this._channel.open({ command })).socket); + } + async installApk(file, options2) { + await this._channel.installApk({ file: await loadFile(this._platform, file), args: options2 && options2.args }); + } + async push(file, path59, options2) { + await this._channel.push({ file: await loadFile(this._platform, file), path: path59, mode: options2 ? options2.mode : void 0 }); + } + async launchBrowser(options2 = {}) { + const contextOptions = await prepareBrowserContextParams(this._platform, options2); + const result2 = await this._channel.launchBrowser(contextOptions); + const context2 = BrowserContext2.from(result2.context); + const selectors = this._android._playwright.selectors; + selectors._contextsForSelectors.add(context2); + context2.once(Events.BrowserContext.Close, () => selectors._contextsForSelectors.delete(context2)); + await context2._initializeHarFromOptions(options2.recordHar); + return context2; + } + 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 result2 = await waiter.waitForEvent(this, event, predicate); + waiter.dispose(); + return result2; + }); + } + }; + AndroidSocket = class extends ChannelOwner { + static from(androidDevice) { + return androidDevice._object; + } + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + this._channel.on("data", ({ data }) => this.emit(Events.AndroidSocket.Data, data)); + this._channel.on("close", () => this.emit(Events.AndroidSocket.Close)); + } + async write(data) { + await this._channel.write({ data }); + } + async close() { + await this._channel.close(); + } + async [Symbol.asyncDispose]() { + await this.close(); + } + }; + AndroidInput = class { + constructor(device) { + this._device = device; + } + async type(text2) { + await this._device._channel.inputType({ text: text2 }); + } + async press(key) { + await this._device._channel.inputPress({ key }); + } + async tap(point) { + await this._device._channel.inputTap({ point }); + } + async swipe(from, segments, steps) { + await this._device._channel.inputSwipe({ segments, steps }); + } + async drag(from, to, steps) { + await this._device._channel.inputDrag({ from, to, steps }); + } + }; + AndroidWebView = class extends EventEmitter3 { + constructor(device, data) { + super(device._platform); + this._device = device; + this._data = data; + } + 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: context2 } = await this._device._channel.connectToWebView({ socketName: this._data.socketName }); + return BrowserContext2.from(context2).pages()[0]; + } + }; + } +}); + +// packages/playwright-core/src/client/browserType.ts +var BrowserType2; +var init_browserType2 = __esm({ + "packages/playwright-core/src/client/browserType.ts"() { + "use strict"; + init_assert(); + init_headers(); + init_browser2(); + init_browserContext2(); + init_channelOwner(); + init_clientHelper(); + init_connect(); + init_timeoutSettings(); + init_worker(); + BrowserType2 = class 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 = {}) { + 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 || this._playwright._defaultLaunchOptions?.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 ? envObjectToArray2(options2.env) : void 0, + timeout: new TimeoutSettings(this._platform).launchTimeout(options2) + }; + return await this._wrapApiCall(async () => { + const browser = Browser2.from((await this._channel.launch(launchOptions)).browser); + browser._connectToBrowserType(this, options2, logger); + return browser; + }); + } + 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 = {}) { + assert(!options2.port, "Cannot specify a port without launching as a server."); + options2 = this._playwright.selectors._withSelectorOptions({ + ...this._playwright._defaultLaunchOptions, + ...options2 + }); + await this._instrumentation.runBeforeCreateBrowserContext(options2); + const logger = options2.logger || this._playwright._defaultLaunchOptions?.logger; + 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 ? envObjectToArray2(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) + }; + const context2 = await this._wrapApiCall(async () => { + const result2 = await this._channel.launchPersistentContext(persistentParams); + const browser = Browser2.from(result2.browser); + browser._connectToBrowserType(this, options2, logger); + const context3 = BrowserContext2.from(result2.context); + await context3._initializeHarFromOptions(options2.recordHar); + return context3; + }); + await this._instrumentation.runAfterCreateBrowserContext(context2); + return context2; + } + async connect(optionsOrEndpoint, options2) { + if (typeof optionsOrEndpoint === "string") + return await this._connect({ ...options2, endpoint: optionsOrEndpoint }); + assert(optionsOrEndpoint.wsEndpoint, "options.wsEndpoint is required"); + return await this._connect({ ...options2, endpoint: optionsOrEndpoint.wsEndpoint }); + } + async _connect(params2) { + return await this._wrapApiCall(async () => { + const browser = await connectToBrowser(this._playwright, { browserName: this.name(), ...params2 }); + browser._connectToBrowserType(this, {}, void 0); + return browser; + }); + } + 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, params2 = {}) { + if (this.name() !== "chromium") + throw new Error("Connecting over CDP is only supported in Chromium."); + const headers = params2.headers ? headersObjectToArray(params2.headers) : void 0; + const result2 = await this._channel.connectOverCDP({ + endpointURL, + headers, + slowMo: params2.slowMo, + timeout: new TimeoutSettings(this._platform).timeout(params2), + isLocal: params2.isLocal, + noDefaults: params2.noDefaults + }); + const browser = Browser2.from(result2.browser); + browser._connectToBrowserType(this, {}, void 0); + if (result2.defaultContext) + await this._instrumentation.runAfterCreateBrowserContext(BrowserContext2.from(result2.defaultContext)); + return browser; + } + async _connectToWorker(endpoint, options2 = {}) { + if (this.name() !== "chromium") + throw new Error("Connecting to workers is only supported in Chromium."); + const result2 = await this._channel.connectToWorker({ + endpoint, + timeout: new TimeoutSettings(this._platform).timeout(options2) + }); + return Worker2.from(result2.worker); + } + }; + } +}); + +// packages/playwright-core/src/client/clientInstrumentation.ts +function createInstrumentation2() { + 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 (...params2) => { + for (const listener of listeners) + await listener[prop]?.(...params2); + }; + } + if (prop.startsWith("on")) { + return (...params2) => { + for (const listener of listeners) + listener[prop]?.(...params2); + }; + } + return obj[prop]; + } + }); +} +var init_clientInstrumentation = __esm({ + "packages/playwright-core/src/client/clientInstrumentation.ts"() { + "use strict"; + } +}); + +// packages/playwright-core/src/client/electron.ts +var Electron2, ElectronApplication2; +var init_electron2 = __esm({ + "packages/playwright-core/src/client/electron.ts"() { + "use strict"; + init_browserContext2(); + init_channelOwner(); + init_clientHelper(); + init_consoleMessage(); + init_errors2(); + init_events(); + init_jsHandle(); + init_waiter(); + init_timeoutSettings(); + Electron2 = class extends ChannelOwner { + static from(electron) { + return electron._object; + } + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + } + async launch(options2 = {}) { + options2 = this._playwright.selectors._withSelectorOptions(options2); + const params2 = { + ...await prepareBrowserContextParams(this._platform, options2), + env: envObjectToArray2(options2.env ? options2.env : this._platform.env), + tracesDir: options2.tracesDir, + artifactsDir: options2.artifactsDir, + timeout: new TimeoutSettings(this._platform).launchTimeout(options2) + }; + const app = ElectronApplication2.from((await this._channel.launch(params2)).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; + } + }; + ElectronApplication2 = class extends ChannelOwner { + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + this._windows = /* @__PURE__ */ new Set(); + this._timeoutSettings = new TimeoutSettings(this._platform); + this._context = BrowserContext2.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, null, null))); + this._setEventToSubscriptionMapping(/* @__PURE__ */ new Map([ + [Events.ElectronApplication.Console, "console"] + ])); + } + static from(electronApplication) { + return electronApplication._object; + } + process() { + return this._connection.toImpl?.(this)?.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 (isTargetClosedError2(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 result2 = await waiter.waitForEvent(this, event, predicate); + waiter.dispose(); + return result2; + }); + } + async browserWindow(page) { + const result2 = await this._channel.browserWindow({ page: page._channel }); + return JSHandle2.from(result2.handle); + } + async evaluate(pageFunction, arg) { + const result2 = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return parseResult(result2.value); + } + async evaluateHandle(pageFunction, arg) { + const result2 = await this._channel.evaluateExpressionHandle({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return JSHandle2.from(result2.handle); + } + }; + } +}); + +// packages/playwright-core/src/client/jsonPipe.ts +var JsonPipe; +var init_jsonPipe = __esm({ + "packages/playwright-core/src/client/jsonPipe.ts"() { + "use strict"; + init_channelOwner(); + JsonPipe = class extends ChannelOwner { + static from(jsonPipe) { + return jsonPipe._object; + } + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + } + channel() { + return this._channel; + } + }; + } +}); + +// packages/playwright-core/src/client/localUtils.ts +var LocalUtils; +var init_localUtils2 = __esm({ + "packages/playwright-core/src/client/localUtils.ts"() { + "use strict"; + init_channelOwner(); + LocalUtils = class extends ChannelOwner { + constructor(parent, type3, guid, initializer) { + super(parent, type3, guid, initializer); + this.devices = {}; + for (const { name, descriptor } of initializer.deviceDescriptors) + this.devices[name] = descriptor; + } + async zip(params2) { + return await this._channel.zip(params2); + } + async harOpen(params2) { + return await this._channel.harOpen(params2); + } + async harLookup(params2) { + return await this._channel.harLookup(params2); + } + async harClose(params2) { + return await this._channel.harClose(params2); + } + async harUnzip(params2) { + return await this._channel.harUnzip(params2); + } + async tracingStarted(params2) { + return await this._channel.tracingStarted(params2); + } + async traceDiscarded(params2) { + return await this._channel.traceDiscarded(params2); + } + async addStackToTracingNoReply(params2) { + return await this._channel.addStackToTracingNoReply(params2); + } + }; + } +}); + +// packages/playwright-core/src/client/selectors.ts +var Selectors2; +var init_selectors2 = __esm({ + "packages/playwright-core/src/client/selectors.ts"() { + "use strict"; + init_clientHelper(); + init_locator(); + Selectors2 = class { + constructor(platform) { + this._selectorEngines = []; + this._contextsForSelectors = /* @__PURE__ */ new Set(); + this._platform = platform; + } + async register(name, script, options2 = {}) { + if (this._selectorEngines.some((engine) => engine.name === name)) + throw new Error(`selectors.register: "${name}" selector engine has been already registered`); + const source8 = await evaluationScript(this._platform, script, void 0, false); + const selectorEngine = { ...options2, name, source: source8 }; + for (const context2 of this._contextsForSelectors) + await context2._channel.registerSelectorEngine({ selectorEngine }); + this._selectorEngines.push(selectorEngine); + } + setTestIdAttribute(attributeName) { + this._testIdAttributeName = attributeName; + setTestIdAttribute(attributeName); + for (const context2 of this._contextsForSelectors) { + context2._options.testIdAttributeName = attributeName; + context2._channel.setTestIdAttributeName({ testIdAttributeName: attributeName }).catch(() => { + }); + } + } + _withSelectorOptions(options2) { + return { ...options2, selectorEngines: this._selectorEngines, testIdAttributeName: this._testIdAttributeName }; + } + }; + } +}); + +// packages/playwright-core/src/client/playwright.ts +var Playwright2; +var init_playwright2 = __esm({ + "packages/playwright-core/src/client/playwright.ts"() { + "use strict"; + init_android2(); + init_browser2(); + init_browserType2(); + init_channelOwner(); + init_electron2(); + init_errors2(); + init_fetch2(); + init_selectors2(); + Playwright2 = class extends ChannelOwner { + constructor(parent, type3, guid, initializer) { + super(parent, type3, 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.devices = this._connection.localUtils()?.devices ?? {}; + this.selectors = new Selectors2(this._connection._platform); + this.errors = { TimeoutError: TimeoutError2 }; + } + static from(channel) { + return channel._object; + } + _browserTypes() { + return [this.chromium, this.firefox, this.webkit]; + } + _preLaunchedBrowser() { + const browser = Browser2.from(this._initializer.preLaunchedBrowser); + browser._connectToBrowserType(this[browser._name], {}, void 0); + return browser; + } + _allContexts() { + return this._browserTypes().flatMap((type3) => [...type3._contexts]); + } + _allPages() { + return this._allContexts().flatMap((context2) => context2.pages()); + } + }; + } +}); + +// packages/playwright-core/src/client/connection.ts +function formatCallLog(platform, log2) { + if (!log2 || !log2.some((l) => !!l)) + return ""; + return ` +Call log: +${platform.colors.dim(log2.join("\n"))} +`; +} +var Root, DummyChannelOwner, Connection; +var init_connection = __esm({ + "packages/playwright-core/src/client/connection.ts"() { + "use strict"; + init_stackTrace(); + init_eventEmitter(); + init_android2(); + init_artifact2(); + init_browser2(); + init_browserContext2(); + init_browserType2(); + init_cdpSession(); + init_channelOwner(); + init_clientInstrumentation(); + init_debugger2(); + init_dialog2(); + init_disposable3(); + init_electron2(); + init_elementHandle(); + init_errors2(); + init_fetch2(); + init_frame(); + init_jsHandle(); + init_jsonPipe(); + init_localUtils2(); + init_network3(); + init_page2(); + init_playwright2(); + init_stream(); + init_tracing2(); + init_worker(); + init_writableStream(); + init_validator(); + Root = class extends ChannelOwner { + constructor(connection) { + super(connection, "Root", "", {}); + } + async initialize() { + return Playwright2.from((await this._channel.initialize({ + sdkLanguage: "javascript" + })).playwright); + } + }; + DummyChannelOwner = class extends ChannelOwner { + }; + Connection = class extends EventEmitter3 { + 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._objectFactories = /* @__PURE__ */ new Map(); + this._instrumentation = instrumentation || createInstrumentation2(); + this._localUtils = localUtils; + this._rootObject = new Root(this); + this.headers = headers; + this.registerObjectFactories({ + Android: (parent, type3, guid, init) => new Android2(parent, type3, guid, init), + AndroidDevice: (parent, type3, guid, init) => new AndroidDevice2(parent, type3, guid, init), + AndroidSocket: (parent, type3, guid, init) => new AndroidSocket(parent, type3, guid, init), + APIRequestContext: (parent, type3, guid, init) => new APIRequestContext2(parent, type3, guid, init), + Artifact: (parent, type3, guid, init) => new Artifact2(parent, type3, guid, init), + BindingCall: (parent, type3, guid, init) => new BindingCall(parent, type3, guid, init), + Browser: (parent, type3, guid, init) => new Browser2(parent, type3, guid, init), + BrowserContext: (parent, type3, guid, init) => new BrowserContext2(parent, type3, guid, init), + BrowserType: (parent, type3, guid, init) => new BrowserType2(parent, type3, guid, init), + CDPSession: (parent, type3, guid, init) => new CDPSession2(parent, type3, guid, init), + Debugger: (parent, type3, guid, init) => new Debugger2(parent, type3, guid, init), + Dialog: (parent, type3, guid, init) => new Dialog2(parent, type3, guid, init), + Disposable: (parent, type3, guid, init) => new DisposableObject2(parent, type3, guid, init), + Electron: (parent, type3, guid, init) => new Electron2(parent, type3, guid, init), + ElectronApplication: (parent, type3, guid, init) => new ElectronApplication2(parent, type3, guid, init), + ElementHandle: (parent, type3, guid, init) => new ElementHandle2(parent, type3, guid, init), + Frame: (parent, type3, guid, init) => new Frame2(parent, type3, guid, init), + JSHandle: (parent, type3, guid, init) => new JSHandle2(parent, type3, guid, init), + JsonPipe: (parent, type3, guid, init) => new JsonPipe(parent, type3, guid, init), + LocalUtils: (parent, type3, guid, init) => { + const result2 = new LocalUtils(parent, type3, guid, init); + if (!this._localUtils) + this._localUtils = result2; + return result2; + }, + Page: (parent, type3, guid, init) => new Page2(parent, type3, guid, init), + Playwright: (parent, type3, guid, init) => new Playwright2(parent, type3, guid, init), + Request: (parent, type3, guid, init) => new Request2(parent, type3, guid, init), + Response: (parent, type3, guid, init) => new Response3(parent, type3, guid, init), + Route: (parent, type3, guid, init) => new Route2(parent, type3, guid, init), + Stream: (parent, type3, guid, init) => new Stream(parent, type3, guid, init), + SocksSupport: (parent, type3, guid, init) => new DummyChannelOwner(parent, type3, guid, init), + Tracing: (parent, type3, guid, init) => new Tracing2(parent, type3, guid, init), + WebSocket: (parent, type3, guid, init) => new WebSocket2(parent, type3, guid, init), + WebSocketRoute: (parent, type3, guid, init) => new WebSocketRoute(parent, type3, guid, init), + Worker: (parent, type3, guid, init) => new Worker2(parent, type3, guid, init), + WritableStream: (parent, type3, guid, init) => new WritableStream(parent, type3, guid, init) + }); + } + registerObjectFactories(factories) { + for (const [type3, factory] of Object.entries(factories)) + this._objectFactories.set(type3, factory); + } + 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, params2, options2) { + 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 type3 = object._type; + const id = ++this._lastId; + const message = { id, guid, method, params: params2 }; + if (this._platform.isLogEnabled("channel")) { + this._platform.log("channel", "SEND> " + JSON.stringify(message)); + } + const location2 = options2.frames?.[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 && type3 !== "LocalUtils") + this._localUtils?.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: type3, 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: params2, result: result2, error, log: log2 } = message; + if (id) { + if (this._platform.isLogEnabled("channel")) + this._platform.log("channel", " createInProcessPlaywright, + playwright: () => playwright +}); +function createInProcessPlaywright() { + const playwright2 = createPlaywright({ sdkLanguage: process.env.PW_LANG_NAME || "javascript" }); + const clientConnection = new Connection(nodePlatform(packageRoot)); + clientConnection.useRawBuffers(); + const dispatcherConnection = new DispatcherConnection( + true + /* local */ + ); + dispatcherConnection.onmessage = (message) => clientConnection.dispatch(message); + clientConnection.onmessage = (message) => dispatcherConnection.dispatch(message); + const rootScope = new RootDispatcher(dispatcherConnection); + new PlaywrightDispatcher(rootScope, playwright2); + const playwrightAPI = clientConnection.getObjectWithKnownName("Playwright"); + playwrightAPI.chromium._serverLauncher = new BrowserServerLauncherImpl("chromium"); + playwrightAPI.firefox._serverLauncher = new BrowserServerLauncherImpl("firefox"); + playwrightAPI.webkit._serverLauncher = new BrowserServerLauncherImpl("webkit"); + playwrightAPI._android._serverLauncher = new AndroidServerLauncherImpl(); + dispatcherConnection.onmessage = (message) => setImmediate(() => clientConnection.dispatch(message)); + clientConnection.onmessage = (message) => setImmediate(() => dispatcherConnection.dispatch(message)); + clientConnection.toImpl = (x) => { + if (x instanceof Connection) + return x === clientConnection ? dispatcherConnection : void 0; + if (!x) + return dispatcherConnection._dispatcherByGuid.get(""); + return dispatcherConnection._dispatcherByGuid.get(x._guid)._object; + }; + return playwrightAPI; +} +var playwright; +var init_inprocess = __esm({ + "packages/playwright-core/src/inprocess.ts"() { + "use strict"; + init_nodePlatform(); + init_androidServerImpl(); + init_browserServerImpl(); + init_server(); + init_connection(); + init_package(); + playwright = createInProcessPlaywright(); + } +}); + +// packages/playwright-core/src/tools/backend/utils.ts +async function waitForCompletion(tab2, callback) { + const requests2 = []; + const requestListener = (request2) => requests2.push(request2); + const disposeListeners = () => { + tab2.page.off("request", requestListener); + }; + tab2.page.on("request", requestListener); + let result2; + try { + result2 = await callback(); + await tab2.waitForTimeout(500); + } finally { + disposeListeners(); + } + const requestedNavigation = requests2.some((request2) => request2.isNavigationRequest()); + if (requestedNavigation) { + await tab2.page.mainFrame().waitForLoadState("load", { timeout: 1e4 }).catch(() => { + }); + return result2; + } + const promises = []; + for (const request2 of requests2) { + if (["document", "stylesheet", "script", "xhr", "fetch"].includes(request2.resourceType())) + promises.push(request2.response().then((r) => r?.finished()).catch(() => { + })); + else + promises.push(request2.response().catch(() => { + })); + } + const timeout = new Promise((resolve) => setTimeout(resolve, 5e3)); + await Promise.race([Promise.all(promises), timeout]); + if (requests2.length) + await tab2.waitForTimeout(500); + return result2; +} +function eventWaiter(page, event, timeout) { + const disposables = []; + const eventPromise = new Promise((resolve, reject) => { + page.on(event, resolve); + disposables.push(() => page.off(event, resolve)); + }); + let abort; + const abortPromise = new Promise((resolve, reject) => { + abort = () => resolve(void 0); + }); + const timeoutPromise = new Promise((f) => { + const timeoutId = setTimeout(() => f(void 0), timeout); + disposables.push(() => clearTimeout(timeoutId)); + }); + return { + promise: Promise.race([eventPromise, abortPromise, timeoutPromise]).finally(() => disposables.forEach((dispose) => dispose())), + abort + }; +} +var init_utils3 = __esm({ + "packages/playwright-core/src/tools/backend/utils.ts"() { + "use strict"; + } +}); + +// packages/playwright-core/src/tools/backend/logFile.ts +var import_fs41, import_path38, debug5, LogFile; +var init_logFile = __esm({ + "packages/playwright-core/src/tools/backend/logFile.ts"() { + "use strict"; + import_fs41 = __toESM(require("fs")); + import_path38 = __toESM(require("path")); + debug5 = require("./utilsBundle").debug; + LogFile = class { + constructor(context2, startTime, filePrefix, title) { + this._stopped = false; + this._line = 0; + this._entries = 0; + this._lastLine = 0; + this._lastEntries = 0; + this._writeChain = Promise.resolve(); + this._context = context2; + this._startTime = startTime; + this._filePrefix = filePrefix; + this._title = title; + } + appendLine(wallTime, text2) { + this._writeChain = this._writeChain.then(() => this._write(wallTime, text2)).catch((e) => debug5("pw:tools:error")(e)); + } + stop() { + this._stopped = true; + } + async take(relativeTo) { + const logChunk = await this._take(); + if (!logChunk) + return void 0; + const logFilePath = relativeTo ? import_path38.default.relative(relativeTo, logChunk.file) : logChunk.file; + const lineRange = logChunk.fromLine === logChunk.toLine ? `#L${logChunk.fromLine}` : `#L${logChunk.fromLine}-L${logChunk.toLine}`; + return `${logFilePath}${lineRange}`; + } + async _take() { + await this._writeChain; + if (!this._file || this._entries === this._lastEntries) + return void 0; + const chunk = { + type: this._title.toLowerCase(), + file: this._file, + fromLine: this._lastLine + 1, + toLine: this._line, + entryCount: this._entries - this._lastEntries + }; + this._lastLine = this._line; + this._lastEntries = this._entries; + return chunk; + } + async _write(wallTime, text2) { + if (this._stopped) + return; + this._file ??= await this._context.outputFile({ prefix: this._filePrefix, ext: "log", date: new Date(this._startTime) }, { origin: "code" }); + const relativeTime = Math.round(wallTime - this._startTime); + const logLine = `[${String(relativeTime).padStart(8, " ")}ms] ${text2} +`; + await import_fs41.default.promises.appendFile(this._file, logLine); + const lineCount = logLine.split("\n").length - 1; + this._line += lineCount; + this._entries++; + } + }; + } +}); + +// packages/playwright-core/src/tools/backend/tool.ts +function defineTool(tool) { + return tool; +} +function defineTabTool(tool) { + return { + ...tool, + handle: async (context2, params2, response2, signal) => { + const tab2 = await context2.ensureTab(); + const modalStates = tab2.modalStates().map((state) => state.type); + if (tool.clearsModalState && !modalStates.includes(tool.clearsModalState)) + response2.addError(`Error: The tool "${tool.schema.name}" can only be used when there is related modal state present.`); + else if (!tool.clearsModalState && modalStates.length) + response2.addError(`Error: Tool "${tool.schema.name}" does not handle the modal state.`); + else + return tool.handle(tab2, params2, response2, signal); + } + }; +} +var init_tool = __esm({ + "packages/playwright-core/src/tools/backend/tool.ts"() { + "use strict"; + } +}); + +// packages/playwright-core/src/tools/backend/dialogs.ts +var z, handleDialog, dialogs_default; +var init_dialogs = __esm({ + "packages/playwright-core/src/tools/backend/dialogs.ts"() { + "use strict"; + init_tool(); + z = require("./utilsBundle").z; + handleDialog = defineTabTool({ + capability: "core", + schema: { + name: "browser_handle_dialog", + title: "Handle a dialog", + description: "Handle a dialog", + inputSchema: z.object({ + accept: z.boolean().describe("Whether to accept the dialog."), + promptText: z.string().optional().describe("The text of the prompt in case of a prompt dialog.") + }), + type: "action" + }, + handle: async (tab2, params2, response2) => { + const dialogState = tab2.modalStates().find((state) => state.type === "dialog"); + if (!dialogState) + throw new Error("No dialog visible"); + tab2.clearModalState(dialogState); + await tab2.waitForCompletion(async () => { + if (params2.accept) + await dialogState.dialog.accept(params2.promptText); + else + await dialogState.dialog.dismiss(); + }); + }, + clearsModalState: "dialog" + }); + dialogs_default = [ + handleDialog + ]; + } +}); + +// packages/playwright-core/src/tools/backend/snapshot.ts +var z2, elementTargetDescription, optionalElementSchema, elementSchema, snapshot, clickSchema, click, drag, hover, selectOptionSchema, selectOption, generateLocator, check, uncheck, snapshot_default; +var init_snapshot = __esm({ + "packages/playwright-core/src/tools/backend/snapshot.ts"() { + "use strict"; + init_stringUtils(); + init_tool(); + z2 = require("./utilsBundle").z; + elementTargetDescription = "Exact target element reference from the page snapshot, or a unique element selector"; + optionalElementSchema = z2.object({ + element: z2.string().optional().describe("Human-readable element description used to obtain permission to interact with the element"), + target: z2.string().optional().describe(elementTargetDescription) + }); + elementSchema = z2.object({ + element: z2.string().optional().describe("Human-readable element description used to obtain permission to interact with the element"), + target: z2.string().describe(elementTargetDescription) + }); + snapshot = defineTabTool({ + capability: "core", + schema: { + name: "browser_snapshot", + title: "Page snapshot", + description: "Capture accessibility snapshot of the current page, this is better than screenshot", + inputSchema: z2.object({ + target: z2.string().optional().describe(elementTargetDescription), + filename: z2.string().optional().describe("Save snapshot to markdown file instead of returning it in the response."), + depth: z2.number().optional().describe("Limit the depth of the snapshot tree"), + boxes: z2.boolean().optional().describe("Include each element's bounding box as [box=x,y,width,height] in the snapshot. Coordinates are viewport-relative, in CSS pixels (Element.getBoundingClientRect)") + }), + type: "readOnly" + }, + handle: async (tab2, params2, response2) => { + let resolved = { locator: void 0, resolved: "" }; + if (params2.target) + resolved = await tab2.targetLocator({ target: params2.target }); + response2.setIncludeFullSnapshot(params2.filename, resolved.locator, params2.depth, params2.boxes); + } + }); + clickSchema = elementSchema.extend({ + doubleClick: z2.boolean().optional().describe("Whether to perform a double click instead of a single click"), + button: z2.enum(["left", "right", "middle"]).optional().describe("Button to click, defaults to left"), + modifiers: z2.array(z2.enum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"])).optional().describe("Modifier keys to press") + }); + click = defineTabTool({ + capability: "core", + schema: { + name: "browser_click", + title: "Click", + description: "Perform click on a web page", + inputSchema: clickSchema, + type: "input" + }, + handle: async (tab2, params2, response2) => { + response2.setIncludeSnapshot(); + const { locator: locator2, resolved } = await tab2.targetLocator(params2); + const options2 = { + button: params2.button, + modifiers: params2.modifiers, + ...tab2.actionTimeoutOptions + }; + const optionsArg = formatObjectOrVoid(options2); + if (params2.doubleClick) + response2.addCode(`await page.${resolved}.dblclick(${optionsArg});`); + else + response2.addCode(`await page.${resolved}.click(${optionsArg});`); + await tab2.waitForCompletion(async () => { + if (params2.doubleClick) + await locator2.dblclick(options2); + else + await locator2.click(options2); + }); + } + }); + drag = defineTabTool({ + capability: "core", + schema: { + name: "browser_drag", + title: "Drag mouse", + description: "Perform drag and drop between two elements", + inputSchema: z2.object({ + startElement: z2.string().optional().describe("Human-readable source element description used to obtain the permission to interact with the element"), + startTarget: z2.string().describe(elementTargetDescription), + endElement: z2.string().optional().describe("Human-readable target element description used to obtain the permission to interact with the element"), + endTarget: z2.string().describe(elementTargetDescription) + }), + type: "input" + }, + handle: async (tab2, params2, response2) => { + response2.setIncludeSnapshot(); + const [start3, end] = await tab2.targetLocators([ + { target: params2.startTarget, element: params2.startElement }, + { target: params2.endTarget, element: params2.endElement } + ]); + await tab2.waitForCompletion(async () => { + await start3.locator.dragTo(end.locator, tab2.actionTimeoutOptions); + }); + response2.addCode(`await page.${start3.resolved}.dragTo(page.${end.resolved});`); + } + }); + hover = defineTabTool({ + capability: "core", + schema: { + name: "browser_hover", + title: "Hover mouse", + description: "Hover over element on page", + inputSchema: elementSchema, + type: "input" + }, + handle: async (tab2, params2, response2) => { + response2.setIncludeSnapshot(); + const { locator: locator2, resolved } = await tab2.targetLocator(params2); + response2.addCode(`await page.${resolved}.hover();`); + await locator2.hover(tab2.actionTimeoutOptions); + } + }); + selectOptionSchema = elementSchema.extend({ + values: z2.array(z2.string()).describe("Array of values to select in the dropdown. This can be a single value or multiple values.") + }); + selectOption = defineTabTool({ + capability: "core", + schema: { + name: "browser_select_option", + title: "Select option", + description: "Select an option in a dropdown", + inputSchema: selectOptionSchema, + type: "input" + }, + handle: async (tab2, params2, response2) => { + response2.setIncludeSnapshot(); + const { locator: locator2, resolved } = await tab2.targetLocator(params2); + response2.addCode(`await page.${resolved}.selectOption(${formatObject(params2.values)});`); + await locator2.selectOption(params2.values, tab2.actionTimeoutOptions); + } + }); + generateLocator = defineTabTool({ + capability: "testing", + schema: { + name: "browser_generate_locator", + title: "Create locator for element", + description: "Generate locator for the given element to use in tests", + inputSchema: elementSchema, + type: "readOnly" + }, + handle: async (tab2, params2, response2) => { + const { resolved } = await tab2.targetLocator(params2); + response2.addTextResult(resolved); + } + }); + check = defineTabTool({ + capability: "core-input", + skillOnly: true, + schema: { + name: "browser_check", + title: "Check", + description: "Check a checkbox or radio button", + inputSchema: elementSchema, + type: "input" + }, + handle: async (tab2, params2, response2) => { + const { locator: locator2, resolved } = await tab2.targetLocator(params2); + response2.addCode(`await page.${resolved}.check();`); + await locator2.check(tab2.actionTimeoutOptions); + } + }); + uncheck = defineTabTool({ + capability: "core-input", + skillOnly: true, + schema: { + name: "browser_uncheck", + title: "Uncheck", + description: "Uncheck a checkbox or radio button", + inputSchema: elementSchema, + type: "input" + }, + handle: async (tab2, params2, response2) => { + const { locator: locator2, resolved } = await tab2.targetLocator(params2); + response2.addCode(`await page.${resolved}.uncheck();`); + await locator2.uncheck(tab2.actionTimeoutOptions); + } + }); + snapshot_default = [ + snapshot, + click, + drag, + hover, + selectOption, + generateLocator, + check, + uncheck + ]; + } +}); + +// packages/playwright-core/src/tools/backend/files.ts +var z3, uploadFile, drop, files_default; +var init_files = __esm({ + "packages/playwright-core/src/tools/backend/files.ts"() { + "use strict"; + init_stringUtils(); + init_tool(); + init_snapshot(); + z3 = require("./utilsBundle").z; + uploadFile = defineTabTool({ + capability: "core", + schema: { + name: "browser_file_upload", + title: "Upload files", + description: "Upload one or multiple files", + inputSchema: z3.object({ + paths: z3.array(z3.string()).optional().describe("The absolute paths to the files to upload. Can be single file or multiple files. If omitted, file chooser is cancelled.") + }), + type: "action" + }, + handle: async (tab2, params2, response2) => { + response2.setIncludeSnapshot(); + const modalState = tab2.modalStates().find((state) => state.type === "fileChooser"); + if (!modalState) + throw new Error("No file chooser visible"); + if (params2.paths) + await Promise.all(params2.paths.map((filePath) => response2.resolveClientFilename(filePath))); + response2.addCode(`await fileChooser.setFiles(${JSON.stringify(params2.paths)})`); + tab2.clearModalState(modalState); + await tab2.waitForCompletion(async () => { + if (params2.paths) + await modalState.fileChooser.setFiles(params2.paths); + }); + }, + clearsModalState: "fileChooser" + }); + drop = defineTabTool({ + capability: "core", + schema: { + name: "browser_drop", + title: "Drop files or data onto an element", + description: 'Drop files or MIME-typed data onto an element, as if dragged from outside the page. At least one of "paths" or "data" must be provided.', + inputSchema: elementSchema.extend({ + paths: z3.array(z3.string()).optional().describe("Absolute paths to files to drop onto the element."), + data: z3.record(z3.string(), z3.string()).optional().describe('Data to drop, as a map of MIME type to string value (e.g. {"text/plain": "hello", "text/uri-list": "https://example.com"}).') + }), + type: "action" + }, + handle: async (tab2, params2, response2) => { + if (!params2.paths?.length && !params2.data) + throw new Error('At least one of "paths" or "data" must be provided.'); + response2.setIncludeSnapshot(); + const { locator: locator2, resolved } = await tab2.targetLocator(params2); + if (params2.paths) + await Promise.all(params2.paths.map((p) => response2.resolveClientFilename(p))); + const payload = {}; + if (params2.paths?.length) + payload.files = params2.paths.length === 1 ? params2.paths[0] : params2.paths; + if (params2.data) + payload.data = params2.data; + await tab2.waitForCompletion(async () => { + await locator2.drop(payload, tab2.actionTimeoutOptions); + }); + response2.addCode(`await page.${resolved}.drop(${formatObject(payload)});`); + } + }); + files_default = [ + uploadFile, + drop + ]; + } +}); + +// packages/playwright-core/src/tools/backend/tab.ts +function messageToConsoleMessage(message) { + return { + type: message.type(), + timestamp: message.timestamp(), + text: message.text(), + toString: () => `[${message.type().toUpperCase()}] ${message.text()} @ ${message.location().url}:${message.location().lineNumber}` + }; +} +function pageErrorToConsoleMessage(errorOrValue) { + if (errorOrValue instanceof Error) { + return { + type: "error", + timestamp: Date.now(), + text: errorOrValue.message, + toString: () => errorOrValue.stack || errorOrValue.message + }; + } + return { + type: "error", + timestamp: Date.now(), + text: String(errorOrValue), + toString: () => String(errorOrValue) + }; +} +function renderModalStates(config, modalStates) { + const result2 = []; + if (modalStates.length === 0) + result2.push("- There is no modal state present"); + for (const state of modalStates) + result2.push(`- [${state.description}]: can be handled by ${config.skillMode ? state.clearedBy.skill : state.clearedBy.tool}`); + return result2; +} +function shouldIncludeMessage(thresholdLevel, type3) { + const messageLevel = consoleLevelForMessageType(type3); + return consoleMessageLevels.indexOf(messageLevel) <= consoleMessageLevels.indexOf(thresholdLevel || "info"); +} +function consoleLevelForMessageType(type3) { + switch (type3) { + case "assert": + case "error": + return "error"; + case "warning": + return "warning"; + case "count": + case "dir": + case "dirxml": + case "info": + case "log": + case "table": + case "time": + case "timeEnd": + return "info"; + case "clear": + case "debug": + case "endGroup": + case "profile": + case "profileEnd": + case "startGroup": + case "startGroupCollapsed": + case "trace": + return "debug"; + default: + return "info"; + } +} +function sanitizeForFilePath2(s) { + const sanitize = (s2) => s2.replace(/[\x00-\x2C\x2E-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+/g, "-"); + const separator = s.lastIndexOf("."); + if (separator === -1) + return sanitize(s); + return sanitize(s.substring(0, separator)) + "." + sanitize(s.substring(separator + 1)); +} +function tabHeaderEquals(a, b) { + return a.title === b.title && a.url === b.url && a.current === b.current && a.crashed === b.crashed && a.console.errors === b.console.errors && a.console.warnings === b.console.warnings && a.console.total === b.console.total; +} +var import_events27, debug6, TabEvents, Tab, consoleMessageLevels, tabSymbol; +var init_tab = __esm({ + "packages/playwright-core/src/tools/backend/tab.ts"() { + "use strict"; + import_events27 = require("events"); + init_locatorGenerators(); + init_locatorParser(); + init_manualPromise(); + init_eventsHelper(); + init_disposable(); + init_utils3(); + init_logFile(); + init_dialogs(); + init_files(); + debug6 = require("./utilsBundle").debug; + TabEvents = { + modalState: "modalState" + }; + Tab = class _Tab extends import_events27.EventEmitter { + constructor(context2, page, onPageClose) { + super(); + this._lastHeader = { title: "about:blank", url: "about:blank", current: false, crashed: false, console: { total: 0, warnings: 0, errors: 0 } }; + this._downloads = []; + this._requests = []; + this.crashed = false; + this._modalStates = []; + this._recentEventEntries = []; + this.context = context2; + this.page = page; + this._onPageClose = onPageClose; + const p = page; + this._disposables = [ + eventsHelper.addEventListener(p, "console", (event) => this._handleConsoleMessage(messageToConsoleMessage(event))), + eventsHelper.addEventListener(p, "pageerror", (error) => this._handleConsoleMessage(pageErrorToConsoleMessage(error))), + eventsHelper.addEventListener(p, "request", (request2) => this._handleRequest(request2)), + eventsHelper.addEventListener(p, "response", (response2) => this._handleResponse(response2)), + eventsHelper.addEventListener(p, "requestfailed", (request2) => this._handleRequestFailed(request2)), + eventsHelper.addEventListener(p, "close", () => this._onClose()), + eventsHelper.addEventListener(p, "crash", () => { + this.crashed = true; + }), + eventsHelper.addEventListener(p, "filechooser", (chooser) => { + this.setModalState({ + type: "fileChooser", + description: "File chooser", + fileChooser: chooser, + clearedBy: { tool: uploadFile.schema.name, skill: "upload" } + }); + }), + eventsHelper.addEventListener(p, "dialog", (dialog) => this._dialogShown(dialog)), + eventsHelper.addEventListener(p, "download", (download) => { + void this._downloadStarted(download); + }) + ]; + page[tabSymbol] = this; + const wallTime = Date.now(); + this._consoleLog = new LogFile(this.context, wallTime, "console", "Console"); + this._initializedPromise = this._initialize(); + this.actionTimeoutOptions = { timeout: context2.config.timeouts?.action }; + this.navigationTimeoutOptions = { timeout: context2.config.timeouts?.navigation }; + this.expectTimeoutOptions = { timeout: context2.config.timeouts?.expect }; + } + async dispose() { + await disposeAll(this._disposables); + this._consoleLog.stop(); + } + static forPage(page) { + return page[tabSymbol]; + } + static async collectConsoleMessages(page) { + const result2 = []; + const messages = await page.consoleMessages().catch(() => []); + for (const message of messages) + result2.push(messageToConsoleMessage(message)); + const errors = await page.pageErrors().catch(() => []); + for (const error of errors) + result2.push(pageErrorToConsoleMessage(error)); + return result2; + } + async _initialize() { + for (const message of await _Tab.collectConsoleMessages(this.page)) + this._handleConsoleMessage(message); + const requests2 = await this.page.requests().catch(() => []); + for (const request2 of requests2.filter((r) => r.existingResponse() || r.failure())) + this._requests.push(request2); + for (const initPage of this.context.config.browser?.initPage || []) { + try { + const { default: func } = require(initPage); + await func({ page: this.page }); + } catch (e) { + const reason = e instanceof Error ? e.message : String(e); + throw new Error(`Failed to load init page "${initPage}": ${reason}`, { cause: e }); + } + } + } + modalStates() { + return this._modalStates; + } + setModalState(modalState) { + this._modalStates.push(modalState); + this.emit(TabEvents.modalState, modalState); + } + clearModalState(modalState) { + this._modalStates = this._modalStates.filter((state) => state !== modalState); + } + _dialogShown(dialog) { + this.setModalState({ + type: "dialog", + description: `"${dialog.type()}" dialog with message "${dialog.message()}"`, + dialog, + clearedBy: { tool: handleDialog.schema.name, skill: "dialog-accept or dialog-dismiss" } + }); + } + async _downloadStarted(download) { + const outputFile2 = await this.context.outputFile({ suggestedFilename: sanitizeForFilePath2(download.suggestedFilename()), prefix: "download", ext: "bin" }, { origin: "code" }); + const entry = { + download, + finished: false, + outputFile: outputFile2 + }; + this._downloads.push(entry); + this._addLogEntry({ type: "download-start", wallTime: Date.now(), download: entry }); + await download.saveAs(entry.outputFile); + entry.finished = true; + this._addLogEntry({ type: "download-finish", wallTime: Date.now(), download: entry }); + } + _clearCollectedArtifacts() { + this._downloads.length = 0; + this._requests.length = 0; + this._recentEventEntries.length = 0; + this._resetLogs(); + } + _resetLogs() { + const wallTime = Date.now(); + this._consoleLog.stop(); + this._consoleLog = new LogFile(this.context, wallTime, "console", "Console"); + } + _handleRequest(request2) { + this._requests.push(request2); + const wallTime = request2.timing().startTime || Date.now(); + this._addLogEntry({ type: "request", wallTime, request: request2 }); + } + _handleResponse(response2) { + const timing = response2.request().timing(); + const wallTime = timing.responseStart + timing.startTime; + this._addLogEntry({ type: "request", wallTime, request: response2.request() }); + } + _handleRequestFailed(request2) { + this._requests.push(request2); + const timing = request2.timing(); + const wallTime = timing.responseEnd + timing.startTime; + this._addLogEntry({ type: "request", wallTime, request: request2 }); + } + _handleConsoleMessage(message) { + const wallTime = message.timestamp; + this._addLogEntry({ type: "console", wallTime, message }); + if (shouldIncludeMessage(this.context.config.console?.level, message.type)) + this._consoleLog.appendLine(wallTime, message.toString()); + } + logErrorMessage(text2) { + this._handleConsoleMessage(pageErrorToConsoleMessage(new Error(text2))); + } + _addLogEntry(entry) { + this._recentEventEntries.push(entry); + } + _onClose() { + this._clearCollectedArtifacts(); + this._onPageClose(this); + } + async headerSnapshot() { + let title; + let consoleCounts = { total: 0, errors: 0, warnings: 0 }; + if (!this.crashed) { + await this._raceAgainstModalStates(async () => { + title = await this.page.title(); + }); + consoleCounts = await this.consoleMessageCount(); + } + const newHeader = { + title: title ?? "", + url: this.page.url(), + current: this.isCurrentTab(), + crashed: this.crashed, + console: consoleCounts + }; + if (!tabHeaderEquals(this._lastHeader, newHeader)) { + this._lastHeader = newHeader; + return { ...this._lastHeader, changed: true }; + } + return { ...this._lastHeader, changed: false }; + } + isCurrentTab() { + return this === this.context.currentTab(); + } + async waitForLoadState(state, options2) { + await this._initializedPromise; + await this.page.waitForLoadState(state, options2).catch((e) => debug6("pw:tools:error")(e)); + } + async checkUrlAndNavigate(url2) { + try { + new URL(url2); + } catch (e) { + if (url2.startsWith("localhost")) + url2 = "http://" + url2; + else + url2 = "https://" + url2; + } + this.context.checkUrlAllowed(url2); + await this.navigate(url2); + return url2; + } + async navigate(url2) { + await this._initializedPromise; + this._clearCollectedArtifacts(); + const { promise: downloadEvent, abort: abortDownloadEvent } = eventWaiter(this.page, "download", 3e3); + try { + await this.page.goto(url2, { waitUntil: "domcontentloaded", ...this.navigationTimeoutOptions }); + abortDownloadEvent(); + } catch (_e) { + const e = _e; + const mightBeDownload = e.message.includes("net::ERR_ABORTED") || e.message.includes("Download is starting"); + if (!mightBeDownload) + throw e; + const download = await downloadEvent; + if (!download) + throw e; + await new Promise((resolve) => setTimeout(resolve, 500)); + return; + } + await this.waitForLoadState("load", { timeout: 5e3 }); + } + async consoleMessageCount() { + await this._initializedPromise; + const messages = await this.page.consoleMessages({ filter: "since-navigation" }); + const pageErrors = await this.page.pageErrors({ filter: "since-navigation" }); + let errors = pageErrors.length; + let warnings = 0; + for (const message of messages) { + if (message.type() === "error") + errors++; + else if (message.type() === "warning") + warnings++; + } + return { total: messages.length + pageErrors.length, errors, warnings }; + } + async consoleMessages(level, all) { + await this._initializedPromise; + const result2 = []; + const messages = await this.page.consoleMessages({ filter: all ? "all" : "since-navigation" }); + for (const message of messages) { + const cm = messageToConsoleMessage(message); + if (shouldIncludeMessage(level, cm.type)) + result2.push(cm); + } + if (shouldIncludeMessage(level, "error")) { + const errors = await this.page.pageErrors({ filter: all ? "all" : "since-navigation" }); + for (const error of errors) + result2.push(pageErrorToConsoleMessage(error)); + } + return result2; + } + async clearConsoleMessages() { + await this._initializedPromise; + await Promise.all([ + this.page.clearConsoleMessages(), + this.page.clearPageErrors() + ]); + } + async requests() { + await this._initializedPromise; + return this._requests; + } + async clearRequests() { + await this._initializedPromise; + this._requests.length = 0; + } + async captureSnapshot(root, depth, boxes, relativeTo) { + await this._initializedPromise; + let tabSnapshot; + const modalStates = await this._raceAgainstModalStates(async () => { + const ariaSnapshot = root ? await root.ariaSnapshot({ mode: "ai", depth, boxes }) : await this.page.ariaSnapshot({ mode: "ai", depth, boxes }); + tabSnapshot = { + ariaSnapshot, + modalStates: [], + events: [] + }; + }); + if (tabSnapshot) { + tabSnapshot.consoleLink = await this._consoleLog.take(relativeTo); + tabSnapshot.events = this._recentEventEntries; + this._recentEventEntries = []; + } + return tabSnapshot ?? { + ariaSnapshot: "", + modalStates, + events: [] + }; + } + _javaScriptBlocked() { + return this._modalStates.some((state) => state.type === "dialog"); + } + async _raceAgainstModalStates(action) { + if (this.modalStates().length) + return this.modalStates(); + const promise = new ManualPromise(); + const listener = (modalState) => promise.resolve([modalState]); + this.once(TabEvents.modalState, listener); + return await Promise.race([ + action().then(() => { + this.off(TabEvents.modalState, listener); + return []; + }), + promise + ]); + } + async waitForCompletion(callback) { + await this._initializedPromise; + await this._raceAgainstModalStates(() => waitForCompletion(this, callback)); + } + async targetLocator(params2) { + await this._initializedPromise; + return (await this.targetLocators([params2]))[0]; + } + async targetLocators(params2) { + await this._initializedPromise; + return Promise.all(params2.map(async (param) => { + if (!param.target.match(/^(f\d+)?e\d+$/)) { + const selector = locatorOrSelectorAsSelector("javascript", param.target, this.context.config.testIdAttribute || "data-testid"); + const handle = await this.page.$(selector); + if (!handle) + throw new Error(`"${param.target}" does not match any elements.`); + handle.dispose().catch(() => { + }); + return { locator: this.page.locator(selector), resolved: asLocator("javascript", selector) }; + } else { + try { + let locator2 = this.page.locator(`aria-ref=${param.target}`); + if (param.element) + locator2 = locator2.describe(param.element); + const resolved = await locator2.normalize(); + return { locator: locator2, resolved: resolved.toString() }; + } catch (e) { + throw new Error(`Ref ${param.target} not found in the current page snapshot. Try capturing new snapshot.`); + } + } + })); + } + async waitForTimeout(time) { + if (this._javaScriptBlocked()) { + await new Promise((f) => setTimeout(f, time)); + return; + } + await this.page.evaluate(() => new Promise((f) => setTimeout(f, 1e3))).catch(() => { + }); + } + }; + consoleMessageLevels = ["error", "warning", "info", "debug"]; + tabSymbol = Symbol("tabSymbol"); + } +}); + +// packages/playwright-core/src/tools/backend/context.ts +function originOrHostGlob(originOrHost) { + const wildcardPortMatch = originOrHost.match(/^(https?:\/\/[^/:]+):\*$/); + if (wildcardPortMatch) + return `${wildcardPortMatch[1]}:*/**`; + try { + const url2 = new URL(originOrHost); + if (url2.origin !== "null") + return `${url2.origin}/**`; + } catch { + } + return `*://${originOrHost}/**`; +} +async function workspaceFile(options2, fileName, perCallWorkspaceDir) { + const workspace = perCallWorkspaceDir ?? options2.cwd; + const resolvedName = import_path39.default.resolve(workspace, fileName); + await checkFile(options2, resolvedName, { origin: "llm" }); + return resolvedName; +} +function outputDir(options2) { + if (options2.config.outputDir) + return import_path39.default.resolve(options2.config.outputDir); + const baseName = options2.config.skillMode ? ".playwright-cli" : ".playwright-mcp"; + if (isSystemDirectory(options2.cwd) || !isWritable(options2.cwd)) + return import_path39.default.join(import_os18.default.tmpdir(), baseName); + return import_path39.default.join(options2.cwd, baseName); +} +async function outputFile(options2, fileName, flags) { + const resolvedFile = import_path39.default.resolve(outputDir(options2), fileName); + await checkFile(options2, resolvedFile, flags); + await import_fs42.default.promises.mkdir(import_path39.default.dirname(resolvedFile), { recursive: true }); + debug7("pw:mcp:file")(resolvedFile); + return resolvedFile; +} +async function checkFile(options2, resolvedFilename, flags) { + if (flags.origin === "code" || options2.config.allowUnrestrictedFileAccess || options2.config.skillMode) + return; + const output = outputDir(options2); + const workspace = options2.cwd; + if (!isPathInside(output, resolvedFilename) && !isPathInside(workspace, resolvedFilename)) + throw new Error(`File access denied: ${resolvedFilename} is outside allowed roots. Allowed roots: ${output}, ${workspace}`); +} +var import_fs42, import_os18, import_path39, debug7, testDebug, Context; +var init_context = __esm({ + "packages/playwright-core/src/tools/backend/context.ts"() { + "use strict"; + import_fs42 = __toESM(require("fs")); + import_os18 = __toESM(require("os")); + import_path39 = __toESM(require("path")); + init_stringUtils(); + init_disposable(); + init_eventsHelper(); + init_fileUtils(); + init_inprocess(); + init_tab(); + debug7 = require("./utilsBundle").debug; + testDebug = debug7("pw:mcp:test"); + Context = class { + constructor(browserContext, options2) { + this._tabs = []; + this._routes = []; + this._disposables = []; + this._pendingUnhandledRejections = []; + this._unhandledRejectionListeners = /* @__PURE__ */ new Set(); + this._onUnhandledRejection = (reason) => { + this._pendingUnhandledRejections.push(reason); + for (const listener of this._unhandledRejectionListeners) + listener(reason); + }; + this.config = options2.config; + this.sessionLog = options2.sessionLog; + this.options = options2; + this._rawBrowserContext = browserContext; + testDebug("create context"); + process.on("unhandledRejection", this._onUnhandledRejection); + } + async dispose() { + process.off("unhandledRejection", this._onUnhandledRejection); + await disposeAll(this._disposables); + for (const tab2 of this._tabs) + await tab2.dispose(); + this._tabs.length = 0; + this._currentTab = void 0; + await this.stopVideoRecording(); + } + drainPendingUnhandledRejections() { + const reasons = this._pendingUnhandledRejections.slice(); + this._pendingUnhandledRejections.length = 0; + return reasons; + } + onUnhandledRejection(listener) { + this._unhandledRejectionListeners.add(listener); + return () => this._unhandledRejectionListeners.delete(listener); + } + debugger() { + return this._rawBrowserContext.debugger; + } + tabs() { + return this._tabs; + } + currentTab() { + return this._currentTab; + } + currentTabOrDie() { + if (!this._currentTab) + throw new Error("No open pages available."); + return this._currentTab; + } + async newTab() { + const browserContext = await this.ensureBrowserContext(); + const page = await browserContext.newPage(); + this._currentTab = this._tabs.find((t) => t.page === page); + return this._currentTab; + } + async selectTab(index) { + const tab2 = this._tabs[index]; + if (!tab2) + throw new Error(`Tab ${index} not found`); + await tab2.page.bringToFront(); + this._currentTab = tab2; + return tab2; + } + async ensureTab() { + await this.ensureBrowserContext(); + const crashed = this._currentTab?.crashed; + if (crashed) { + await this._currentTab.page.close().catch(() => { + }); + this._currentTab = void 0; + } + if (!this._currentTab) + await this.newTab(); + if (crashed) + this._currentTab.logErrorMessage("Page crashed and was reset to about:blank."); + return this._currentTab; + } + async closeTab(index) { + const tab2 = index === void 0 ? this._currentTab : this._tabs[index]; + if (!tab2) + throw new Error(`Tab ${index} not found`); + const url2 = tab2.page.url(); + await tab2.page.close(); + return url2; + } + async workspaceFile(fileName, perCallWorkspaceDir) { + return await workspaceFile(this.options, fileName, perCallWorkspaceDir); + } + async outputFile(template, options2) { + const baseName = template.suggestedFilename || `${template.prefix}-${(template.date ?? /* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}${template.ext ? "." + template.ext : ""}`; + return await outputFile(this.options, baseName, options2); + } + async startVideoRecording(fileName, params2) { + if (this._video) + throw new Error("Video recording has already been started."); + this._video = { params: params2, fileName, fileNames: [] }; + const browserContext = await this.ensureBrowserContext(); + for (const page of browserContext.pages()) + await this._startPageVideo(page); + } + async stopVideoRecording() { + if (!this._video) + return []; + const video = this._video; + for (const page of this._rawBrowserContext.pages()) + await page.screencast.stop(); + this._video = void 0; + return [...video.fileNames]; + } + async _startPageVideo(page) { + if (!this._video) + return; + const suffix = this._video.fileNames.length ? `-${this._video.fileNames.length}` : ""; + let fileName = this._video.fileName; + if (fileName && suffix) { + const ext = import_path39.default.extname(fileName); + fileName = import_path39.default.basename(fileName, ext) + suffix + ext; + } + this._video.fileNames.push(fileName); + await page.screencast.start({ path: fileName, ...this._video.params }); + } + _onPageCreated(page) { + const tab2 = new Tab(this, page, (tab3) => this._onPageClosed(tab3)); + this._tabs.push(tab2); + if (!this._currentTab) + this._currentTab = tab2; + this._startPageVideo(page).catch(() => { + }); + } + _onPageClosed(tab2) { + const index = this._tabs.indexOf(tab2); + if (index === -1) + return; + this._tabs.splice(index, 1); + if (this._currentTab === tab2) + this._currentTab = this._tabs[Math.min(index, this._tabs.length - 1)]; + } + routes() { + return this._routes; + } + async addRoute(entry) { + const browserContext = await this.ensureBrowserContext(); + await browserContext.route(entry.pattern, entry.handler); + this._routes.push(entry); + } + async removeRoute(pattern) { + let removed = 0; + const browserContext = await this.ensureBrowserContext(); + if (pattern) { + const toRemove = this._routes.filter((r) => r.pattern === pattern); + for (const route2 of toRemove) + await browserContext.unroute(route2.pattern, route2.handler); + this._routes = this._routes.filter((r) => r.pattern !== pattern); + removed = toRemove.length; + } else { + for (const route2 of this._routes) + await browserContext.unroute(route2.pattern, route2.handler); + removed = this._routes.length; + this._routes = []; + } + return removed; + } + isRunningTool() { + return this._runningToolName !== void 0; + } + setRunningTool(name) { + this._runningToolName = name; + } + async _setupRequestInterception(context2) { + if (this.config.network?.allowedOrigins?.length) { + this._disposables.push(await context2.route("**", (route2) => route2.abort("blockedbyclient"))); + for (const origin of this.config.network.allowedOrigins) { + const glob = originOrHostGlob(origin); + this._disposables.push(await context2.route(glob, (route2) => route2.continue())); + } + } + if (this.config.network?.blockedOrigins?.length) { + for (const origin of this.config.network.blockedOrigins) + this._disposables.push(await context2.route(originOrHostGlob(origin), (route2) => route2.abort("blockedbyclient"))); + } + } + async ensureBrowserContext() { + if (this._browserContextPromise) + return this._browserContextPromise; + this._browserContextPromise = this._initializeBrowserContext(); + return this._browserContextPromise; + } + async _initializeBrowserContext() { + if (this.config.testIdAttribute) + playwright.selectors.setTestIdAttribute(this.config.testIdAttribute); + const browserContext = this._rawBrowserContext; + await this._setupRequestInterception(browserContext); + if (this.config.saveTrace) { + await browserContext.tracing.start({ + name: "trace-" + Date.now(), + screenshots: true, + snapshots: true, + live: true + }); + this._disposables.push({ + dispose: async () => { + await browserContext.tracing.stop(); + } + }); + } + for (const initScript of this.config.browser?.initScript || []) + this._disposables.push(await browserContext.addInitScript({ path: import_path39.default.resolve(this.options.cwd, initScript) })); + for (const page of browserContext.pages()) + this._onPageCreated(page); + this._disposables.push(eventsHelper.addEventListener(browserContext, "page", (page) => this._onPageCreated(page))); + return browserContext; + } + checkUrlAllowed(url2) { + if (this.config.allowUnrestrictedFileAccess) + return; + if (!URL.canParse(url2)) + return; + if (new URL(url2).protocol === "file:") + throw new Error(`Access to "file:" protocol is blocked. Attempted URL: "${url2}"`); + } + lookupSecret(secretName) { + if (!this.config.secrets?.[secretName]) + return { value: secretName, code: escapeWithQuotes(secretName, "'") }; + return { + value: this.config.secrets[secretName], + code: `process.env['${secretName}']` + }; + } + }; + } +}); + +// packages/playwright-core/src/tools/backend/screenshot.ts +function scaleImageToFitMessage(buffer, imageType) { + const image = imageType === "png" ? PNG3.sync.read(buffer) : jpegjs4.decode(buffer, { maxMemoryUsageInMB: 512 }); + const pixels = image.width * image.height; + const shrink = Math.min(1568 / image.width, 1568 / image.height, Math.sqrt(1.15 * 1024 * 1024 / pixels)); + if (shrink > 1) + return buffer; + const width = image.width * shrink | 0; + const height = image.height * shrink | 0; + const scaledImage = scaleImageToSize(image, { width, height }); + return imageType === "png" ? PNG3.sync.write(scaledImage) : jpegjs4.encode(scaledImage, 80).data; +} +var jpegjs4, PNG3, z4, screenshotSchema, screenshot, screenshot_default; +var init_screenshot = __esm({ + "packages/playwright-core/src/tools/backend/screenshot.ts"() { + "use strict"; + init_stringUtils(); + init_imageUtils(); + init_tool(); + init_snapshot(); + jpegjs4 = require("./utilsBundle").jpegjs; + ({ PNG: PNG3 } = require("./utilsBundle")); + z4 = require("./utilsBundle").z; + screenshotSchema = optionalElementSchema.extend({ + type: z4.enum(["png", "jpeg"]).default("png").describe("Image format for the screenshot. Default is png."), + filename: z4.string().optional().describe("File name to save the screenshot to. Defaults to `page-{timestamp}.{png|jpeg}` if not specified. Prefer relative file names to stay within the output directory."), + fullPage: z4.boolean().optional().describe("When true, takes a screenshot of the full scrollable page, instead of the currently visible viewport. Cannot be used with element screenshots.") + }); + screenshot = defineTabTool({ + capability: "core", + schema: { + name: "browser_take_screenshot", + title: "Take a screenshot", + description: `Take a screenshot of the current page. You can't perform actions based on the screenshot, use browser_snapshot for actions.`, + inputSchema: screenshotSchema, + type: "readOnly" + }, + handle: async (tab2, params2, response2) => { + if (params2.fullPage && params2.target) + throw new Error("fullPage cannot be used with element screenshots."); + const fileType = params2.type || "png"; + const options2 = { + type: fileType, + quality: fileType === "png" ? void 0 : 90, + scale: "css", + ...tab2.actionTimeoutOptions, + ...params2.fullPage !== void 0 && { fullPage: params2.fullPage } + }; + const screenshotTargetLabel = params2.target ? params2.element || "element" : params2.fullPage ? "full page" : "viewport"; + const target = params2.target ? await tab2.targetLocator({ element: params2.element, target: params2.target }) : null; + const data = target ? await target.locator.screenshot(options2) : await tab2.page.screenshot(options2); + const resolvedFile = await response2.resolveClientFile({ prefix: target ? "element" : "page", ext: fileType, suggestedFilename: params2.filename }, `Screenshot of ${screenshotTargetLabel}`); + response2.addCode(`// Screenshot ${screenshotTargetLabel} and save it as ${resolvedFile.relativeName}`); + if (target) + response2.addCode(`await page.${target.resolved}.screenshot(${formatObject({ ...options2, path: resolvedFile.relativeName })});`); + else + response2.addCode(`await page.screenshot(${formatObject({ ...options2, path: resolvedFile.relativeName })});`); + await response2.addFileResult(resolvedFile, data); + if (!params2.filename) + await response2.registerImageResult(data, fileType); + } + }); + screenshot_default = [ + screenshot + ]; + } +}); + +// packages/playwright-core/src/tools/backend/response.ts +function renderTabMarkdown(tab2) { + const lines = [`- Page URL: ${tab2.url}`]; + if (tab2.title) + lines.push(`- Page Title: ${tab2.title}`); + if (tab2.crashed) + lines.push(`- Page status: crashed`); + if (tab2.console.errors || tab2.console.warnings) + lines.push(`- Console: ${tab2.console.errors} errors, ${tab2.console.warnings} warnings`); + return lines; +} +function renderTabsMarkdown(tabs) { + if (!tabs.length) + return ["No open tabs. Navigate to a URL to create one."]; + const lines = []; + for (let i = 0; i < tabs.length; i++) { + const tab2 = tabs[i]; + const current = tab2.current ? " (current)" : ""; + const crashed = tab2.crashed ? " [crashed]" : ""; + lines.push(`- ${i}:${current} [${tab2.title}](${tab2.url})${crashed}`); + } + return lines; +} +function sanitizeUnicode(text2) { + return text2.toWellFormed?.() ?? text2; +} +function parseSections(text2) { + const sections = /* @__PURE__ */ new Map(); + const sectionHeaders = text2.split(/^### /m).slice(1); + for (const section of sectionHeaders) { + const firstNewlineIndex = section.indexOf("\n"); + if (firstNewlineIndex === -1) + continue; + const sectionName = section.substring(0, firstNewlineIndex); + const sectionContent = section.substring(firstNewlineIndex + 1).trim(); + sections.set(sectionName, sectionContent); + } + return sections; +} +function parseResponse(response2, cwd) { + if (response2.content?.[0].type !== "text") + return void 0; + const text2 = response2.content[0].text; + const sections = parseSections(text2); + const error = sections.get("Error"); + const result2 = sections.get("Result"); + const code = sections.get("Ran Playwright code"); + const tabs = sections.get("Open tabs"); + const page = sections.get("Page"); + const snapshotSection = sections.get("Snapshot"); + const events = sections.get("Events"); + const modalState = sections.get("Modal state"); + const paused = sections.get("Paused"); + const codeNoFrame = code?.replace(/^```js\n/, "").replace(/\n```$/, ""); + const isError4 = response2.isError; + const attachments = response2.content.length > 1 ? response2.content.slice(1) : void 0; + let snapshot3; + let inlineSnapshot; + if (snapshotSection) { + const match = snapshotSection.match(/\[Snapshot\]\(([^)]+)\)/); + if (match) { + if (cwd) { + try { + snapshot3 = import_fs43.default.readFileSync(import_path40.default.resolve(cwd, match[1]), "utf-8"); + } catch { + } + } + } else { + inlineSnapshot = snapshotSection.replace(/^```yaml\n?/, "").replace(/\n?```$/, ""); + } + } + return { + result: result2, + error, + code: codeNoFrame, + tabs, + page, + snapshot: snapshot3, + inlineSnapshot, + events, + modalState, + paused, + isError: isError4, + attachments, + text: text2 + }; +} +var import_fs43, import_path40, debug8, requestDebug, Response4; +var init_response = __esm({ + "packages/playwright-core/src/tools/backend/response.ts"() { + "use strict"; + import_fs43 = __toESM(require("fs")); + import_path40 = __toESM(require("path")); + init_tab(); + init_screenshot(); + debug8 = require("./utilsBundle").debug; + requestDebug = debug8("pw:mcp:request"); + Response4 = class { + constructor(context2, toolName, toolArgs, options2) { + this._results = []; + this._errors = []; + this._code = []; + this._includeSnapshot = "none"; + this._isClose = false; + this._imageResults = []; + this._context = context2; + this.toolName = toolName; + this.toolArgs = toolArgs; + this._clientWorkspace = options2?.relativeTo ?? context2.options.cwd; + this._json = options2?.json ?? false; + this._raw = this._json || (options2?.raw ?? false); + } + _computeRelativeTo(fileName) { + const rel = import_path40.default.relative(this._clientWorkspace, fileName); + if (import_path40.default.dirname(rel) === "." && !rel.startsWith(".")) + return "./" + rel; + return rel; + } + async resolveClientFile(template, title) { + let fileName; + if (template.suggestedFilename) + fileName = await this.resolveClientFilename(template.suggestedFilename); + else + fileName = await this._context.outputFile(template, { origin: "llm" }); + const relativeName = this._computeRelativeTo(fileName); + const printableLink = `- [${title}](${relativeName})`; + return { fileName, relativeName, printableLink }; + } + async resolveClientFilename(filename) { + return await this._context.workspaceFile(filename, this._clientWorkspace); + } + addTextResult(text2) { + this._results.push(text2); + } + async addResult(title, data, file) { + if (file.suggestedFilename || typeof data !== "string") { + const resolvedFile = await this.resolveClientFile(file, title); + await this.addFileResult(resolvedFile, data); + } else { + this.addTextResult(data); + } + } + async _writeFile(resolvedFile, data) { + if (typeof data === "string") + await import_fs43.default.promises.writeFile(resolvedFile.fileName, this._redactSecrets(data), "utf-8"); + else if (data) + await import_fs43.default.promises.writeFile(resolvedFile.fileName, data); + } + async addFileResult(resolvedFile, data) { + await this._writeFile(resolvedFile, data); + this.addTextResult(resolvedFile.printableLink); + } + addFileLink(title, fileName) { + const relativeName = this._computeRelativeTo(fileName); + this.addTextResult(`- [${title}](${relativeName})`); + } + async registerImageResult(data, imageType) { + this._imageResults.push({ data, imageType }); + } + setClose() { + this._isClose = true; + } + addError(error) { + this._errors.push(error); + } + addCode(code) { + this._code.push(code); + } + setIncludeSnapshot() { + this._includeSnapshot = this._context.config.snapshot?.mode ?? "full"; + } + setIncludeFullSnapshot(includeSnapshotFileName, root, depth, boxes) { + this._includeSnapshot = "explicit"; + this._includeSnapshotFileName = includeSnapshotFileName; + this._includeSnapshotDepth = depth; + this._includeSnapshotBoxes = boxes; + this._includeSnapshotRoot = root; + } + _redactSecrets(text2) { + for (const [secretName, secretValue] of Object.entries(this._context.config.secrets ?? {})) { + if (!secretValue) + continue; + text2 = text2.replaceAll(secretValue, `${secretName}`); + } + return text2; + } + async serialize() { + const allSections = await this._build(); + const rawSections = ["Error", "Result", "Snapshot"]; + const sections = this._raw ? allSections.filter((section) => rawSections.includes(section.title)) : allSections; + let serializedText; + if (this._json) { + const payload = {}; + const isError4 = sections.some((section) => section.isError); + if (isError4) + payload.isError = true; + for (const section of sections) { + if (!section.content.length) + continue; + const key = section.title.toLowerCase(); + if (key === "snapshot") { + const match = section.content[0]?.match(/^- \[Snapshot\]\(([^)]+)\)$/); + payload.snapshot = match ? { file: match[1] } : section.content.join("\n"); + } else { + payload[key] = section.content.join("\n"); + } + } + serializedText = JSON.stringify(payload, null, 2); + } else { + const text2 = []; + for (const section of sections) { + if (!section.content.length) + continue; + if (!this._raw) { + text2.push(`### ${section.title}`); + if (section.codeframe) + text2.push(`\`\`\`${section.codeframe}`); + text2.push(...section.content); + if (section.codeframe) + text2.push("```"); + } else { + text2.push(...section.content); + } + } + serializedText = text2.join("\n"); + } + const content = [ + { + type: "text", + text: sanitizeUnicode(this._redactSecrets(serializedText)) + } + ]; + if (this._context.config.imageResponses !== "omit") { + for (const imageResult of this._imageResults) { + const scaledData = scaleImageToFitMessage(imageResult.data, imageResult.imageType); + content.push({ type: "image", data: scaledData.toString("base64"), mimeType: imageResult.imageType === "png" ? "image/png" : "image/jpeg" }); + } + } + return { + content, + ...this._isClose ? { isClose: true } : {}, + ...sections.some((section) => section.isError) ? { isError: true } : {} + }; + } + async _build() { + const sections = []; + const addSection = (title, content, codeframe) => { + const section = { title, content, isError: title === "Error", codeframe }; + sections.push(section); + return content; + }; + if (this._errors.length) + addSection("Error", this._errors); + if (this._results.length) + addSection("Result", this._results); + if (this._context.config.codegen !== "none" && this._code.length) + addSection("Ran Playwright code", this._code, "js"); + const tabSnapshot = this._context.currentTab() ? await this._context.currentTabOrDie().captureSnapshot(this._includeSnapshotRoot, this._includeSnapshotDepth, this._includeSnapshotBoxes, this._clientWorkspace) : void 0; + const tabHeaders = await Promise.all(this._context.tabs().map((tab2) => tab2.headerSnapshot())); + if (this._includeSnapshot !== "none" || tabHeaders.some((header) => header.changed)) { + if (tabHeaders.length !== 1) + addSection("Open tabs", renderTabsMarkdown(tabHeaders)); + addSection("Page", renderTabMarkdown(tabHeaders.find((h) => h.current) ?? tabHeaders[0])); + } + if (this._context.tabs().length === 0) + this._isClose = true; + if (tabSnapshot?.modalStates.length) + addSection("Modal state", renderModalStates(this._context.config, tabSnapshot.modalStates)); + if (tabSnapshot && this._includeSnapshot !== "none") { + if (this._includeSnapshot !== "explicit" || this._includeSnapshotFileName) { + const suggestedFilename = this._includeSnapshotFileName === "" ? void 0 : this._includeSnapshotFileName; + const resolvedFile = await this.resolveClientFile({ prefix: "page", ext: "yml", suggestedFilename }, "Snapshot"); + await this._writeFile(resolvedFile, tabSnapshot.ariaSnapshot); + addSection("Snapshot", [resolvedFile.printableLink]); + } else { + addSection("Snapshot", [tabSnapshot.ariaSnapshot], "yaml"); + } + } + const text2 = []; + if (tabSnapshot?.consoleLink) + text2.push(`- New console entries: ${tabSnapshot.consoleLink}`); + if (tabSnapshot?.events.filter((event) => event.type !== "request").length) { + for (const event of tabSnapshot.events) { + if (event.type === "download-start") + text2.push(`- Downloading file ${event.download.download.suggestedFilename()} ...`); + else if (event.type === "download-finish") + text2.push(`- Downloaded file ${event.download.download.suggestedFilename()} to "${this._computeRelativeTo(event.download.outputFile)}"`); + } + } + if (text2.length) + addSection("Events", text2); + const pausedDetails = this._context.debugger().pausedDetails(); + if (pausedDetails) { + addSection("Paused", [ + `- ${pausedDetails.title} at ${this._computeRelativeTo(pausedDetails.location.file)}${pausedDetails.location.line ? ":" + pausedDetails.location.line : ""}`, + "- Use any tools to explore and interact, resume by calling resume/step-over/pause-at" + ]); + } + return sections; + } + }; + } +}); + +// packages/playwright-core/src/tools/backend/sessionLog.ts +var import_fs44, import_path41, SessionLog; +var init_sessionLog = __esm({ + "packages/playwright-core/src/tools/backend/sessionLog.ts"() { + "use strict"; + import_fs44 = __toESM(require("fs")); + import_path41 = __toESM(require("path")); + init_context(); + init_response(); + SessionLog = class _SessionLog { + constructor(sessionFolder, cwd) { + this._sessionFileQueue = Promise.resolve(); + this._folder = sessionFolder; + this._file = import_path41.default.join(this._folder, "session.md"); + this._cwd = cwd; + } + static async create(config, cwd) { + const sessionFolder = await outputFile({ config, cwd }, `session-${Date.now()}`, { origin: "code" }); + await import_fs44.default.promises.mkdir(sessionFolder, { recursive: true }); + console.error(`Session: ${sessionFolder}`); + return new _SessionLog(sessionFolder, cwd); + } + logResponse(toolName, toolArgs, responseObject) { + const parsed = { ...parseResponse(responseObject, this._cwd), text: void 0 }; + const lines = [""]; + lines.push( + `### Tool call: ${toolName}`, + `- Args`, + "```json", + JSON.stringify(toolArgs, null, 2), + "```" + ); + if (parsed) { + lines.push(`- Result`); + lines.push("```json"); + lines.push(JSON.stringify(parsed, null, 2)); + lines.push("```"); + } + lines.push(""); + this._sessionFileQueue = this._sessionFileQueue.then(() => import_fs44.default.promises.appendFile(this._file, lines.join("\n"))); + } + }; + } +}); + +// packages/playwright-core/src/tools/backend/browserBackend.ts +function formatRejectionReason(reason) { + if (reason instanceof Error) + return reason.stack ?? reason.message; + return String(reason); +} +var debug9, BrowserBackend; +var init_browserBackend = __esm({ + "packages/playwright-core/src/tools/backend/browserBackend.ts"() { + "use strict"; + init_context(); + init_response(); + init_sessionLog(); + debug9 = require("./utilsBundle").debug; + BrowserBackend = class { + constructor(config, browserContext, tools) { + this._disconnected = false; + this._config = config; + this._tools = tools; + this.browserContext = browserContext; + const markDisconnected = () => { + this._disconnected = true; + }; + this.browserContext.once("close", markDisconnected); + this.browserContext.browser()?.once("disconnected", markDisconnected); + } + async initialize(clientInfo) { + this._sessionLog = this._config.saveSession ? await SessionLog.create(this._config, clientInfo.cwd) : void 0; + this._context = new Context(this.browserContext, { + config: this._config, + sessionLog: this._sessionLog, + cwd: clientInfo.cwd + }); + } + async dispose() { + await this._context?.dispose().catch((e) => debug9("pw:tools:error")(e)); + } + async callTool(name, rawArguments = {}, signal) { + const json = !!rawArguments._meta?.json; + const formatError = (message) => ({ + content: [{ type: "text", text: json ? JSON.stringify({ isError: true, error: message }, null, 2) : `### Error +${message}` }], + isError: true + }); + const tool = this._tools.find((tool2) => tool2.schema.name === name); + if (!tool) + return formatError(`Tool "${name}" not found`); + const parsedArguments = tool.schema.inputSchema.parse(rawArguments); + const cwd = rawArguments._meta?.cwd; + const raw = !!rawArguments._meta?.raw; + const context2 = this._context; + const response2 = new Response4(context2, name, parsedArguments, { relativeTo: cwd, raw, json }); + context2.setRunningTool(name); + let responseObject; + try { + await tool.handle(context2, parsedArguments, response2, signal); + for (const reason of context2.drainPendingUnhandledRejections()) + response2.addError(formatRejectionReason(reason)); + responseObject = await response2.serialize(); + this._sessionLog?.logResponse(name, parsedArguments, responseObject); + } catch (error) { + const messages = [String(error), ...context2.drainPendingUnhandledRejections().map(formatRejectionReason)]; + responseObject = formatError(messages.join("\n\n")); + } finally { + context2.setRunningTool(void 0); + } + if (this._disconnected) + responseObject.isClose = true; + return responseObject; + } + }; + } +}); + +// packages/playwright-core/src/tools/backend/common.ts +var z5, close, resize, common_default; +var init_common = __esm({ + "packages/playwright-core/src/tools/backend/common.ts"() { + "use strict"; + init_tool(); + init_response(); + z5 = require("./utilsBundle").z; + close = defineTool({ + capability: "core", + schema: { + name: "browser_close", + title: "Close browser", + description: "Close the page", + inputSchema: z5.object({}), + type: "action" + }, + handle: async (context2, params2, response2) => { + const result2 = renderTabsMarkdown([]); + response2.addTextResult(result2.join("\n")); + response2.addCode(`await page.close()`); + response2.setClose(); + } + }); + resize = defineTabTool({ + capability: "core", + schema: { + name: "browser_resize", + title: "Resize browser window", + description: "Resize the browser window", + inputSchema: z5.object({ + width: z5.number().describe("Width of the browser window"), + height: z5.number().describe("Height of the browser window") + }), + type: "action" + }, + handle: async (tab2, params2, response2) => { + response2.addCode(`await page.setViewportSize({ width: ${params2.width}, height: ${params2.height} });`); + await tab2.page.setViewportSize({ width: params2.width, height: params2.height }); + } + }); + common_default = [ + close, + resize + ]; + } +}); + +// packages/playwright-core/src/tools/backend/config.ts +var z6, configShow, config_default; +var init_config = __esm({ + "packages/playwright-core/src/tools/backend/config.ts"() { + "use strict"; + init_tool(); + z6 = require("./utilsBundle").z; + configShow = defineTool({ + capability: "config", + schema: { + name: "browser_get_config", + title: "Get config", + description: "Get the final resolved config after merging CLI options, environment variables and config file.", + inputSchema: z6.object({}), + type: "readOnly" + }, + handle: async (context2, params2, response2) => { + response2.addTextResult(JSON.stringify(context2.config, null, 2)); + } + }); + config_default = [ + configShow + ]; + } +}); + +// packages/playwright-core/src/tools/backend/console.ts +var z7, console2, consoleClear, console_default; +var init_console2 = __esm({ + "packages/playwright-core/src/tools/backend/console.ts"() { + "use strict"; + init_tool(); + z7 = require("./utilsBundle").z; + console2 = defineTabTool({ + capability: "core", + schema: { + name: "browser_console_messages", + title: "Get console messages", + description: "Returns all console messages", + inputSchema: z7.object({ + level: z7.enum(["error", "warning", "info", "debug"]).default("info").describe('Level of the console messages to return. Each level includes the messages of more severe levels. Defaults to "info".'), + all: z7.boolean().optional().describe("Return all console messages since the beginning of the session, not just since the last navigation. Defaults to false."), + filename: z7.string().optional().describe("Filename to save the console messages to. If not provided, messages are returned as text.") + }), + type: "readOnly" + }, + handle: async (tab2, params2, response2) => { + const count = await tab2.consoleMessageCount(); + const header = [`Total messages: ${count.total} (Errors: ${count.errors}, Warnings: ${count.warnings})`]; + const messages = await tab2.consoleMessages(params2.level, params2.all); + if (messages.length !== count.total) + header.push(`Returning ${messages.length} messages for level "${params2.level}"`); + const text2 = [...header, "", ...messages.map((message) => message.toString())].join("\n"); + await response2.addResult("Console", text2, { prefix: "console", ext: "log", suggestedFilename: params2.filename }); + } + }); + consoleClear = defineTabTool({ + capability: "core", + skillOnly: true, + schema: { + name: "browser_console_clear", + title: "Clear console messages", + description: "Clear all console messages", + inputSchema: z7.object({}), + type: "readOnly" + }, + handle: async (tab2) => { + await tab2.clearConsoleMessages(); + } + }); + console_default = [ + console2, + consoleClear + ]; + } +}); + +// packages/playwright-core/src/tools/backend/cookies.ts +var z8, cookieList, cookieGet, cookieSet, cookieDelete, cookieClear, cookies_default; +var init_cookies = __esm({ + "packages/playwright-core/src/tools/backend/cookies.ts"() { + "use strict"; + init_tool(); + z8 = require("./utilsBundle").z; + cookieList = defineTool({ + capability: "storage", + schema: { + name: "browser_cookie_list", + title: "List cookies", + description: "List all cookies (optionally filtered by domain/path)", + inputSchema: z8.object({ + domain: z8.string().optional().describe("Filter cookies by domain"), + path: z8.string().optional().describe("Filter cookies by path") + }), + type: "readOnly" + }, + handle: async (context2, params2, response2) => { + const browserContext = await context2.ensureBrowserContext(); + let cookies = await browserContext.cookies(); + if (params2.domain) + cookies = cookies.filter((c) => c.domain.includes(params2.domain)); + if (params2.path) + cookies = cookies.filter((c) => c.path.startsWith(params2.path)); + if (cookies.length === 0) + response2.addTextResult("No cookies found"); + else + response2.addTextResult(cookies.map((c) => `${c.name}=${c.value} (domain: ${c.domain}, path: ${c.path})`).join("\n")); + response2.addCode(`await page.context().cookies();`); + } + }); + cookieGet = defineTool({ + capability: "storage", + schema: { + name: "browser_cookie_get", + title: "Get cookie", + description: "Get a specific cookie by name", + inputSchema: z8.object({ + name: z8.string().describe("Cookie name to get") + }), + type: "readOnly" + }, + handle: async (context2, params2, response2) => { + const browserContext = await context2.ensureBrowserContext(); + const cookies = await browserContext.cookies(); + const cookie = cookies.find((c) => c.name === params2.name); + if (!cookie) + response2.addTextResult(`Cookie '${params2.name}' not found`); + else + response2.addTextResult(`${cookie.name}=${cookie.value} (domain: ${cookie.domain}, path: ${cookie.path}, httpOnly: ${cookie.httpOnly}, secure: ${cookie.secure}, sameSite: ${cookie.sameSite})`); + response2.addCode(`await page.context().cookies();`); + } + }); + cookieSet = defineTool({ + capability: "storage", + schema: { + name: "browser_cookie_set", + title: "Set cookie", + description: "Set a cookie with optional flags (domain, path, expires, httpOnly, secure, sameSite)", + inputSchema: z8.object({ + name: z8.string().describe("Cookie name"), + value: z8.string().describe("Cookie value"), + domain: z8.string().optional().describe("Cookie domain"), + path: z8.string().optional().describe("Cookie path"), + expires: z8.number().optional().describe("Cookie expiration as Unix timestamp"), + httpOnly: z8.boolean().optional().describe("Whether the cookie is HTTP only"), + secure: z8.boolean().optional().describe("Whether the cookie is secure"), + sameSite: z8.enum(["Strict", "Lax", "None"]).optional().describe("Cookie SameSite attribute") + }), + type: "action" + }, + handle: async (context2, params2, response2) => { + const browserContext = await context2.ensureBrowserContext(); + const tab2 = await context2.ensureTab(); + const url2 = new URL(tab2.page.url()); + const cookie = { + name: params2.name, + value: params2.value, + domain: params2.domain || url2.hostname, + path: params2.path || "/" + }; + if (params2.expires !== void 0) + cookie.expires = params2.expires; + if (params2.httpOnly !== void 0) + cookie.httpOnly = params2.httpOnly; + if (params2.secure !== void 0) + cookie.secure = params2.secure; + if (params2.sameSite !== void 0) + cookie.sameSite = params2.sameSite; + await browserContext.addCookies([cookie]); + response2.addCode(`await page.context().addCookies([${JSON.stringify(cookie)}]);`); + } + }); + cookieDelete = defineTool({ + capability: "storage", + schema: { + name: "browser_cookie_delete", + title: "Delete cookie", + description: "Delete a specific cookie", + inputSchema: z8.object({ + name: z8.string().describe("Cookie name to delete") + }), + type: "action" + }, + handle: async (context2, params2, response2) => { + const browserContext = await context2.ensureBrowserContext(); + await browserContext.clearCookies({ name: params2.name }); + response2.addCode(`await page.context().clearCookies({ name: '${params2.name}' });`); + } + }); + cookieClear = defineTool({ + capability: "storage", + schema: { + name: "browser_cookie_clear", + title: "Clear cookies", + description: "Clear all cookies", + inputSchema: z8.object({}), + type: "action" + }, + handle: async (context2, params2, response2) => { + const browserContext = await context2.ensureBrowserContext(); + await browserContext.clearCookies(); + response2.addCode(`await page.context().clearCookies();`); + } + }); + cookies_default = [ + cookieList, + cookieGet, + cookieSet, + cookieDelete, + cookieClear + ]; + } +}); + +// packages/playwright-core/src/tools/backend/devtools.ts +var import_child_process3, z9, resume, highlight, hideHighlight, annotate, devtools_default; +var init_devtools = __esm({ + "packages/playwright-core/src/tools/backend/devtools.ts"() { + "use strict"; + import_child_process3 = require("child_process"); + init_package(); + init_tool(); + init_snapshot(); + z9 = require("./utilsBundle").z; + resume = defineTool({ + capability: "devtools", + schema: { + name: "browser_resume", + title: "Resume paused script execution", + description: "Resume script execution after it was paused. When called with step set to true, execution will pause again before the next action.", + inputSchema: z9.object({ + step: z9.boolean().optional().describe("When true, execution will pause again before the next action, allowing step-by-step debugging."), + location: z9.string().optional().describe('Pause execution at a specific :, e.g. "example.spec.ts:42".') + }), + type: "action" + }, + handle: async (context2, params2, response2) => { + const browserContext = await context2.ensureBrowserContext(); + const pausedPromise = new Promise((resolve) => { + const listener = () => { + if (browserContext.debugger.pausedDetails()) { + browserContext.debugger.off("pausedstatechanged", listener); + resolve(); + } + }; + browserContext.debugger.on("pausedstatechanged", listener); + }); + if (params2.location) { + const [file, lineStr] = params2.location.split(":"); + let location2; + if (lineStr) { + const line = Number(lineStr); + if (isNaN(line)) + throw new Error(`Invalid location "${params2.location}", expected format is :, e.g. "example.spec.ts:42"`); + location2 = { file, line }; + } else { + location2 = { file: params2.location }; + } + await browserContext.debugger.runTo(location2); + } else if (params2.step) { + await browserContext.debugger.next(); + } else { + await browserContext.debugger.resume(); + } + await pausedPromise; + } + }); + highlight = defineTabTool({ + capability: "devtools", + schema: { + name: "browser_highlight", + title: "Highlight element", + description: "Show a persistent highlight overlay around the element on the page.", + inputSchema: elementSchema.extend({ + style: z9.string().optional().describe('Additional inline CSS applied to the highlight overlay, e.g. "outline: 2px dashed red".') + }), + type: "readOnly" + }, + handle: async (tab2, params2, response2) => { + const { locator: locator2 } = await tab2.targetLocator(params2); + await locator2.highlight({ style: params2.style }); + response2.addTextResult(`Highlighted ${locator2}`); + } + }); + hideHighlight = defineTabTool({ + capability: "devtools", + schema: { + name: "browser_hide_highlight", + title: "Hide element highlight", + description: "Remove a highlight overlay previously added for the element.", + inputSchema: optionalElementSchema.extend({ + element: z9.string().optional().describe("Human-readable element description used when adding the highlight; must match the value passed to browser_highlight.") + }), + type: "readOnly" + }, + handle: async (tab2, params2, response2) => { + if (params2.target) { + const { locator: locator2 } = await tab2.targetLocator({ target: params2.target, element: params2.element }); + await locator2.hideHighlight(); + response2.addTextResult(`Hid highlight for ${locator2}`); + } else { + await tab2.page.hideHighlight(); + response2.addTextResult(`Hid page highlight`); + } + } + }); + annotate = defineTabTool({ + capability: "devtools", + schema: { + name: "browser_annotate", + title: "Annotate the current page", + description: "Open the Playwright Dashboard in annotation mode for the current page and wait for the user to draw annotations. Returns the annotated screenshot, ARIA snapshot, and the list of annotations.", + inputSchema: z9.object({}), + type: "readOnly" + }, + handle: async (tab2, params2, response2, signal) => { + const pageId4 = tab2.page._guid; + const daemonScript = libPath("entry", "dashboardApp.js"); + const daemonArgs = [daemonScript, `--pageId=${pageId4}`]; + const daemon = (0, import_child_process3.spawn)(process.execPath, daemonArgs, { detached: true, stdio: "ignore" }); + daemon.unref(); + const client = (0, import_child_process3.spawn)(process.execPath, [...daemonArgs, "--annotate"], { + stdio: ["pipe", "pipe", "inherit"] + }); + const onAbort = () => client.kill(); + signal?.addEventListener("abort", onAbort); + const stdoutChunks = []; + client.stdout.on("data", (chunk) => stdoutChunks.push(chunk)); + const exitCode = await new Promise((resolve) => client.on("exit", (code) => resolve(code))); + signal?.removeEventListener("abort", onAbort); + if (signal?.aborted) { + response2.addTextResult("Annotation cancelled."); + return; + } + if (exitCode !== 0) { + response2.addError(`Annotation client exited with code ${exitCode}`); + return; + } + const text2 = Buffer.concat(stdoutChunks).toString("utf8").trim(); + if (!text2) { + response2.addTextResult("No annotations were submitted."); + return; + } + const { frames, feedback } = JSON.parse(text2); + if (!frames || frames.length === 0) { + response2.addTextResult("No annotations were submitted."); + return; + } + const date = /* @__PURE__ */ new Date(); + if (feedback) + response2.addTextResult(feedback); + const multi = frames.length > 1; + for (let i = 0; i < frames.length; i++) { + const frame = frames[i]; + const idx = i + 1; + const session2 = frame.sessionTitle || "session"; + const tab3 = frame.title || "tab"; + response2.addTextResult(`${multi ? `## Screenshot ${idx} +` : ""}${session2} / ${tab3} @ ${frame.url} (${frame.viewportWidth}x${frame.viewportHeight})`); + for (const a of frame.annotations) + response2.addTextResult(` { x: ${a.x}, y: ${a.y}, width: ${a.width}, height: ${a.height} }: ${a.text}`); + if (frame.data) + await response2.addResult(`Annotation image${multi ? " " + idx : ""}`, Buffer.from(frame.data, "base64"), { prefix: `annotations${multi ? "-" + idx : ""}`, ext: "png", date }); + if (frame.ariaSnapshot) + await response2.addResult(`Annotation snapshot${multi ? " " + idx : ""}`, Buffer.from(frame.ariaSnapshot, "utf8"), { prefix: `annotations${multi ? "-" + idx : ""}`, ext: "yaml", date }); + } + } + }); + devtools_default = [resume, highlight, hideHighlight, annotate]; + } +}); + +// packages/playwright-core/src/tools/backend/evaluate.ts +var z10, evaluateSchema, evaluate2, evaluate_default; +var init_evaluate = __esm({ + "packages/playwright-core/src/tools/backend/evaluate.ts"() { + "use strict"; + init_stringUtils(); + init_tool(); + init_snapshot(); + z10 = require("./utilsBundle").z; + evaluateSchema = optionalElementSchema.extend({ + function: z10.string().describe("() => { /* code */ } or (element) => { /* code */ } when element is provided"), + filename: z10.string().optional().describe("Filename to save the result to. If not provided, result is returned as text.") + }); + evaluate2 = defineTabTool({ + capability: "core", + schema: { + name: "browser_evaluate", + title: "Evaluate JavaScript", + description: "Evaluate JavaScript expression on page or element", + inputSchema: evaluateSchema, + type: "action" + }, + handle: async (tab, params, response) => { + let locator; + const expression = params.function; + if (params.target) + locator = await tab.targetLocator({ target: params.target, element: params.element || "element" }); + await tab.waitForCompletion(async () => { + let evalResult; + if (locator?.locator) { + evalResult = await locator.locator.evaluate(async (element, expr) => { + const value = eval(`(${expr})`); + const isFunction = typeof value === "function"; + const result = await (isFunction ? value(element) : value); + return { result, isFunction }; + }, expression); + } else { + evalResult = await tab.page.evaluate(async (expr) => { + const value = eval(`(${expr})`); + const isFunction = typeof value === "function"; + const result = await (isFunction ? value() : value); + return { result, isFunction }; + }, expression); + } + const codeExpression = evalResult.isFunction ? expression : `() => (${expression})`; + if (locator) + response.addCode(`await page.${locator.resolved}.evaluate(${escapeWithQuotes(codeExpression)});`); + else + response.addCode(`await page.evaluate(${escapeWithQuotes(codeExpression)});`); + const text = JSON.stringify(evalResult.result, null, 2) ?? "undefined"; + await response.addResult("Evaluation result", text, { prefix: "result", ext: "json", suggestedFilename: params.filename }); + }).catch((e) => { + response.addError(e instanceof Error ? e.message : String(e)); + }); + } + }); + evaluate_default = [ + evaluate2 + ]; + } +}); + +// packages/playwright-core/src/tools/backend/form.ts +var z11, fillForm, form_default; +var init_form = __esm({ + "packages/playwright-core/src/tools/backend/form.ts"() { + "use strict"; + init_stringUtils(); + init_tool(); + init_snapshot(); + z11 = require("./utilsBundle").z; + fillForm = defineTabTool({ + capability: "core", + schema: { + name: "browser_fill_form", + title: "Fill form", + description: "Fill multiple form fields", + inputSchema: z11.object({ + fields: z11.array(elementSchema.extend({ + name: z11.string().describe("Human-readable field name"), + type: z11.enum(["textbox", "checkbox", "radio", "combobox", "slider"]).describe("Type of the field"), + value: z11.string().describe("Value to fill in the field. If the field is a checkbox, the value should be `true` or `false`. If the field is a combobox, the value should be the text of the option.") + })).describe("Fields to fill in") + }), + type: "input" + }, + handle: async (tab2, params2, response2) => { + for (const field of params2.fields) { + const { locator: locator2, resolved } = await tab2.targetLocator({ element: field.name, target: field.target }); + const locatorSource = `await page.${resolved}`; + if (field.type === "textbox" || field.type === "slider") { + const secret = tab2.context.lookupSecret(field.value); + await locator2.fill(secret.value, tab2.actionTimeoutOptions); + response2.addCode(`${locatorSource}.fill(${secret.code});`); + } else if (field.type === "checkbox" || field.type === "radio") { + await locator2.setChecked(field.value === "true", tab2.actionTimeoutOptions); + response2.addCode(`${locatorSource}.setChecked(${field.value});`); + } else if (field.type === "combobox") { + await locator2.selectOption({ label: field.value }, tab2.actionTimeoutOptions); + response2.addCode(`${locatorSource}.selectOption(${escapeWithQuotes(field.value)});`); + } + } + } + }); + form_default = [ + fillForm + ]; + } +}); + +// packages/playwright-core/src/tools/backend/keyboard.ts +var z12, press, pressSequentially, typeSchema, type, keydown, keyup, keyboard_default; +var init_keyboard = __esm({ + "packages/playwright-core/src/tools/backend/keyboard.ts"() { + "use strict"; + init_tool(); + init_snapshot(); + z12 = require("./utilsBundle").z; + press = defineTabTool({ + capability: "core-input", + schema: { + name: "browser_press_key", + title: "Press a key", + description: "Press a key on the keyboard", + inputSchema: z12.object({ + key: z12.string().describe("Name of the key to press or a character to generate, such as `ArrowLeft` or `a`") + }), + type: "input" + }, + handle: async (tab2, params2, response2) => { + response2.addCode(`// Press ${params2.key}`); + response2.addCode(`await page.keyboard.press('${params2.key}');`); + if (params2.key === "Enter") { + response2.setIncludeSnapshot(); + await tab2.waitForCompletion(async () => { + await tab2.page.keyboard.press("Enter"); + }); + } else { + await tab2.page.keyboard.press(params2.key); + } + } + }); + pressSequentially = defineTabTool({ + capability: "core-input", + skillOnly: true, + schema: { + name: "browser_press_sequentially", + title: "Type text key by key", + description: "Type text key by key on the keyboard", + inputSchema: z12.object({ + text: z12.string().describe("Text to type"), + submit: z12.boolean().optional().describe("Whether to submit entered text (press Enter after)") + }), + type: "input" + }, + handle: async (tab2, params2, response2) => { + response2.addCode(`// Press ${params2.text}`); + response2.addCode(`await page.keyboard.type('${params2.text}');`); + await tab2.page.keyboard.type(params2.text); + if (params2.submit) { + response2.addCode(`await page.keyboard.press('Enter');`); + response2.setIncludeSnapshot(); + await tab2.waitForCompletion(async () => { + await tab2.page.keyboard.press("Enter"); + }); + } + } + }); + typeSchema = elementSchema.extend({ + text: z12.string().describe("Text to type into the element"), + submit: z12.boolean().optional().describe("Whether to submit entered text (press Enter after)"), + slowly: z12.boolean().optional().describe("Whether to type one character at a time. Useful for triggering key handlers in the page. By default entire text is filled in at once.") + }); + type = defineTabTool({ + capability: "core-input", + schema: { + name: "browser_type", + title: "Type text", + description: "Type text into editable element", + inputSchema: typeSchema, + type: "input" + }, + handle: async (tab2, params2, response2) => { + const { locator: locator2, resolved } = await tab2.targetLocator(params2); + const secret = tab2.context.lookupSecret(params2.text); + const action = async () => { + if (params2.slowly) { + response2.setIncludeSnapshot(); + response2.addCode(`await page.${resolved}.pressSequentially(${secret.code});`); + await locator2.pressSequentially(secret.value, tab2.actionTimeoutOptions); + } else { + response2.addCode(`await page.${resolved}.fill(${secret.code});`); + await locator2.fill(secret.value, tab2.actionTimeoutOptions); + } + if (params2.submit) { + response2.setIncludeSnapshot(); + response2.addCode(`await page.${resolved}.press('Enter');`); + await locator2.press("Enter", tab2.actionTimeoutOptions); + } + }; + if (params2.submit || params2.slowly) + await tab2.waitForCompletion(action); + else + await action(); + } + }); + keydown = defineTabTool({ + capability: "core-input", + skillOnly: true, + schema: { + name: "browser_keydown", + title: "Press a key down", + description: "Press a key down on the keyboard", + inputSchema: z12.object({ + key: z12.string().describe("Name of the key to press or a character to generate, such as `ArrowLeft` or `a`") + }), + type: "input" + }, + handle: async (tab2, params2, response2) => { + response2.addCode(`await page.keyboard.down('${params2.key}');`); + await tab2.page.keyboard.down(params2.key); + } + }); + keyup = defineTabTool({ + capability: "core-input", + skillOnly: true, + schema: { + name: "browser_keyup", + title: "Press a key up", + description: "Press a key up on the keyboard", + inputSchema: z12.object({ + key: z12.string().describe("Name of the key to press or a character to generate, such as `ArrowLeft` or `a`") + }), + type: "input" + }, + handle: async (tab2, params2, response2) => { + response2.addCode(`await page.keyboard.up('${params2.key}');`); + await tab2.page.keyboard.up(params2.key); + } + }); + keyboard_default = [ + press, + type, + pressSequentially, + keydown, + keyup + ]; + } +}); + +// packages/playwright-core/src/tools/backend/mouse.ts +var z13, mouseMove, mouseDown, mouseUp, mouseWheel, mouseClick, mouseDrag, mouse_default; +var init_mouse = __esm({ + "packages/playwright-core/src/tools/backend/mouse.ts"() { + "use strict"; + init_stringUtils(); + init_tool(); + z13 = require("./utilsBundle").z; + mouseMove = defineTabTool({ + capability: "vision", + schema: { + name: "browser_mouse_move_xy", + title: "Move mouse", + description: "Move mouse to a given position", + inputSchema: z13.object({ + x: z13.number().describe("X coordinate"), + y: z13.number().describe("Y coordinate") + }), + type: "input" + }, + handle: async (tab2, params2, response2) => { + response2.addCode(`// Move mouse to (${params2.x}, ${params2.y})`); + response2.addCode(`await page.mouse.move(${params2.x}, ${params2.y});`); + await tab2.page.mouse.move(params2.x, params2.y); + } + }); + mouseDown = defineTabTool({ + capability: "vision", + schema: { + name: "browser_mouse_down", + title: "Press mouse down", + description: "Press mouse down", + inputSchema: z13.object({ + button: z13.enum(["left", "right", "middle"]).optional().describe("Button to press, defaults to left") + }), + type: "input" + }, + handle: async (tab2, params2, response2) => { + const options2 = { button: params2.button }; + const optionsArg = formatObjectOrVoid(options2); + response2.addCode(`// Press mouse down`); + response2.addCode(`await page.mouse.down(${optionsArg});`); + await tab2.page.mouse.down(options2); + } + }); + mouseUp = defineTabTool({ + capability: "vision", + schema: { + name: "browser_mouse_up", + title: "Press mouse up", + description: "Press mouse up", + inputSchema: z13.object({ + button: z13.enum(["left", "right", "middle"]).optional().describe("Button to press, defaults to left") + }), + type: "input" + }, + handle: async (tab2, params2, response2) => { + const options2 = { button: params2.button }; + const optionsArg = formatObjectOrVoid(options2); + response2.addCode(`// Press mouse up`); + response2.addCode(`await page.mouse.up(${optionsArg});`); + await tab2.page.mouse.up(options2); + } + }); + mouseWheel = defineTabTool({ + capability: "vision", + schema: { + name: "browser_mouse_wheel", + title: "Scroll mouse wheel", + description: "Scroll mouse wheel", + inputSchema: z13.object({ + deltaX: z13.number().default(0).describe("X delta"), + deltaY: z13.number().default(0).describe("Y delta") + }), + type: "input" + }, + handle: async (tab2, params2, response2) => { + response2.addCode(`// Scroll mouse wheel`); + response2.addCode(`await page.mouse.wheel(${params2.deltaX}, ${params2.deltaY});`); + await tab2.page.mouse.wheel(params2.deltaX, params2.deltaY); + } + }); + mouseClick = defineTabTool({ + capability: "vision", + schema: { + name: "browser_mouse_click_xy", + title: "Click", + description: "Click mouse button at a given position", + inputSchema: z13.object({ + x: z13.number().describe("X coordinate"), + y: z13.number().describe("Y coordinate"), + button: z13.enum(["left", "right", "middle"]).optional().describe("Button to click, defaults to left"), + clickCount: z13.number().optional().describe("Number of clicks, defaults to 1"), + delay: z13.number().optional().describe("Time to wait between mouse down and mouse up in milliseconds, defaults to 0") + }), + type: "input" + }, + handle: async (tab2, params2, response2) => { + response2.setIncludeSnapshot(); + const options2 = { + button: params2.button, + clickCount: params2.clickCount, + delay: params2.delay + }; + const formatted = formatObjectOrVoid(options2); + const optionsArg = formatted ? `, ${formatted}` : ""; + response2.addCode(`// Click mouse at coordinates (${params2.x}, ${params2.y})`); + response2.addCode(`await page.mouse.click(${params2.x}, ${params2.y}${optionsArg});`); + await tab2.waitForCompletion(async () => { + await tab2.page.mouse.click(params2.x, params2.y, options2); + }); + } + }); + mouseDrag = defineTabTool({ + capability: "vision", + schema: { + name: "browser_mouse_drag_xy", + title: "Drag mouse", + description: "Drag left mouse button to a given position", + inputSchema: z13.object({ + startX: z13.number().describe("Start X coordinate"), + startY: z13.number().describe("Start Y coordinate"), + endX: z13.number().describe("End X coordinate"), + endY: z13.number().describe("End Y coordinate") + }), + type: "input" + }, + handle: async (tab2, params2, response2) => { + response2.setIncludeSnapshot(); + response2.addCode(`// Drag mouse from (${params2.startX}, ${params2.startY}) to (${params2.endX}, ${params2.endY})`); + response2.addCode(`await page.mouse.move(${params2.startX}, ${params2.startY});`); + response2.addCode(`await page.mouse.down();`); + response2.addCode(`await page.mouse.move(${params2.endX}, ${params2.endY});`); + response2.addCode(`await page.mouse.up();`); + await tab2.waitForCompletion(async () => { + await tab2.page.mouse.move(params2.startX, params2.startY); + await tab2.page.mouse.down(); + await tab2.page.mouse.move(params2.endX, params2.endY); + await tab2.page.mouse.up(); + }); + } + }); + mouse_default = [ + mouseMove, + mouseClick, + mouseDrag, + mouseDown, + mouseUp, + mouseWheel + ]; + } +}); + +// packages/playwright-core/src/tools/backend/navigate.ts +var z14, navigate, goBack, goForward, reload, navigate_default; +var init_navigate = __esm({ + "packages/playwright-core/src/tools/backend/navigate.ts"() { + "use strict"; + init_tool(); + z14 = require("./utilsBundle").z; + navigate = defineTool({ + capability: "core-navigation", + schema: { + name: "browser_navigate", + title: "Navigate to a URL", + description: "Navigate to a URL", + inputSchema: z14.object({ + url: z14.string().describe("The URL to navigate to") + }), + type: "action" + }, + handle: async (context2, params2, response2) => { + const tab2 = await context2.ensureTab(); + const url2 = await tab2.checkUrlAndNavigate(params2.url); + response2.setIncludeSnapshot(); + response2.addCode(`await page.goto('${url2}');`); + } + }); + goBack = defineTabTool({ + capability: "core-navigation", + schema: { + name: "browser_navigate_back", + title: "Go back", + description: "Go back to the previous page in the history", + inputSchema: z14.object({}), + type: "action" + }, + handle: async (tab2, params2, response2) => { + await tab2.page.goBack(tab2.navigationTimeoutOptions); + response2.setIncludeSnapshot(); + response2.addCode(`await page.goBack();`); + } + }); + goForward = defineTabTool({ + capability: "core-navigation", + skillOnly: true, + schema: { + name: "browser_navigate_forward", + title: "Go forward", + description: "Go forward to the next page in the history", + inputSchema: z14.object({}), + type: "action" + }, + handle: async (tab2, params2, response2) => { + await tab2.page.goForward(tab2.navigationTimeoutOptions); + response2.setIncludeSnapshot(); + response2.addCode(`await page.goForward();`); + } + }); + reload = defineTabTool({ + capability: "core-navigation", + skillOnly: true, + schema: { + name: "browser_reload", + title: "Reload the page", + description: "Reload the current page", + inputSchema: z14.object({}), + type: "action" + }, + handle: async (tab2, params2, response2) => { + await tab2.page.reload(tab2.navigationTimeoutOptions); + response2.setIncludeSnapshot(); + response2.addCode(`await page.reload();`); + } + }); + navigate_default = [ + navigate, + goBack, + goForward, + reload + ]; + } +}); + +// packages/playwright-core/src/tools/backend/network.ts +function isSuccessfulResponse(request2) { + if (request2.failure()) + return false; + const response2 = request2.existingResponse(); + return !!response2 && response2.status() < 400; +} +function isFetch(request2) { + return ["fetch", "xhr"].includes(request2.resourceType()); +} +function renderRequestLine(request2) { + const response2 = request2.existingResponse(); + let line = `[${request2.method().toUpperCase()}] ${request2.url()}`; + if (response2) + line += ` => [${response2.status()}] ${response2.statusText()}`; + else if (request2.failure()) + line += ` => [FAILED] ${request2.failure()?.errorText ?? "Unknown error"}`; + return line; +} +function renderRequestDetails(index, request2, skillMode) { + const httpResponse = request2.existingResponse(); + const responseHeaders = httpResponse?.headers(); + const lines = []; + lines.push(`#${index} [${request2.method().toUpperCase()}] ${request2.url()}`); + lines.push(""); + lines.push(" General"); + if (httpResponse) + lines.push(` status: [${httpResponse.status()}] ${httpResponse.statusText()}`); + else if (request2.failure()) + lines.push(` status: [FAILED] ${request2.failure()?.errorText ?? "Unknown error"}`); + const duration = computeDurationMs(request2); + if (duration !== void 0) + lines.push(` duration: ${duration}ms`); + lines.push(` type: ${request2.resourceType()}`); + const contentType = responseHeaders?.["content-type"]; + if (contentType) + lines.push(` mimeType: ${contentType.split(";")[0].trim()}`); + appendHeaderSection(lines, "Request headers", request2.headers()); + if (responseHeaders) + appendHeaderSection(lines, "Response headers", responseHeaders); + const hints = []; + if (request2.postData()) + hints.push(partHint(skillMode, "request-body", index)); + if (canHaveResponseBody(httpResponse)) + hints.push(partHint(skillMode, "response-body", index)); + if (hints.length) + lines.push("", ...hints); + return lines.join("\n"); +} +function partHint(skillMode, part, index) { + const subject = part === "request-body" ? "request body" : "response body"; + return skillMode ? `Run \`${part} ${index}\` to read the ${subject}.` : `Call browser_network_request with part="${part}" to read the ${subject}.`; +} +function canHaveResponseBody(httpResponse) { + if (!httpResponse) + return false; + const status = httpResponse.status(); + return status !== 204 && status !== 304 && !(status >= 100 && status < 200); +} +function appendHeaderSection(lines, title, headers) { + const entries = Object.entries(headers); + if (!entries.length) + return; + lines.push(""); + lines.push(` ${title}`); + for (const [k, v] of entries) + lines.push(` ${k}: ${v}`); +} +function computeDurationMs(request2) { + const timing = request2.timing(); + if (!timing || timing.responseEnd < 0) + return void 0; + return Math.round(timing.responseEnd); +} +async function renderRequestPart(request2, part, response2, suggestedFilename) { + if (part === "request-headers") { + await response2.addResult("Request headers", renderHeaders(request2.headers()), { prefix: "request", ext: "txt", suggestedFilename }); + return; + } + if (part === "request-body") { + const data = request2.postData(); + if (data !== null) + await response2.addResult("Request body", data, { prefix: "request", ext: "txt", suggestedFilename }); + return; + } + const httpResponse = request2.existingResponse(); + if (!httpResponse) + return; + if (part === "response-headers") { + await response2.addResult("Response headers", renderHeaders(httpResponse.headers()), { prefix: "response", ext: "txt", suggestedFilename }); + return; + } + const contentType = httpResponse.headers()["content-type"]; + if (isTextualMimeType(contentType ?? "")) { + let text2; + try { + text2 = await httpResponse.text(); + } catch { + return; + } + await response2.addResult("Response body", text2, { prefix: "response", ext: "txt", suggestedFilename }); + return; + } + const path59 = await saveResponseBody(request2, response2, suggestedFilename); + if (path59 !== void 0) + response2.addTextResult(path59); +} +function renderHeaders(headers) { + return Object.entries(headers).map(([k, v]) => `${k}: ${v}`).join("\n"); +} +async function saveResponseBody(request2, response2, suggestedFilename) { + const httpResponse = request2.existingResponse(); + if (!canHaveResponseBody(httpResponse)) + return void 0; + let body; + try { + body = await httpResponse.body(); + } catch { + return void 0; + } + if (!body.length) + return void 0; + const ext = getExtensionForMimeType(httpResponse.headers()["content-type"]); + const resolved = await response2.resolveClientFile({ prefix: "response", ext, suggestedFilename }, "Response body"); + await import_fs45.default.promises.writeFile(resolved.fileName, body); + return resolved.relativeName; +} +var import_fs45, z15, requests, REQUEST_PARTS, request, networkClear, networkStateSet, network_default; +var init_network4 = __esm({ + "packages/playwright-core/src/tools/backend/network.ts"() { + "use strict"; + import_fs45 = __toESM(require("fs")); + init_mimeType(); + init_tool(); + z15 = require("./utilsBundle").z; + requests = defineTabTool({ + capability: "core", + schema: { + name: "browser_network_requests", + title: "List network requests", + description: "Returns a numbered list of network requests since loading the page. Use browser_network_request with the number to get full details.", + inputSchema: z15.object({ + static: z15.boolean().default(false).describe("Whether to include successful static resources like images, fonts, scripts, etc. Defaults to false."), + filter: z15.string().optional().describe('Only return requests whose URL matches this regexp (e.g. "/api/.*user").'), + filename: z15.string().optional().describe("Filename to save the network requests to. If not provided, requests are returned as text.") + }), + type: "readOnly" + }, + handle: async (tab2, params2, response2) => { + const allRequests = await tab2.requests(); + const filter = params2.filter ? new RegExp(params2.filter) : void 0; + const lines = []; + let hiddenStaticCount = 0; + for (let i = 0; i < allRequests.length; i++) { + const request2 = allRequests[i]; + if (!params2.static && !isFetch(request2) && isSuccessfulResponse(request2)) { + hiddenStaticCount++; + continue; + } + if (filter) { + filter.lastIndex = 0; + if (!filter.test(request2.url())) + continue; + } + lines.push(`${i + 1}. ${renderRequestLine(request2)}`); + } + if (hiddenStaticCount > 0) { + const optionName = tab2.context.config.skillMode ? "--static" : '"static"'; + lines.push(` +Note: ${hiddenStaticCount} static request${hiddenStaticCount === 1 ? "" : "s"} not shown, run with ${optionName} option to see ${hiddenStaticCount === 1 ? "it" : "them"}.`); + } + await response2.addResult("Network", lines.join("\n"), { prefix: "network", ext: "log", suggestedFilename: params2.filename }); + } + }); + REQUEST_PARTS = ["request-headers", "request-body", "response-headers", "response-body"]; + request = defineTabTool({ + capability: "core", + schema: { + name: "browser_network_request", + title: "Show network request details", + description: "Returns full details (headers and body) of a single network request, or a single part if `part` is set. Use the number from browser_network_requests.", + inputSchema: z15.object({ + index: z15.number().int().min(1).describe("1-based index of the request, as printed by browser_network_requests."), + part: z15.enum(REQUEST_PARTS).optional().describe("Return only this part of the request. Omit to return full details."), + filename: z15.string().optional().describe("Filename to save the result to. If not provided, output is returned as text.") + }), + type: "readOnly" + }, + handle: async (tab2, params2, response2) => { + const allRequests = await tab2.requests(); + const request2 = allRequests[params2.index - 1]; + if (!request2) { + response2.addError(`Request #${params2.index} not found. Use browser_network_requests to see available indexes.`); + return; + } + if (params2.part) { + await renderRequestPart(request2, params2.part, response2, params2.filename); + return; + } + await response2.addResult("Request", renderRequestDetails(params2.index, request2, !!tab2.context.config.skillMode), { prefix: "request", ext: "log", suggestedFilename: params2.filename }); + } + }); + networkClear = defineTabTool({ + capability: "core", + skillOnly: true, + schema: { + name: "browser_network_clear", + title: "Clear network requests", + description: "Clear all network requests", + inputSchema: z15.object({}), + type: "readOnly" + }, + handle: async (tab2, params2, response2) => { + await tab2.clearRequests(); + } + }); + networkStateSet = defineTool({ + capability: "network", + schema: { + name: "browser_network_state_set", + title: "Set network state", + description: "Sets the browser network state to online or offline. When offline, all network requests will fail.", + inputSchema: z15.object({ + state: z15.enum(["online", "offline"]).describe('Set to "offline" to simulate offline mode, "online" to restore network connectivity') + }), + type: "action" + }, + handle: async (context2, params2, response2) => { + const browserContext = await context2.ensureBrowserContext(); + const offline = params2.state === "offline"; + await browserContext.setOffline(offline); + response2.addTextResult(`Network is now ${params2.state}`); + response2.addCode(`await page.context().setOffline(${offline});`); + } + }); + network_default = [ + requests, + request, + networkClear, + networkStateSet + ]; + } +}); + +// packages/playwright-core/src/tools/backend/pdf.ts +var z16, pdfSchema, pdf, pdf_default; +var init_pdf = __esm({ + "packages/playwright-core/src/tools/backend/pdf.ts"() { + "use strict"; + init_stringUtils(); + init_tool(); + z16 = require("./utilsBundle").z; + pdfSchema = z16.object({ + filename: z16.string().optional().describe("File name to save the pdf to. Defaults to `page-{timestamp}.pdf` if not specified. Prefer relative file names to stay within the output directory.") + }); + pdf = defineTabTool({ + capability: "pdf", + schema: { + name: "browser_pdf_save", + title: "Save as PDF", + description: "Save page as PDF", + inputSchema: pdfSchema, + type: "readOnly" + }, + handle: async (tab2, params2, response2) => { + const data = await tab2.page.pdf(); + const result2 = await response2.resolveClientFile({ prefix: "page", ext: "pdf", suggestedFilename: params2.filename }, "Page as pdf"); + await response2.addFileResult(result2, data); + response2.addCode(`await page.pdf(${formatObject({ path: result2.relativeName })});`); + } + }); + pdf_default = [ + pdf + ]; + } +}); + +// packages/playwright-core/src/tools/backend/route.ts +var z17, route, routeList, unroute, route_default; +var init_route = __esm({ + "packages/playwright-core/src/tools/backend/route.ts"() { + "use strict"; + init_tool(); + z17 = require("./utilsBundle").z; + route = defineTool({ + capability: "network", + schema: { + name: "browser_route", + title: "Mock network requests", + description: "Set up a route to mock network requests matching a URL pattern", + inputSchema: z17.object({ + pattern: z17.string().describe('URL pattern to match (e.g., "**/api/users", "**/*.{png,jpg}")'), + status: z17.number().optional().describe("HTTP status code to return (default: 200)"), + body: z17.string().optional().describe("Response body (text or JSON string)"), + contentType: z17.string().optional().describe('Content-Type header (e.g., "application/json", "text/html")'), + headers: z17.array(z17.string()).optional().describe('Headers to add in "Name: Value" format'), + removeHeaders: z17.string().optional().describe("Comma-separated list of header names to remove from request") + }), + type: "action" + }, + handle: async (context2, params2, response2) => { + const addHeaders = params2.headers ? Object.fromEntries(params2.headers.map((h) => { + const colonIndex = h.indexOf(":"); + return [h.substring(0, colonIndex).trim(), h.substring(colonIndex + 1).trim()]; + })) : void 0; + const removeHeaders = params2.removeHeaders ? params2.removeHeaders.split(",").map((h) => h.trim()) : void 0; + const handler = async (route2) => { + if (params2.body !== void 0 || params2.status !== void 0) { + await route2.fulfill({ + status: params2.status ?? 200, + contentType: params2.contentType, + body: params2.body + }); + return; + } + const headers = { ...route2.request().headers() }; + if (addHeaders) { + for (const [key, value2] of Object.entries(addHeaders)) + headers[key] = value2; + } + if (removeHeaders) { + for (const header of removeHeaders) + delete headers[header.toLowerCase()]; + } + await route2.continue({ headers }); + }; + const entry = { + pattern: params2.pattern, + status: params2.status, + body: params2.body, + contentType: params2.contentType, + addHeaders, + removeHeaders, + handler + }; + await context2.addRoute(entry); + response2.addTextResult(`Route added for pattern: ${params2.pattern}`); + response2.addCode(`await page.context().route('${params2.pattern}', async route => { /* route handler */ });`); + } + }); + routeList = defineTool({ + capability: "network", + schema: { + name: "browser_route_list", + title: "List network routes", + description: "List all active network routes", + inputSchema: z17.object({}), + type: "readOnly" + }, + handle: async (context2, params2, response2) => { + const routes = context2.routes(); + if (routes.length === 0) { + response2.addTextResult("No active routes"); + return; + } + const lines = []; + for (let i = 0; i < routes.length; i++) { + const route2 = routes[i]; + const details = []; + if (route2.status !== void 0) + details.push(`status=${route2.status}`); + if (route2.body !== void 0) + details.push(`body=${route2.body.length > 50 ? route2.body.substring(0, 50) + "..." : route2.body}`); + if (route2.contentType) + details.push(`contentType=${route2.contentType}`); + if (route2.addHeaders) + details.push(`addHeaders=${JSON.stringify(route2.addHeaders)}`); + if (route2.removeHeaders) + details.push(`removeHeaders=${route2.removeHeaders.join(",")}`); + const detailsStr = details.length ? ` (${details.join(", ")})` : ""; + lines.push(`${i + 1}. ${route2.pattern}${detailsStr}`); + } + response2.addTextResult(lines.join("\n")); + } + }); + unroute = defineTool({ + capability: "network", + schema: { + name: "browser_unroute", + title: "Remove network routes", + description: "Remove network routes matching a pattern (or all routes if no pattern specified)", + inputSchema: z17.object({ + pattern: z17.string().optional().describe("URL pattern to unroute (omit to remove all routes)") + }), + type: "action" + }, + handle: async (context2, params2, response2) => { + const removed = await context2.removeRoute(params2.pattern); + if (params2.pattern) + response2.addTextResult(`Removed ${removed} route(s) for pattern: ${params2.pattern}`); + else + response2.addTextResult(`Removed all ${removed} route(s)`); + } + }); + route_default = [ + route, + routeList, + unroute + ]; + } +}); + +// packages/playwright-core/src/tools/backend/runCode.ts +var import_fs46, import_vm, z18, codeSchema, runCode, runCode_default; +var init_runCode = __esm({ + "packages/playwright-core/src/tools/backend/runCode.ts"() { + "use strict"; + import_fs46 = __toESM(require("fs")); + import_vm = __toESM(require("vm")); + init_manualPromise(); + init_tool(); + z18 = require("./utilsBundle").z; + codeSchema = z18.object({ + code: z18.string().optional().describe(`A JavaScript function containing Playwright code to execute. It will be invoked with a single argument, page, which you can use for any page interaction. For example: \`async (page) => { await page.getByRole('button', { name: 'Submit' }).click(); return await page.title(); }\``), + filename: z18.string().optional().describe("Load code from the specified file. If both code and filename are provided, code will be ignored.") + }); + runCode = defineTabTool({ + capability: "core", + schema: { + name: "browser_run_code_unsafe", + title: "Run Playwright code (unsafe)", + description: "Run a Playwright code snippet. Unsafe: executes arbitrary JavaScript in the Playwright server process and is RCE-equivalent.", + inputSchema: codeSchema, + type: "action" + }, + handle: async (tab2, params2, response2) => { + let code = params2.code; + if (params2.filename) { + const resolvedPath = await response2.resolveClientFilename(params2.filename); + code = await import_fs46.default.promises.readFile(resolvedPath, "utf-8"); + } + response2.addCode(`await (${code})(page);`); + const __end__ = new ManualPromise(); + const context2 = { + page: tab2.page, + __end__ + }; + import_vm.default.createContext(context2); + const unsubscribe = tab2.context.onUnhandledRejection((reason) => { + if (!__end__.isDone()) + __end__.reject(reason instanceof Error ? reason : new Error(String(reason))); + }); + try { + await tab2.waitForCompletion(async () => { + context2.__fn__ = import_vm.default.runInContext("(" + code + ")", context2); + const snippet = "(async () => {\n try {\n const result = await __fn__(page);\n __end__.resolve(JSON.stringify(result));\n } catch (e) {\n __end__.reject(e);\n }\n})()"; + const iifePromise = import_vm.default.runInContext(snippet, context2); + await Promise.race([iifePromise, __end__]); + const result2 = await __end__; + if (typeof result2 === "string") + response2.addTextResult(result2); + }); + } finally { + unsubscribe(); + } + } + }); + runCode_default = [ + runCode + ]; + } +}); + +// packages/playwright-core/src/tools/backend/storage.ts +var z19, storageState, setStorageState, storage_default; +var init_storage = __esm({ + "packages/playwright-core/src/tools/backend/storage.ts"() { + "use strict"; + init_tool(); + z19 = require("./utilsBundle").z; + storageState = defineTool({ + capability: "storage", + schema: { + name: "browser_storage_state", + title: "Save storage state", + description: "Save storage state (cookies, local storage) to a file for later reuse", + inputSchema: z19.object({ + filename: z19.string().optional().describe("File name to save the storage state to. Defaults to `storage-state-{timestamp}.json` if not specified.") + }), + type: "readOnly" + }, + handle: async (context2, params2, response2) => { + const browserContext = await context2.ensureBrowserContext(); + const state = await browserContext.storageState(); + const serializedState = JSON.stringify(state, null, 2); + const resolvedFile = await response2.resolveClientFile({ prefix: "storage-state", ext: "json", suggestedFilename: params2.filename }, "Storage state"); + response2.addCode(`await page.context().storageState({ path: '${resolvedFile.relativeName}' });`); + await response2.addFileResult(resolvedFile, serializedState); + } + }); + setStorageState = defineTool({ + capability: "storage", + schema: { + name: "browser_set_storage_state", + title: "Restore storage state", + description: "Restore storage state (cookies, local storage) from a file. This clears existing cookies and local storage before restoring.", + inputSchema: z19.object({ + filename: z19.string().describe("Path to the storage state file to restore from") + }), + type: "action" + }, + handle: async (context2, params2, response2) => { + const browserContext = await context2.ensureBrowserContext(); + const resolvedFilename = await response2.resolveClientFilename(params2.filename); + await browserContext.setStorageState(resolvedFilename); + response2.addTextResult(`Storage state restored from ${params2.filename}`); + response2.addCode(`await page.context().setStorageState('${params2.filename}');`); + } + }); + storage_default = [ + storageState, + setStorageState + ]; + } +}); + +// packages/playwright-core/src/tools/backend/tabs.ts +var z20, browserTabs, tabs_default; +var init_tabs = __esm({ + "packages/playwright-core/src/tools/backend/tabs.ts"() { + "use strict"; + init_tool(); + init_response(); + z20 = require("./utilsBundle").z; + browserTabs = defineTool({ + capability: "core-tabs", + schema: { + name: "browser_tabs", + title: "Manage tabs", + description: "List, create, close, or select a browser tab.", + inputSchema: z20.object({ + action: z20.enum(["list", "new", "close", "select"]).describe("Operation to perform"), + index: z20.number().optional().describe("Tab index, used for close/select. If omitted for close, current tab is closed."), + url: z20.string().optional().describe("URL to navigate to in the new tab, used for new.") + }), + type: "action" + }, + handle: async (context2, params2, response2) => { + switch (params2.action) { + case "list": { + await context2.ensureTab(); + break; + } + case "new": { + const tab2 = await context2.newTab(); + if (params2.url) { + const url2 = await tab2.checkUrlAndNavigate(params2.url); + response2.setIncludeSnapshot(); + response2.addCode(`await page.goto('${url2}');`); + } + break; + } + case "close": { + await context2.closeTab(params2.index); + break; + } + case "select": { + if (params2.index === void 0) + throw new Error("Tab index is required"); + await context2.selectTab(params2.index); + break; + } + } + const tabHeaders = await Promise.all(context2.tabs().map((tab2) => tab2.headerSnapshot())); + const result2 = renderTabsMarkdown(tabHeaders); + response2.addTextResult(result2.join("\n")); + } + }); + tabs_default = [ + browserTabs + ]; + } +}); + +// packages/playwright-core/src/tools/backend/tracing.ts +var z21, tracingStart, tracingStop, tracing_default, traceLegendSymbol; +var init_tracing3 = __esm({ + "packages/playwright-core/src/tools/backend/tracing.ts"() { + "use strict"; + init_tool(); + z21 = require("./utilsBundle").z; + tracingStart = defineTool({ + capability: "devtools", + schema: { + name: "browser_start_tracing", + title: "Start tracing", + description: "Start trace recording", + inputSchema: z21.object({}), + type: "readOnly" + }, + handle: async (context2, params2, response2) => { + const browserContext = await context2.ensureBrowserContext(); + const tracesDir = await context2.outputFile({ prefix: "", suggestedFilename: `traces`, ext: "" }, { origin: "code" }); + const name = "trace-" + Date.now(); + await browserContext.tracing.start({ + name, + screenshots: true, + snapshots: true, + live: true + }); + response2.addTextResult(`Trace recording started`); + response2.addFileLink("Action log", `${tracesDir}/${name}.trace`); + response2.addFileLink("Network log", `${tracesDir}/${name}.network`); + response2.addFileLink("Resources", `${tracesDir}/resources`); + browserContext.tracing[traceLegendSymbol] = { tracesDir, name }; + } + }); + tracingStop = defineTool({ + capability: "devtools", + schema: { + name: "browser_stop_tracing", + title: "Stop tracing", + description: "Stop trace recording", + inputSchema: z21.object({}), + type: "readOnly" + }, + handle: async (context2, params2, response2) => { + const browserContext = await context2.ensureBrowserContext(); + await browserContext.tracing.stop(); + const traceLegend = browserContext.tracing[traceLegendSymbol]; + if (!traceLegend) + throw new Error("Tracing is not started"); + delete browserContext.tracing[traceLegendSymbol]; + response2.addTextResult(`Trace recording stopped.`); + response2.addFileLink("Trace", `${traceLegend.tracesDir}/${traceLegend.name}.trace`); + response2.addFileLink("Network log", `${traceLegend.tracesDir}/${traceLegend.name}.network`); + response2.addFileLink("Resources", `${traceLegend.tracesDir}/resources`); + } + }); + tracing_default = [ + tracingStart, + tracingStop + ]; + traceLegendSymbol = Symbol("tracesDir"); + } +}); + +// packages/playwright-core/src/tools/backend/verify.ts +var z22, verifyElement, verifyText, verifyList, verifyValue, verify_default; +var init_verify = __esm({ + "packages/playwright-core/src/tools/backend/verify.ts"() { + "use strict"; + init_stringUtils(); + init_tool(); + z22 = require("./utilsBundle").z; + verifyElement = defineTabTool({ + capability: "testing", + schema: { + name: "browser_verify_element_visible", + title: "Verify element visible", + description: "Verify element is visible on the page", + inputSchema: z22.object({ + role: z22.string().describe('ROLE of the element. Can be found in the snapshot like this: `- {ROLE} "Accessible Name":`'), + accessibleName: z22.string().describe('ACCESSIBLE_NAME of the element. Can be found in the snapshot like this: `- role "{ACCESSIBLE_NAME}"`') + }), + type: "assertion" + }, + handle: async (tab2, params2, response2) => { + for (const frame of tab2.page.frames()) { + const locator2 = frame.getByRole(params2.role, { name: params2.accessibleName }); + if (await locator2.count() > 0) { + const resolved = await locator2.normalize(); + response2.addCode(`await expect(page.${resolved}).toBeVisible();`); + response2.addTextResult("Done"); + return; + } + } + response2.addError(`Element with role "${params2.role}" and accessible name "${params2.accessibleName}" not found`); + } + }); + verifyText = defineTabTool({ + capability: "testing", + schema: { + name: "browser_verify_text_visible", + title: "Verify text visible", + description: `Verify text is visible on the page. Prefer ${verifyElement.schema.name} if possible.`, + inputSchema: z22.object({ + text: z22.string().describe('TEXT to verify. Can be found in the snapshot like this: `- role "Accessible Name": {TEXT}` or like this: `- text: {TEXT}`') + }), + type: "assertion" + }, + handle: async (tab2, params2, response2) => { + for (const frame of tab2.page.frames()) { + const locator2 = frame.getByText(params2.text).filter({ visible: true }); + if (await locator2.count() > 0) { + const resolved = await locator2.normalize(); + response2.addCode(`await expect(page.${resolved}).toBeVisible();`); + response2.addTextResult("Done"); + return; + } + } + response2.addError("Text not found"); + } + }); + verifyList = defineTabTool({ + capability: "testing", + schema: { + name: "browser_verify_list_visible", + title: "Verify list visible", + description: "Verify list is visible on the page", + inputSchema: z22.object({ + element: z22.string().describe("Human-readable list description"), + target: z22.string().describe("Exact target element reference that points to the list"), + items: z22.array(z22.string()).describe("Items to verify") + }), + type: "assertion" + }, + handle: async (tab2, params2, response2) => { + const { locator: locator2 } = await tab2.targetLocator(params2); + const itemTexts = []; + for (const item of params2.items) { + const itemLocator = locator2.getByText(item); + if (await itemLocator.count() === 0) { + response2.addError(`Item "${item}" not found`); + return; + } + itemTexts.push(await itemLocator.textContent(tab2.expectTimeoutOptions)); + } + const ariaSnapshot = `\` +- list: +${itemTexts.map((t) => ` - listitem: ${escapeWithQuotes(t, '"')}`).join("\n")} +\``; + response2.addCode(`await expect(page.locator('body')).toMatchAriaSnapshot(${ariaSnapshot});`); + response2.addTextResult("Done"); + } + }); + verifyValue = defineTabTool({ + capability: "testing", + schema: { + name: "browser_verify_value", + title: "Verify value", + description: "Verify element value", + inputSchema: z22.object({ + type: z22.enum(["textbox", "checkbox", "radio", "combobox", "slider"]).describe("Type of the element"), + element: z22.string().describe("Human-readable element description"), + target: z22.string().describe("Exact target element reference from the page snapshot"), + value: z22.string().describe('Value to verify. For checkbox, use "true" or "false".') + }), + type: "assertion" + }, + handle: async (tab2, params2, response2) => { + const { locator: locator2, resolved } = await tab2.targetLocator(params2); + const locatorSource = `page.${resolved}`; + if (params2.type === "textbox" || params2.type === "slider" || params2.type === "combobox") { + const value2 = await locator2.inputValue(tab2.expectTimeoutOptions); + if (value2 !== params2.value) { + response2.addError(`Expected value "${params2.value}", but got "${value2}"`); + return; + } + response2.addCode(`await expect(${locatorSource}).toHaveValue(${escapeWithQuotes(params2.value)});`); + } else if (params2.type === "checkbox" || params2.type === "radio") { + const value2 = await locator2.isChecked(tab2.expectTimeoutOptions); + if (value2 !== (params2.value === "true")) { + response2.addError(`Expected value "${params2.value}", but got "${value2}"`); + return; + } + const matcher = value2 ? "toBeChecked" : "not.toBeChecked"; + response2.addCode(`await expect(${locatorSource}).${matcher}();`); + } + response2.addTextResult("Done"); + } + }); + verify_default = [ + verifyElement, + verifyText, + verifyList, + verifyValue + ]; + } +}); + +// packages/playwright-core/src/tools/backend/video.ts +var z23, videoStart, videoStop, videoChapter, video_default; +var init_video2 = __esm({ + "packages/playwright-core/src/tools/backend/video.ts"() { + "use strict"; + init_tool(); + z23 = require("./utilsBundle").z; + videoStart = defineTool({ + capability: "devtools", + schema: { + name: "browser_start_video", + title: "Start video", + description: "Start video recording", + inputSchema: z23.object({ + filename: z23.string().optional().describe("Filename to save the video."), + size: z23.object({ + width: z23.number().describe("Video width"), + height: z23.number().describe("Video height") + }).optional().describe("Video size") + }), + type: "readOnly" + }, + handle: async (context2, params2, response2) => { + const resolvedFile = await response2.resolveClientFile({ prefix: "video", ext: "webm", suggestedFilename: params2.filename }, "Video"); + await context2.startVideoRecording(resolvedFile.fileName, { size: params2.size }); + response2.addTextResult("Video recording started."); + } + }); + videoStop = defineTool({ + capability: "devtools", + schema: { + name: "browser_stop_video", + title: "Stop video", + description: "Stop video recording", + inputSchema: z23.object({}), + type: "readOnly" + }, + handle: async (context2, params2, response2) => { + const fileNames = await context2.stopVideoRecording(); + if (!fileNames.length) { + response2.addTextResult("No videos were recorded."); + return; + } + for (const fileName of fileNames) { + const resolvedFile = await response2.resolveClientFile({ + prefix: "video", + ext: "webm", + suggestedFilename: fileName + }, "Video"); + await response2.addFileResult(resolvedFile, null); + } + } + }); + videoChapter = defineTool({ + capability: "devtools", + schema: { + name: "browser_video_chapter", + title: "Video chapter", + description: "Add a chapter marker to the video recording. Shows a full-screen chapter card with blurred backdrop.", + inputSchema: z23.object({ + title: z23.string().describe("Chapter title"), + description: z23.string().optional().describe("Chapter description"), + duration: z23.number().optional().describe("Duration in milliseconds to show the chapter card") + }), + type: "readOnly" + }, + handle: async (context2, params2, response2) => { + const tab2 = context2.currentTabOrDie(); + await tab2.page.screencast.showChapter(params2.title, { + description: params2.description, + duration: params2.duration + }); + response2.addTextResult(`Chapter '${params2.title}' added.`); + } + }); + video_default = [ + videoStart, + videoStop, + videoChapter + ]; + } +}); + +// packages/playwright-core/src/tools/backend/wait.ts +var z24, wait, wait_default; +var init_wait = __esm({ + "packages/playwright-core/src/tools/backend/wait.ts"() { + "use strict"; + init_tool(); + z24 = require("./utilsBundle").z; + wait = defineTool({ + capability: "core", + schema: { + name: "browser_wait_for", + title: "Wait for", + description: "Wait for text to appear or disappear or a specified time to pass", + inputSchema: z24.object({ + time: z24.number().optional().describe("The time to wait in seconds"), + text: z24.string().optional().describe("The text to wait for"), + textGone: z24.string().optional().describe("The text to wait for to disappear") + }), + type: "assertion" + }, + handle: async (context2, params2, response2) => { + if (!params2.text && !params2.textGone && !params2.time) + throw new Error("Either time, text or textGone must be provided"); + if (params2.time) { + response2.addCode(`await new Promise(f => setTimeout(f, ${params2.time} * 1000));`); + await new Promise((f) => setTimeout(f, Math.min(3e4, params2.time * 1e3))); + } + const tab2 = context2.currentTabOrDie(); + const locator2 = params2.text ? tab2.page.getByText(params2.text).first() : void 0; + const goneLocator = params2.textGone ? tab2.page.getByText(params2.textGone).first() : void 0; + if (goneLocator) { + response2.addCode(`await page.getByText(${JSON.stringify(params2.textGone)}).first().waitFor({ state: 'hidden' });`); + await goneLocator.waitFor({ state: "hidden" }); + } + if (locator2) { + response2.addCode(`await page.getByText(${JSON.stringify(params2.text)}).first().waitFor({ state: 'visible' });`); + await locator2.waitFor({ state: "visible" }); + } + response2.addTextResult(`Waited for ${params2.text || params2.textGone || params2.time}`); + response2.setIncludeSnapshot(); + } + }); + wait_default = [ + wait + ]; + } +}); + +// packages/playwright-core/src/tools/backend/webstorage.ts +var z25, localStorageList, localStorageGet, localStorageSet, localStorageDelete, localStorageClear, sessionStorageList, sessionStorageGet, sessionStorageSet, sessionStorageDelete, sessionStorageClear, webstorage_default; +var init_webstorage = __esm({ + "packages/playwright-core/src/tools/backend/webstorage.ts"() { + "use strict"; + init_tool(); + z25 = require("./utilsBundle").z; + localStorageList = defineTabTool({ + capability: "storage", + schema: { + name: "browser_localstorage_list", + title: "List localStorage", + description: "List all localStorage key-value pairs", + inputSchema: z25.object({}), + type: "readOnly" + }, + handle: async (tab2, params2, response2) => { + const items = await tab2.page.evaluate(() => { + const result2 = []; + for (let i = 0; i < localStorage.length; i++) { + const key = localStorage.key(i); + if (key !== null) + result2.push({ key, value: localStorage.getItem(key) || "" }); + } + return result2; + }); + if (items.length === 0) + response2.addTextResult("No localStorage items found"); + else + response2.addTextResult(items.map((item) => `${item.key}=${item.value}`).join("\n")); + response2.addCode(`await page.evaluate(() => ({ ...localStorage }));`); + } + }); + localStorageGet = defineTabTool({ + capability: "storage", + schema: { + name: "browser_localstorage_get", + title: "Get localStorage item", + description: "Get a localStorage item by key", + inputSchema: z25.object({ + key: z25.string().describe("Key to get") + }), + type: "readOnly" + }, + handle: async (tab2, params2, response2) => { + const value2 = await tab2.page.evaluate((key) => localStorage.getItem(key), params2.key); + if (value2 === null) + response2.addTextResult(`localStorage key '${params2.key}' not found`); + else + response2.addTextResult(`${params2.key}=${value2}`); + response2.addCode(`await page.evaluate(() => localStorage.getItem('${params2.key}'));`); + } + }); + localStorageSet = defineTabTool({ + capability: "storage", + schema: { + name: "browser_localstorage_set", + title: "Set localStorage item", + description: "Set a localStorage item", + inputSchema: z25.object({ + key: z25.string().describe("Key to set"), + value: z25.string().describe("Value to set") + }), + type: "action" + }, + handle: async (tab2, params2, response2) => { + await tab2.page.evaluate(({ key, value: value2 }) => localStorage.setItem(key, value2), params2); + response2.addCode(`await page.evaluate(() => localStorage.setItem('${params2.key}', '${params2.value}'));`); + } + }); + localStorageDelete = defineTabTool({ + capability: "storage", + schema: { + name: "browser_localstorage_delete", + title: "Delete localStorage item", + description: "Delete a localStorage item", + inputSchema: z25.object({ + key: z25.string().describe("Key to delete") + }), + type: "action" + }, + handle: async (tab2, params2, response2) => { + await tab2.page.evaluate((key) => localStorage.removeItem(key), params2.key); + response2.addCode(`await page.evaluate(() => localStorage.removeItem('${params2.key}'));`); + } + }); + localStorageClear = defineTabTool({ + capability: "storage", + schema: { + name: "browser_localstorage_clear", + title: "Clear localStorage", + description: "Clear all localStorage", + inputSchema: z25.object({}), + type: "action" + }, + handle: async (tab2, params2, response2) => { + await tab2.page.evaluate(() => localStorage.clear()); + response2.addCode(`await page.evaluate(() => localStorage.clear());`); + } + }); + sessionStorageList = defineTabTool({ + capability: "storage", + schema: { + name: "browser_sessionstorage_list", + title: "List sessionStorage", + description: "List all sessionStorage key-value pairs", + inputSchema: z25.object({}), + type: "readOnly" + }, + handle: async (tab2, params2, response2) => { + const items = await tab2.page.evaluate(() => { + const result2 = []; + for (let i = 0; i < sessionStorage.length; i++) { + const key = sessionStorage.key(i); + if (key !== null) + result2.push({ key, value: sessionStorage.getItem(key) || "" }); + } + return result2; + }); + if (items.length === 0) + response2.addTextResult("No sessionStorage items found"); + else + response2.addTextResult(items.map((item) => `${item.key}=${item.value}`).join("\n")); + response2.addCode(`await page.evaluate(() => ({ ...sessionStorage }));`); + } + }); + sessionStorageGet = defineTabTool({ + capability: "storage", + schema: { + name: "browser_sessionstorage_get", + title: "Get sessionStorage item", + description: "Get a sessionStorage item by key", + inputSchema: z25.object({ + key: z25.string().describe("Key to get") + }), + type: "readOnly" + }, + handle: async (tab2, params2, response2) => { + const value2 = await tab2.page.evaluate((key) => sessionStorage.getItem(key), params2.key); + if (value2 === null) + response2.addTextResult(`sessionStorage key '${params2.key}' not found`); + else + response2.addTextResult(`${params2.key}=${value2}`); + response2.addCode(`await page.evaluate(() => sessionStorage.getItem('${params2.key}'));`); + } + }); + sessionStorageSet = defineTabTool({ + capability: "storage", + schema: { + name: "browser_sessionstorage_set", + title: "Set sessionStorage item", + description: "Set a sessionStorage item", + inputSchema: z25.object({ + key: z25.string().describe("Key to set"), + value: z25.string().describe("Value to set") + }), + type: "action" + }, + handle: async (tab2, params2, response2) => { + await tab2.page.evaluate(({ key, value: value2 }) => sessionStorage.setItem(key, value2), params2); + response2.addCode(`await page.evaluate(() => sessionStorage.setItem('${params2.key}', '${params2.value}'));`); + } + }); + sessionStorageDelete = defineTabTool({ + capability: "storage", + schema: { + name: "browser_sessionstorage_delete", + title: "Delete sessionStorage item", + description: "Delete a sessionStorage item", + inputSchema: z25.object({ + key: z25.string().describe("Key to delete") + }), + type: "action" + }, + handle: async (tab2, params2, response2) => { + await tab2.page.evaluate((key) => sessionStorage.removeItem(key), params2.key); + response2.addCode(`await page.evaluate(() => sessionStorage.removeItem('${params2.key}'));`); + } + }); + sessionStorageClear = defineTabTool({ + capability: "storage", + schema: { + name: "browser_sessionstorage_clear", + title: "Clear sessionStorage", + description: "Clear all sessionStorage", + inputSchema: z25.object({}), + type: "action" + }, + handle: async (tab2, params2, response2) => { + await tab2.page.evaluate(() => sessionStorage.clear()); + response2.addCode(`await page.evaluate(() => sessionStorage.clear());`); + } + }); + webstorage_default = [ + localStorageList, + localStorageGet, + localStorageSet, + localStorageDelete, + localStorageClear, + sessionStorageList, + sessionStorageGet, + sessionStorageSet, + sessionStorageDelete, + sessionStorageClear + ]; + } +}); + +// packages/playwright-core/src/tools/backend/tools.ts +function filteredTools(config) { + return browserTools.filter((tool) => tool.capability.startsWith("core") || config.capabilities?.includes(tool.capability)).filter((tool) => !tool.skillOnly).map((tool) => ({ + ...tool, + schema: { + ...tool.schema, + // Note: we first ensure that "selector" property is present, so that we can omit() it without an error. + inputSchema: tool.schema.inputSchema.extend({ selector: z26.string(), startSelector: z26.string(), endSelector: z26.string() }).omit({ selector: true, startSelector: true, endSelector: true }) + } + })); +} +var z26, browserTools; +var init_tools = __esm({ + "packages/playwright-core/src/tools/backend/tools.ts"() { + "use strict"; + init_common(); + init_config(); + init_console2(); + init_cookies(); + init_devtools(); + init_dialogs(); + init_evaluate(); + init_files(); + init_form(); + init_keyboard(); + init_mouse(); + init_navigate(); + init_network4(); + init_pdf(); + init_route(); + init_runCode(); + init_snapshot(); + init_screenshot(); + init_storage(); + init_tabs(); + init_tracing3(); + init_verify(); + init_video2(); + init_wait(); + init_webstorage(); + z26 = require("./utilsBundle").z; + browserTools = [ + ...common_default, + ...config_default, + ...console_default, + ...cookies_default, + ...devtools_default, + ...dialogs_default, + ...evaluate_default, + ...files_default, + ...form_default, + ...keyboard_default, + ...mouse_default, + ...navigate_default, + ...network_default, + ...pdf_default, + ...route_default, + ...runCode_default, + ...screenshot_default, + ...snapshot_default, + ...storage_default, + ...tabs_default, + ...tracing_default, + ...verify_default, + ...video_default, + ...wait_default, + ...webstorage_default + ]; + } +}); + +// packages/playwright-core/src/tools/cli-daemon/command.ts +function declareCommand(command) { + return command; +} +function parseCommand(command, args) { + const optionsObject = { ...args }; + delete optionsObject["_"]; + const optionsSchema = (command.options ?? kEmptyOptions).strict(); + const options2 = zodParse(optionsSchema, optionsObject, "option"); + const argsSchema = (command.args ?? kEmptyArgs).strict(); + const argNames = [...Object.keys(argsSchema.shape)]; + const argv = args["_"].slice(1); + if (argv.length > argNames.length) + throw new Error(`error: too many arguments: expected ${argNames.length}, received ${argv.length}`); + const argsObject = {}; + argNames.forEach((name, index) => argsObject[name] = argv[index]); + const parsedArgsObject = zodParse(argsSchema, argsObject, "argument"); + const toolName = typeof command.toolName === "function" ? command.toolName({ ...parsedArgsObject, ...options2 }) : command.toolName; + const toolParams = command.toolParams({ ...parsedArgsObject, ...options2 }); + return { toolName, toolParams }; +} +function zodParse(schema, data, type3) { + try { + return schema.parse(data); + } catch (e) { + throw new Error(e.issues.map((issue) => { + const keys = issue.code === "unrecognized_keys" ? issue.keys : [""]; + const props = keys.map((key) => [...issue.path, key].filter(Boolean).join(".")); + return props.map((prop) => { + const label = type3 === "option" ? `'--${prop}' option` : `'${prop}' argument`; + switch (issue.code) { + case "invalid_type": + return "error: " + label + ": " + issue.message.replace(/Invalid input:/, "").trim(); + case "unrecognized_keys": + return "error: unknown " + label; + default: + return "error: " + label + ": " + issue.message; + } + }); + }).flat().join("\n")); + } +} +var z27, kEmptyOptions, kEmptyArgs; +var init_command = __esm({ + "packages/playwright-core/src/tools/cli-daemon/command.ts"() { + "use strict"; + z27 = require("./utilsBundle").z; + kEmptyOptions = z27.object({}); + kEmptyArgs = z27.object({}); + } +}); + +// packages/playwright-core/src/tools/cli-client/minimist.ts +function minimist(args, opts) { + if (!opts) + opts = {}; + const bools = {}; + const strings = {}; + for (const key of toArray(opts.boolean)) + bools[key] = true; + for (const key of toArray(opts.string)) + strings[key] = true; + const argv = { _: [] }; + function setArg(key, val) { + if (argv[key] === void 0 || bools[key] || typeof argv[key] === "boolean") + argv[key] = val; + else if (Array.isArray(argv[key])) + argv[key].push(val); + else + argv[key] = [argv[key], val]; + } + let notFlags = []; + const doubleDashIndex = args.indexOf("--"); + if (doubleDashIndex !== -1) { + notFlags = args.slice(doubleDashIndex + 1); + args = args.slice(0, doubleDashIndex); + } + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + let key; + let next; + if (/^--.+=/.test(arg)) { + const m = arg.match(/^--([^=]+)=([\s\S]*)$/); + key = m[1]; + if (bools[key]) + throw new Error(`boolean option '--${key}' should not be passed with '=value', use '--${key}' or '--no-${key}' instead`); + setArg(key, m[2]); + } else if (/^--no-.+/.test(arg)) { + key = arg.match(/^--no-(.+)/)[1]; + setArg(key, false); + } else if (/^--.+/.test(arg)) { + key = arg.match(/^--(.+)/)[1]; + next = args[i + 1]; + if (next !== void 0 && !/^(-|--)[^-]/.test(next) && !bools[key]) { + setArg(key, next); + i += 1; + } else if (/^(true|false)$/.test(next)) { + setArg(key, next === "true"); + i += 1; + } else { + setArg(key, strings[key] ? "" : true); + } + } else if (/^-[^-]+/.test(arg)) { + const letters = arg.slice(1, -1).split(""); + let broken = false; + for (let j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + if (next === "-") { + setArg(letters[j], next); + continue; + } + if (/[A-Za-z]/.test(letters[j]) && next[0] === "=") { + setArg(letters[j], next.slice(1)); + broken = true; + break; + } + if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { + setArg(letters[j], next); + broken = true; + break; + } + if (letters[j + 1] && letters[j + 1].match(/\W/)) { + setArg(letters[j], arg.slice(j + 2)); + broken = true; + break; + } else { + setArg(letters[j], strings[letters[j]] ? "" : true); + } + } + key = arg.slice(-1)[0]; + if (!broken && key !== "-") { + if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1]) && !bools[key]) { + setArg(key, args[i + 1]); + i += 1; + } else if (args[i + 1] && /^(true|false)$/.test(args[i + 1])) { + setArg(key, args[i + 1] === "true"); + i += 1; + } else { + setArg(key, strings[key] ? "" : true); + } + } + } else { + argv._.push(arg); + } + } + for (const k of notFlags) + argv._.push(k); + return argv; +} +function toArray(value2) { + if (!value2) + return []; + return Array.isArray(value2) ? value2 : [value2]; +} +var init_minimist = __esm({ + "packages/playwright-core/src/tools/cli-client/minimist.ts"() { + "use strict"; + } +}); + +// packages/playwright-core/src/tools/cli-daemon/commands.ts +var z28, elementTargetDescription2, numberArg, open5, attach, close2, detach, goto, goBack2, goForward2, reload2, pressKey, type2, keydown2, keyup2, mouseMove2, mouseDown2, mouseUp2, mouseWheel2, click2, doubleClick, drag2, drop2, fill, hover2, select, fileUpload, check2, uncheck2, snapshot2, generateLocator2, highlight2, evaluate3, dialogAccept, dialogDismiss, resize2, runCode2, tabList, tabNew, tabClose, tabSelect, stateLoad, stateSave, cookieList2, cookieGet2, cookieSet2, cookieDelete2, cookieClear2, localStorageList2, localStorageGet2, localStorageSet2, localStorageDelete2, localStorageClear2, sessionStorageList2, sessionStorageGet2, sessionStorageSet2, sessionStorageDelete2, sessionStorageClear2, routeMock, routeList2, unroute2, networkStateSet2, screenshot2, pdfSave, consoleList, networkRequests, filenameOption, networkRequest, networkRequestHeaders, networkRequestBody, networkResponseHeaders, networkResponseBody, tracingStart2, tracingStop2, videoStart2, videoStop2, videoChapter2, dashboardShow, resume2, stepOver, pauseAt, sessionList, sessionCloseAll, killAll, deleteData, configPrint, install, installBrowser, tray, commandsArray, commands; +var init_commands = __esm({ + "packages/playwright-core/src/tools/cli-daemon/commands.ts"() { + "use strict"; + init_command(); + z28 = require("./utilsBundle").z; + elementTargetDescription2 = "Exact target element reference from the page snapshot, or a unique element selector"; + numberArg = z28.preprocess((val, ctx) => { + const number = Number(val); + if (Number.isNaN(number)) { + ctx.issues.push({ + code: "custom", + message: `expected number, received '${val}'`, + input: val + }); + } + return number; + }, z28.number()); + open5 = declareCommand({ + name: "open", + description: "Open the browser", + category: "core", + args: z28.object({ + url: z28.string().optional().describe("The URL to navigate to") + }), + options: z28.object({ + browser: z28.string().optional().describe("Browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge."), + config: z28.string().optional().describe("Path to the configuration file, defaults to .playwright/cli.config.json"), + headed: z28.boolean().optional().describe("Run browser in headed mode"), + persistent: z28.boolean().optional().describe("Use persistent browser profile"), + profile: z28.string().optional().describe("Path to a persistent user data directory.") + }), + toolName: "", + toolParams: () => ({}) + }); + attach = declareCommand({ + name: "attach", + description: "Attach to a running Playwright browser", + category: "core", + args: z28.object({ + name: z28.string().optional().describe("Bound browser name to attach to") + }), + options: z28.object({ + cdp: z28.string().optional().describe("Connect to an existing browser via CDP endpoint URL."), + endpoint: z28.string().optional().describe("Playwright browser server endpoint to attach to."), + extension: z28.union([z28.boolean(), z28.string()]).optional().describe("Connect to browser extension, optionally specify browser name (e.g. --extension=chrome)"), + config: z28.string().optional().describe("Path to the configuration file, defaults to .playwright/cli.config.json"), + session: z28.string().optional().describe('Session name (defaults to bound browser name or "default")') + }), + toolName: "browser_snapshot", + toolParams: () => ({ filename: "" }) + }); + close2 = declareCommand({ + name: "close", + description: "Close the browser", + category: "core", + args: z28.object({}), + toolName: "", + toolParams: () => ({}) + }); + detach = declareCommand({ + name: "detach", + description: "Detach from an attached browser", + category: "core", + args: z28.object({}), + toolName: "", + toolParams: () => ({}) + }); + goto = declareCommand({ + name: "goto", + description: "Navigate to a URL", + category: "core", + args: z28.object({ + url: z28.string().describe("The URL to navigate to") + }), + toolName: "browser_navigate", + toolParams: ({ url: url2 }) => ({ url: url2 }) + }); + goBack2 = declareCommand({ + name: "go-back", + description: "Go back to the previous page", + category: "navigation", + args: z28.object({}), + toolName: "browser_navigate_back", + toolParams: () => ({}) + }); + goForward2 = declareCommand({ + name: "go-forward", + description: "Go forward to the next page", + category: "navigation", + args: z28.object({}), + toolName: "browser_navigate_forward", + toolParams: () => ({}) + }); + reload2 = declareCommand({ + name: "reload", + description: "Reload the current page", + category: "navigation", + args: z28.object({}), + toolName: "browser_reload", + toolParams: () => ({}) + }); + pressKey = declareCommand({ + name: "press", + description: "Press a key on the keyboard, `a`, `ArrowLeft`", + category: "keyboard", + args: z28.object({ + key: z28.string().describe("Name of the key to press or a character to generate, such as `ArrowLeft` or `a`") + }), + toolName: "browser_press_key", + toolParams: ({ key }) => ({ key }) + }); + type2 = declareCommand({ + name: "type", + description: "Type text into editable element", + category: "core", + args: z28.object({ + text: z28.string().describe("Text to type into the element") + }), + options: z28.object({ + submit: z28.boolean().optional().describe("Whether to submit entered text (press Enter after)") + }), + toolName: "browser_press_sequentially", + toolParams: ({ text: text2, submit }) => ({ text: text2, submit }) + }); + keydown2 = declareCommand({ + name: "keydown", + description: "Press a key down on the keyboard", + category: "keyboard", + args: z28.object({ + key: z28.string().describe("Name of the key to press or a character to generate, such as `ArrowLeft` or `a`") + }), + toolName: "browser_keydown", + toolParams: ({ key }) => ({ key }) + }); + keyup2 = declareCommand({ + name: "keyup", + description: "Press a key up on the keyboard", + category: "keyboard", + args: z28.object({ + key: z28.string().describe("Name of the key to press or a character to generate, such as `ArrowLeft` or `a`") + }), + toolName: "browser_keyup", + toolParams: ({ key }) => ({ key }) + }); + mouseMove2 = declareCommand({ + name: "mousemove", + description: "Move mouse to a given position", + category: "mouse", + args: z28.object({ + x: numberArg.describe("X coordinate"), + y: numberArg.describe("Y coordinate") + }), + toolName: "browser_mouse_move_xy", + toolParams: ({ x, y }) => ({ x, y }) + }); + mouseDown2 = declareCommand({ + name: "mousedown", + description: "Press mouse down", + category: "mouse", + args: z28.object({ + button: z28.string().optional().describe("Button to press, defaults to left") + }), + toolName: "browser_mouse_down", + toolParams: ({ button }) => ({ button }) + }); + mouseUp2 = declareCommand({ + name: "mouseup", + description: "Press mouse up", + category: "mouse", + args: z28.object({ + button: z28.string().optional().describe("Button to press, defaults to left") + }), + toolName: "browser_mouse_up", + toolParams: ({ button }) => ({ button }) + }); + mouseWheel2 = declareCommand({ + name: "mousewheel", + description: "Scroll mouse wheel", + category: "mouse", + args: z28.object({ + dx: numberArg.describe("X delta"), + dy: numberArg.describe("Y delta") + }), + toolName: "browser_mouse_wheel", + toolParams: ({ dx: deltaX, dy: deltaY }) => ({ deltaX, deltaY }) + }); + click2 = declareCommand({ + name: "click", + description: "Perform click on a web page", + category: "core", + args: z28.object({ + target: z28.string().describe(elementTargetDescription2), + button: z28.string().optional().describe("Button to click, defaults to left") + }), + options: z28.object({ + modifiers: z28.array(z28.string()).optional().describe("Modifier keys to press") + }), + toolName: "browser_click", + toolParams: ({ target, button, modifiers }) => ({ target, button, modifiers }) + }); + doubleClick = declareCommand({ + name: "dblclick", + description: "Perform double click on a web page", + category: "core", + args: z28.object({ + target: z28.string().describe(elementTargetDescription2), + button: z28.string().optional().describe("Button to click, defaults to left") + }), + options: z28.object({ + modifiers: z28.array(z28.string()).optional().describe("Modifier keys to press") + }), + toolName: "browser_click", + toolParams: ({ target, button, modifiers }) => ({ target, button, modifiers, doubleClick: true }) + }); + drag2 = declareCommand({ + name: "drag", + description: "Perform drag and drop between two elements", + category: "core", + args: z28.object({ + startTarget: z28.string().describe("Exact source element reference from the page snapshot, or a unique element selector"), + endTarget: z28.string().describe(elementTargetDescription2) + }), + toolName: "browser_drag", + toolParams: ({ startTarget, endTarget }) => ({ startTarget, endTarget }) + }); + drop2 = declareCommand({ + name: "drop", + description: "Drop files or data onto an element", + category: "core", + args: z28.object({ + target: z28.string().describe(elementTargetDescription2) + }), + options: z28.object({ + path: z28.union([z28.string(), z28.array(z28.string())]).optional().transform((v) => v ? Array.isArray(v) ? v : [v] : void 0).describe("Absolute path to a file to drop onto the element (repeatable)"), + data: z28.union([z28.string(), z28.array(z28.string())]).optional().transform((v) => v ? Array.isArray(v) ? v : [v] : void 0).describe('Data to drop in "mime/type=value" format, e.g. --data "text/plain=hello" (repeatable)') + }), + toolName: "browser_drop", + toolParams: ({ target, path: path59, data }) => { + let dataMap; + if (data) { + dataMap = {}; + for (const entry of data) { + const idx = entry.indexOf("="); + if (idx === -1) + throw new Error(`--data must be in "mime/type=value" format, got: ${entry}`); + dataMap[entry.slice(0, idx)] = entry.slice(idx + 1); + } + } + return { target, paths: path59, data: dataMap }; + } + }); + fill = declareCommand({ + name: "fill", + description: "Fill text into editable element", + category: "core", + args: z28.object({ + target: z28.string().describe(elementTargetDescription2), + text: z28.string().describe("Text to fill into the element") + }), + options: z28.object({ + submit: z28.boolean().optional().describe("Whether to submit entered text (press Enter after)") + }), + toolName: "browser_type", + toolParams: ({ target, text: text2, submit }) => ({ target, text: text2, submit }) + }); + hover2 = declareCommand({ + name: "hover", + description: "Hover over element on page", + category: "core", + args: z28.object({ + target: z28.string().describe(elementTargetDescription2) + }), + toolName: "browser_hover", + toolParams: ({ target }) => ({ target }) + }); + select = declareCommand({ + name: "select", + description: "Select an option in a dropdown", + category: "core", + args: z28.object({ + target: z28.string().describe(elementTargetDescription2), + val: z28.string().describe("Value to select in the dropdown") + }), + toolName: "browser_select_option", + toolParams: ({ target, val: value2 }) => ({ target, values: [value2] }) + }); + fileUpload = declareCommand({ + name: "upload", + description: "Upload one or multiple files", + category: "core", + args: z28.object({ + file: z28.string().describe("The absolute paths to the files to upload") + }), + toolName: "browser_file_upload", + toolParams: ({ file }) => ({ paths: [file] }) + }); + check2 = declareCommand({ + name: "check", + description: "Check a checkbox or radio button", + category: "core", + args: z28.object({ + target: z28.string().describe(elementTargetDescription2) + }), + toolName: "browser_check", + toolParams: ({ target }) => ({ target }) + }); + uncheck2 = declareCommand({ + name: "uncheck", + description: "Uncheck a checkbox or radio button", + category: "core", + args: z28.object({ + target: z28.string().describe(elementTargetDescription2) + }), + toolName: "browser_uncheck", + toolParams: ({ target }) => ({ target }) + }); + snapshot2 = declareCommand({ + name: "snapshot", + description: "Capture page snapshot to obtain element ref", + category: "core", + args: z28.object({ + target: z28.string().optional().describe("Element reference from the previous page snapshot, or a unique element selector for the root element to capture a partial snapshot instead of the whole page") + }), + options: z28.object({ + filename: z28.string().optional().describe("Save snapshot to markdown file instead of returning it in the response."), + depth: numberArg.optional().describe("Limit snapshot depth, unlimited by default."), + boxes: z28.boolean().optional().describe("Include each element's bounding box as [box=x,y,width,height] in the snapshot. Coordinates are viewport-relative, in CSS pixels (Element.getBoundingClientRect).") + }), + toolName: "browser_snapshot", + toolParams: ({ filename, target, depth, boxes }) => ({ filename, target, depth, boxes }) + }); + generateLocator2 = declareCommand({ + name: "generate-locator", + description: "Generate a Playwright locator for the given element", + category: "devtools", + args: z28.object({ + target: z28.string().describe(elementTargetDescription2) + }), + toolName: "browser_generate_locator", + toolParams: ({ target }) => ({ target }) + }); + highlight2 = declareCommand({ + name: "highlight", + description: "Show (or with --hide, remove) a highlight overlay for an element; `--hide` without a target hides all page highlights.", + category: "devtools", + args: z28.object({ + target: z28.string().optional().describe(elementTargetDescription2) + }), + options: z28.object({ + hide: z28.boolean().optional().describe("Hide a previously added highlight for this element, or all page highlights when no element is given"), + style: z28.string().optional().describe('Additional inline CSS applied to the highlight overlay, e.g. "outline: 2px dashed red"') + }), + toolName: ({ hide }) => hide ? "browser_hide_highlight" : "browser_highlight", + toolParams: ({ target, style }) => ({ target, style }) + }); + evaluate3 = declareCommand({ + name: "eval", + description: "Evaluate JavaScript expression on page or element", + category: "core", + args: z28.object({ + func: z28.string().describe("() => { /* code */ } or (element) => { /* code */ } when element is provided"), + target: z28.string().optional().describe(elementTargetDescription2) + }), + options: z28.object({ + filename: z28.string().optional().describe("Save evaluation result to a file instead of returning it in the response.") + }), + toolName: "browser_evaluate", + toolParams: ({ func, target, filename }) => ({ function: func, filename, target }) + }); + dialogAccept = declareCommand({ + name: "dialog-accept", + description: "Accept a dialog", + category: "core", + args: z28.object({ + prompt: z28.string().optional().describe("The text of the prompt in case of a prompt dialog.") + }), + toolName: "browser_handle_dialog", + toolParams: ({ prompt: promptText }) => ({ accept: true, promptText }) + }); + dialogDismiss = declareCommand({ + name: "dialog-dismiss", + description: "Dismiss a dialog", + category: "core", + args: z28.object({}), + toolName: "browser_handle_dialog", + toolParams: () => ({ accept: false }) + }); + resize2 = declareCommand({ + name: "resize", + description: "Resize the browser window", + category: "core", + args: z28.object({ + w: numberArg.describe("Width of the browser window"), + h: numberArg.describe("Height of the browser window") + }), + toolName: "browser_resize", + toolParams: ({ w: width, h: height }) => ({ width, height }) + }); + runCode2 = declareCommand({ + name: "run-code", + description: "Run Playwright code snippet", + category: "devtools", + args: z28.object({ + code: z28.string().optional().describe("A JavaScript function containing Playwright code to execute. It will be invoked with a single argument, page, which you can use for any page interaction.") + }), + options: z28.object({ + filename: z28.string().optional().describe("Load code from the specified file.") + }), + toolName: "browser_run_code_unsafe", + toolParams: ({ code, filename }) => ({ code, filename }) + }); + tabList = declareCommand({ + name: "tab-list", + description: "List all tabs", + category: "tabs", + args: z28.object({}), + toolName: "browser_tabs", + toolParams: () => ({ action: "list" }) + }); + tabNew = declareCommand({ + name: "tab-new", + description: "Create a new tab", + category: "tabs", + args: z28.object({ + url: z28.string().optional().describe("The URL to navigate to in the new tab. If omitted, the new tab will be blank.") + }), + toolName: "browser_tabs", + toolParams: ({ url: url2 }) => ({ action: "new", url: url2 }) + }); + tabClose = declareCommand({ + name: "tab-close", + description: "Close a browser tab", + category: "tabs", + args: z28.object({ + index: numberArg.optional().describe("Tab index. If omitted, current tab is closed.") + }), + toolName: "browser_tabs", + toolParams: ({ index }) => ({ action: "close", index }) + }); + tabSelect = declareCommand({ + name: "tab-select", + description: "Select a browser tab", + category: "tabs", + args: z28.object({ + index: numberArg.describe("Tab index") + }), + toolName: "browser_tabs", + toolParams: ({ index }) => ({ action: "select", index }) + }); + stateLoad = declareCommand({ + name: "state-load", + description: "Loads browser storage (authentication) state from a file", + category: "storage", + args: z28.object({ + filename: z28.string().describe("File name to load the storage state from.") + }), + toolName: "browser_set_storage_state", + toolParams: ({ filename }) => ({ filename }) + }); + stateSave = declareCommand({ + name: "state-save", + description: "Saves the current storage (authentication) state to a file", + category: "storage", + args: z28.object({ + filename: z28.string().optional().describe("File name to save the storage state to.") + }), + toolName: "browser_storage_state", + toolParams: ({ filename }) => ({ filename }) + }); + cookieList2 = declareCommand({ + name: "cookie-list", + description: "List all cookies (optionally filtered by domain/path)", + category: "storage", + raw: true, + args: z28.object({}), + options: z28.object({ + domain: z28.string().optional().describe("Filter cookies by domain"), + path: z28.string().optional().describe("Filter cookies by path") + }), + toolName: "browser_cookie_list", + toolParams: ({ domain, path: path59 }) => ({ domain, path: path59 }) + }); + cookieGet2 = declareCommand({ + name: "cookie-get", + description: "Get a specific cookie by name", + category: "storage", + raw: true, + args: z28.object({ + name: z28.string().describe("Cookie name") + }), + toolName: "browser_cookie_get", + toolParams: ({ name }) => ({ name }) + }); + cookieSet2 = declareCommand({ + name: "cookie-set", + description: "Set a cookie with optional flags", + category: "storage", + args: z28.object({ + name: z28.string().describe("Cookie name"), + value: z28.string().describe("Cookie value") + }), + options: z28.object({ + domain: z28.string().optional().describe("Cookie domain"), + path: z28.string().optional().describe("Cookie path"), + expires: numberArg.optional().describe("Cookie expiration as Unix timestamp"), + httpOnly: z28.boolean().optional().describe("Whether the cookie is HTTP only"), + secure: z28.boolean().optional().describe("Whether the cookie is secure"), + sameSite: z28.enum(["Strict", "Lax", "None"]).optional().describe("Cookie SameSite attribute") + }), + toolName: "browser_cookie_set", + toolParams: ({ name, value: value2, domain, path: path59, expires, httpOnly, secure, sameSite }) => ({ name, value: value2, domain, path: path59, expires, httpOnly, secure, sameSite }) + }); + cookieDelete2 = declareCommand({ + name: "cookie-delete", + description: "Delete a specific cookie", + category: "storage", + args: z28.object({ + name: z28.string().describe("Cookie name") + }), + toolName: "browser_cookie_delete", + toolParams: ({ name }) => ({ name }) + }); + cookieClear2 = declareCommand({ + name: "cookie-clear", + description: "Clear all cookies", + category: "storage", + args: z28.object({}), + toolName: "browser_cookie_clear", + toolParams: () => ({}) + }); + localStorageList2 = declareCommand({ + name: "localstorage-list", + description: "List all localStorage key-value pairs", + category: "storage", + raw: true, + args: z28.object({}), + toolName: "browser_localstorage_list", + toolParams: () => ({}) + }); + localStorageGet2 = declareCommand({ + name: "localstorage-get", + description: "Get a localStorage item by key", + category: "storage", + raw: true, + args: z28.object({ + key: z28.string().describe("Key to get") + }), + toolName: "browser_localstorage_get", + toolParams: ({ key }) => ({ key }) + }); + localStorageSet2 = declareCommand({ + name: "localstorage-set", + description: "Set a localStorage item", + category: "storage", + args: z28.object({ + key: z28.string().describe("Key to set"), + value: z28.string().describe("Value to set") + }), + toolName: "browser_localstorage_set", + toolParams: ({ key, value: value2 }) => ({ key, value: value2 }) + }); + localStorageDelete2 = declareCommand({ + name: "localstorage-delete", + description: "Delete a localStorage item", + category: "storage", + args: z28.object({ + key: z28.string().describe("Key to delete") + }), + toolName: "browser_localstorage_delete", + toolParams: ({ key }) => ({ key }) + }); + localStorageClear2 = declareCommand({ + name: "localstorage-clear", + description: "Clear all localStorage", + category: "storage", + args: z28.object({}), + toolName: "browser_localstorage_clear", + toolParams: () => ({}) + }); + sessionStorageList2 = declareCommand({ + name: "sessionstorage-list", + description: "List all sessionStorage key-value pairs", + category: "storage", + raw: true, + args: z28.object({}), + toolName: "browser_sessionstorage_list", + toolParams: () => ({}) + }); + sessionStorageGet2 = declareCommand({ + name: "sessionstorage-get", + description: "Get a sessionStorage item by key", + category: "storage", + raw: true, + args: z28.object({ + key: z28.string().describe("Key to get") + }), + toolName: "browser_sessionstorage_get", + toolParams: ({ key }) => ({ key }) + }); + sessionStorageSet2 = declareCommand({ + name: "sessionstorage-set", + description: "Set a sessionStorage item", + category: "storage", + args: z28.object({ + key: z28.string().describe("Key to set"), + value: z28.string().describe("Value to set") + }), + toolName: "browser_sessionstorage_set", + toolParams: ({ key, value: value2 }) => ({ key, value: value2 }) + }); + sessionStorageDelete2 = declareCommand({ + name: "sessionstorage-delete", + description: "Delete a sessionStorage item", + category: "storage", + args: z28.object({ + key: z28.string().describe("Key to delete") + }), + toolName: "browser_sessionstorage_delete", + toolParams: ({ key }) => ({ key }) + }); + sessionStorageClear2 = declareCommand({ + name: "sessionstorage-clear", + description: "Clear all sessionStorage", + category: "storage", + args: z28.object({}), + toolName: "browser_sessionstorage_clear", + toolParams: () => ({}) + }); + routeMock = declareCommand({ + name: "route", + description: "Mock network requests matching a URL pattern", + category: "network", + args: z28.object({ + pattern: z28.string().describe('URL pattern to match (e.g., "**/api/users")') + }), + options: z28.object({ + status: numberArg.optional().describe("HTTP status code (default: 200)"), + body: z28.string().optional().describe("Response body (text or JSON string)"), + ["content-type"]: z28.string().optional().describe("Content-Type header"), + header: z28.union([z28.string(), z28.array(z28.string())]).optional().transform((v) => v ? Array.isArray(v) ? v : [v] : void 0).describe('Header to add in "Name: Value" format (repeatable)'), + ["remove-header"]: z28.string().optional().describe("Comma-separated header names to remove") + }), + toolName: "browser_route", + toolParams: ({ pattern, status, body, ["content-type"]: contentType, header: headers, ["remove-header"]: removeHeaders }) => ({ + pattern, + status, + body, + contentType, + headers, + removeHeaders + }) + }); + routeList2 = declareCommand({ + name: "route-list", + description: "List all active network routes", + category: "network", + raw: true, + args: z28.object({}), + toolName: "browser_route_list", + toolParams: () => ({}) + }); + unroute2 = declareCommand({ + name: "unroute", + description: "Remove routes matching a pattern (or all routes)", + category: "network", + args: z28.object({ + pattern: z28.string().optional().describe("URL pattern to unroute (omit to remove all)") + }), + toolName: "browser_unroute", + toolParams: ({ pattern }) => ({ pattern }) + }); + networkStateSet2 = declareCommand({ + name: "network-state-set", + description: "Set the browser network state to online or offline", + category: "network", + args: z28.object({ + state: z28.enum(["online", "offline"]).describe('Set to "offline" to simulate offline mode, "online" to restore network connectivity') + }), + toolName: "browser_network_state_set", + toolParams: ({ state }) => ({ state }) + }); + screenshot2 = declareCommand({ + name: "screenshot", + description: "screenshot of the current page or element", + category: "export", + args: z28.object({ + target: z28.string().optional().describe(elementTargetDescription2) + }), + options: z28.object({ + filename: z28.string().optional().describe("File name to save the screenshot to. Defaults to `page-{timestamp}.{png|jpeg}` if not specified."), + ["full-page"]: z28.boolean().optional().describe("When true, takes a screenshot of the full scrollable page, instead of the currently visible viewport.") + }), + toolName: "browser_take_screenshot", + toolParams: ({ target, filename, ["full-page"]: fullPage }) => ({ filename, target, fullPage }) + }); + pdfSave = declareCommand({ + name: "pdf", + description: "Save page as PDF", + category: "export", + args: z28.object({}), + options: z28.object({ + filename: z28.string().optional().describe("File name to save the pdf to. Defaults to `page-{timestamp}.pdf` if not specified.") + }), + toolName: "browser_pdf_save", + toolParams: ({ filename }) => ({ filename }) + }); + consoleList = declareCommand({ + name: "console", + description: "List console messages", + category: "devtools", + args: z28.object({ + ["min-level"]: z28.string().optional().describe('Level of the console messages to return. Each level includes the messages of more severe levels. Defaults to "info".') + }), + options: z28.object({ + clear: z28.boolean().optional().describe("Whether to clear the console list") + }), + toolName: ({ clear }) => clear ? "browser_console_clear" : "browser_console_messages", + toolParams: ({ ["min-level"]: level, clear }) => clear ? {} : { level } + }); + networkRequests = declareCommand({ + name: "requests", + description: "List all network requests since loading the page. Each request is numbered for use with the `request` command.", + category: "network", + args: z28.object({}), + options: z28.object({ + static: z28.boolean().optional().describe("Whether to include successful static resources like images, fonts, scripts, etc. Defaults to false."), + filter: z28.string().optional().describe('Only return requests whose URL matches this regexp (e.g. "/api/.*user").'), + clear: z28.boolean().optional().describe("Whether to clear the network list") + }), + toolName: ({ clear }) => clear ? "browser_network_clear" : "browser_network_requests", + toolParams: ({ static: s, filter, clear }) => clear ? {} : { static: s, filter } + }); + filenameOption = z28.string().optional().describe("Filename to save the result to. If not provided, output is returned as text."); + networkRequest = declareCommand({ + name: "request", + description: "Show full details (headers, body, response) of a single network request by its number from the `requests` command.", + category: "network", + args: z28.object({ + index: numberArg.describe("1-based number of the request as listed by `requests`") + }), + options: z28.object({ + filename: filenameOption + }), + toolName: "browser_network_request", + toolParams: ({ index, filename }) => ({ index, filename }) + }); + networkRequestHeaders = declareCommand({ + name: "request-headers", + description: "Print only the request headers for a single network request by its number from the `requests` command.", + category: "network", + raw: true, + args: z28.object({ + index: numberArg.describe("1-based number of the request as listed by `requests`") + }), + options: z28.object({ + filename: filenameOption + }), + toolName: "browser_network_request", + toolParams: ({ index, filename }) => ({ index, part: "request-headers", filename }) + }); + networkRequestBody = declareCommand({ + name: "request-body", + description: "Print only the request body for a single network request by its number from the `requests` command.", + category: "network", + raw: true, + args: z28.object({ + index: numberArg.describe("1-based number of the request as listed by `requests`") + }), + options: z28.object({ + filename: filenameOption + }), + toolName: "browser_network_request", + toolParams: ({ index, filename }) => ({ index, part: "request-body", filename }) + }); + networkResponseHeaders = declareCommand({ + name: "response-headers", + description: "Print only the response headers for a single network request by its number from the `requests` command.", + category: "network", + raw: true, + args: z28.object({ + index: numberArg.describe("1-based number of the request as listed by `requests`") + }), + options: z28.object({ + filename: filenameOption + }), + toolName: "browser_network_request", + toolParams: ({ index, filename }) => ({ index, part: "response-headers", filename }) + }); + networkResponseBody = declareCommand({ + name: "response-body", + description: "Print the response body for a single network request by its number from the `requests` command. Textual bodies are inlined; binary bodies are saved to a file and the path is printed.", + category: "network", + raw: true, + args: z28.object({ + index: numberArg.describe("1-based number of the request as listed by `requests`") + }), + options: z28.object({ + filename: filenameOption + }), + toolName: "browser_network_request", + toolParams: ({ index, filename }) => ({ index, part: "response-body", filename }) + }); + tracingStart2 = declareCommand({ + name: "tracing-start", + description: "Start trace recording", + category: "devtools", + args: z28.object({}), + toolName: "browser_start_tracing", + toolParams: () => ({}) + }); + tracingStop2 = declareCommand({ + name: "tracing-stop", + description: "Stop trace recording", + category: "devtools", + args: z28.object({}), + toolName: "browser_stop_tracing", + toolParams: () => ({}) + }); + videoStart2 = declareCommand({ + name: "video-start", + description: "Start video recording", + category: "devtools", + args: z28.object({ + filename: z28.string().optional().describe("Filename to save the video.") + }), + options: z28.object({ + size: z28.string().optional().describe('Video frame size, e.g. "800x600". If not specified, the size of the recorded video will fit 800x800.') + }), + toolName: "browser_start_video", + toolParams: ({ filename, size }) => { + const parsedSize = size ? size.split("x").map(Number) : void 0; + return { filename, size: parsedSize ? { width: parsedSize[0], height: parsedSize[1] } : void 0 }; + } + }); + videoStop2 = declareCommand({ + name: "video-stop", + description: "Stop video recording", + category: "devtools", + toolName: "browser_stop_video", + toolParams: () => ({}) + }); + videoChapter2 = declareCommand({ + name: "video-chapter", + description: "Add a chapter marker to the video recording", + category: "devtools", + args: z28.object({ + title: z28.string().describe("Chapter title.") + }), + options: z28.object({ + description: z28.string().optional().describe("Chapter description."), + duration: numberArg.optional().describe("Duration in milliseconds to show the chapter card.") + }), + toolName: "browser_video_chapter", + toolParams: ({ title, description, duration }) => ({ title, description, duration }) + }); + dashboardShow = declareCommand({ + name: "show", + description: "Show Playwright Dashboard", + category: "devtools", + raw: true, + args: z28.object({}), + options: z28.object({ + port: numberArg.optional().describe("Start as a blocking HTTP server on this port (use 0 for a random port)"), + host: z28.string().optional().describe("Host to bind to when using --port (defaults to localhost)"), + annotate: z28.boolean().optional().describe("Switch the dashboard into annotation mode."), + kill: z28.boolean().optional().describe("Kill the dashboard daemon.") + }), + toolName: ({ annotate: annotate2 }) => annotate2 ? "browser_annotate" : "", + toolParams: () => ({}) + }); + resume2 = declareCommand({ + name: "resume", + description: "Resume the test execution", + category: "devtools", + args: z28.object({}), + toolName: "browser_resume", + toolParams: ({ step }) => ({ step }) + }); + stepOver = declareCommand({ + name: "step-over", + description: "Step over the next call in the test", + category: "devtools", + args: z28.object({}), + toolName: "browser_resume", + toolParams: ({}) => ({ step: true }) + }); + pauseAt = declareCommand({ + name: "pause-at", + description: "Run the test up to a specific location and pause there", + category: "devtools", + args: z28.object({ + location: z28.string().describe('Location to pause at. Format is :, e.g. "example.spec.ts:42".') + }), + toolName: "browser_resume", + toolParams: ({ location: location2 }) => ({ location: location2 }) + }); + sessionList = declareCommand({ + name: "list", + description: "List browser sessions", + category: "browsers", + args: z28.object({}), + options: z28.object({ + all: z28.boolean().optional().describe("List all browser sessions across all workspaces") + }), + toolName: "", + toolParams: () => ({}) + }); + sessionCloseAll = declareCommand({ + name: "close-all", + description: "Close all browser sessions", + category: "browsers", + toolName: "", + toolParams: () => ({}) + }); + killAll = declareCommand({ + name: "kill-all", + description: "Forcefully kill all browser sessions (for stale/zombie processes)", + category: "browsers", + toolName: "", + toolParams: () => ({}) + }); + deleteData = declareCommand({ + name: "delete-data", + description: "Delete session data", + category: "core", + toolName: "", + toolParams: () => ({}) + }); + configPrint = declareCommand({ + name: "config-print", + description: "Print the final resolved config after merging CLI options, environment variables and config file.", + category: "config", + hidden: true, + toolName: "browser_get_config", + toolParams: () => ({}) + }); + install = declareCommand({ + name: "install", + description: "Initialize workspace", + category: "install", + args: z28.object({}), + options: z28.object({ + skills: z28.string().optional().describe("Install skills, possible values: claude (default), agents.") + }), + toolName: "", + toolParams: () => ({}) + }); + installBrowser = declareCommand({ + name: "install-browser", + description: "Install browser", + category: "install", + args: z28.object({ + browser: z28.string().optional().describe("Browser to install") + }), + options: z28.object({ + ["with-deps"]: z28.boolean().optional().describe("Install system dependencies for browsers"), + ["dry-run"]: z28.boolean().optional().describe("Do not execute installation, only print information"), + list: z28.boolean().optional().describe("Prints list of browsers from all Playwright installations"), + force: z28.boolean().optional().describe("Force reinstall of already installed browsers"), + ["only-shell"]: z28.boolean().optional().describe("Only install headless shell when installing Chromium"), + ["no-shell"]: z28.boolean().optional().describe("Do not install Chromium headless shell") + }), + toolName: "", + toolParams: () => ({}) + }); + tray = declareCommand({ + name: "tray", + description: "Run tray", + category: "config", + hidden: true, + toolName: "", + toolParams: () => ({}) + }); + commandsArray = [ + // core category + open5, + attach, + close2, + detach, + goto, + type2, + click2, + doubleClick, + fill, + drag2, + drop2, + hover2, + select, + fileUpload, + check2, + uncheck2, + snapshot2, + evaluate3, + consoleList, + dialogAccept, + dialogDismiss, + resize2, + runCode2, + deleteData, + // navigation category + goBack2, + goForward2, + reload2, + // keyboard category + pressKey, + keydown2, + keyup2, + // mouse category + mouseMove2, + mouseDown2, + mouseUp2, + mouseWheel2, + // export category + screenshot2, + pdfSave, + // tabs category + tabList, + tabNew, + tabClose, + tabSelect, + // storage category + stateLoad, + stateSave, + cookieList2, + cookieGet2, + cookieSet2, + cookieDelete2, + cookieClear2, + localStorageList2, + localStorageGet2, + localStorageSet2, + localStorageDelete2, + localStorageClear2, + sessionStorageList2, + sessionStorageGet2, + sessionStorageSet2, + sessionStorageDelete2, + sessionStorageClear2, + // network category + networkRequests, + networkRequest, + networkRequestHeaders, + networkRequestBody, + networkResponseHeaders, + networkResponseBody, + routeMock, + routeList2, + unroute2, + networkStateSet2, + // config category + configPrint, + // install category + install, + installBrowser, + // devtools category + tracingStart2, + tracingStop2, + videoStart2, + videoStop2, + videoChapter2, + dashboardShow, + pauseAt, + resume2, + stepOver, + generateLocator2, + highlight2, + // session category + sessionList, + sessionCloseAll, + killAll, + // Hidden commands + tray + ]; + commands = Object.fromEntries(commandsArray.map((cmd) => [cmd.name, cmd])); + } +}); + +// packages/playwright-core/src/tools/trace/traceSnapshot.ts +async function traceSnapshot(actionId, options2) { + const trace = await loadTrace(); + const action = trace.resolveActionId(actionId); + if (!action) { + console.error(`Action '${actionId}' not found.`); + process.exitCode = 1; + return; + } + const pageId4 = action.pageId; + if (!pageId4) { + console.error(`Action '${actionId}' has no associated page.`); + process.exitCode = 1; + return; + } + const callId = action.callId; + const storage = trace.loader.storage(); + let snapshotName; + let renderer; + if (options2.name) { + snapshotName = options2.name; + renderer = storage.snapshotByName(pageId4, `${snapshotName}@${callId}`); + } else { + for (const candidate of ["input", "before", "after"]) { + renderer = storage.snapshotByName(pageId4, `${candidate}@${callId}`); + if (renderer) { + snapshotName = candidate; + break; + } + } + } + if (!renderer || !snapshotName) { + console.error(`No snapshot found for action '${actionId}'.`); + process.exitCode = 1; + return; + } + const snapshotKey = `${snapshotName}@${callId}`; + const server = await serveTraceSnapshot(storage, trace.loader, pageId4, snapshotKey); + if (options2.serve) { + console.log(`Serving snapshot at ${server.url}`); + await new Promise(() => { + }); + return; + } + await runCommandOnSnapshot(server, options2.browserArgs || []); +} +async function serveTraceSnapshot(storage, loader, pageId4, snapshotKey) { + const snapshotServer = new SnapshotServer(storage, (sha1) => loader.resourceForSha1(sha1)); + const httpServer = new HttpServer(); + httpServer.routePrefix("/snapshot/", (request2, response2) => { + const url2 = new URL("http://localhost" + request2.url); + const pageOrFrameId = url2.pathname.substring("/snapshot/".length); + const searchParams = url2.searchParams; + searchParams.set("name", snapshotKey); + const snapshotResponse = snapshotServer.serveSnapshot(pageOrFrameId, searchParams, url2.href); + response2.statusCode = snapshotResponse.status; + snapshotResponse.headers.forEach((value2, key) => response2.setHeader(key, value2)); + snapshotResponse.text().then((text2) => response2.end(text2)); + return true; + }); + httpServer.routePrefix("/", (_request, response2) => { + response2.statusCode = 302; + response2.setHeader("Location", `/snapshot/${pageId4}?name=${encodeURIComponent(snapshotKey)}`); + response2.end(); + return true; + }); + await httpServer.start({ preferredPort: 0 }); + return { url: httpServer.urlPrefix("human-readable"), stop: () => httpServer.stop() }; +} +async function runCommandOnSnapshot(server, browserArgs) { + const browser = await playwright.chromium.launch({ headless: true }); + const context2 = await browser.newContext(); + const page = await context2.newPage(); + await page.goto(server.url); + const backend = new BrowserBackend({ + snapshot: { mode: "full" }, + outputMode: "file", + skillMode: true + }, context2, browserTools); + await backend.initialize({ cwd: process.cwd(), clientName: "playwright-cli" }); + try { + if (!browserArgs.length) + browserArgs = ["snapshot"]; + const args = minimist(browserArgs, { string: ["_"] }); + const command = commands[args._[0]]; + if (!command) + throw new Error(`Unknown command: ${args._[0]}`); + const { toolName, toolParams } = parseCommand(command, args); + const result2 = await backend.callTool(toolName, toolParams); + const text2 = result2.content[0]?.type === "text" ? result2.content[0].text : void 0; + if (text2) + console.log(text2); + if (result2.isError) { + console.error("Command failed."); + process.exitCode = 1; + } + } catch (e) { + console.error(e.message); + process.exitCode = 1; + } finally { + await server.stop().catch((e) => console.error(e)); + await gracefullyCloseAll(); + } +} +var init_traceSnapshot = __esm({ + "packages/playwright-core/src/tools/trace/traceSnapshot.ts"() { + "use strict"; + init_processLauncher(); + init_httpServer(); + init_snapshotServer(); + init_browserBackend(); + init_tools(); + init_inprocess(); + init_command(); + init_minimist(); + init_commands(); + init_traceUtils2(); + } +}); + +// packages/playwright-core/src/tools/trace/traceScreenshot.ts +async function traceScreenshot(actionId, options2) { + const trace = await loadTrace(); + const action = trace.resolveActionId(actionId); + if (!action) { + console.error(`Action '${actionId}' not found.`); + process.exitCode = 1; + return; + } + const pageId4 = action.pageId; + if (!pageId4) { + console.error(`Action '${actionId}' has no associated page.`); + process.exitCode = 1; + return; + } + const callId = action.callId; + const storage = trace.loader.storage(); + const snapshotNames = ["input", "before", "after"]; + let sha1; + for (const name of snapshotNames) { + const renderer = storage.snapshotByName(pageId4, `${name}@${callId}`); + sha1 = renderer?.closestScreenshot(); + if (sha1) + break; + } + if (!sha1) { + console.error(`No screenshot found for action '${actionId}'.`); + process.exitCode = 1; + return; + } + const blob = await trace.loader.resourceForSha1(sha1); + if (!blob) { + console.error(`Screenshot resource not found.`); + process.exitCode = 1; + return; + } + const defaultName = `screenshot-${actionId}.png`; + const buffer = Buffer.from(await blob.arrayBuffer()); + const outFile = await saveOutputFile(defaultName, buffer, options2.output); + console.log(` Screenshot saved to ${outFile}`); +} +var init_traceScreenshot = __esm({ + "packages/playwright-core/src/tools/trace/traceScreenshot.ts"() { + "use strict"; + init_traceUtils2(); + } +}); + +// packages/playwright-core/src/tools/trace/traceAttachments.ts +async function traceAttachments() { + const trace = await loadTrace(); + if (!trace.model.attachments.length) { + console.log(" No attachments"); + return; + } + console.log(` ${"#".padStart(4)} ${"Name".padEnd(40)} ${"Content-Type".padEnd(30)} ${"Action".padEnd(8)}`); + console.log(` ${"\u2500".repeat(4)} ${"\u2500".repeat(40)} ${"\u2500".repeat(30)} ${"\u2500".repeat(8)}`); + for (let i = 0; i < trace.model.attachments.length; i++) { + const a = trace.model.attachments[i]; + const actionOrdinal = trace.callIdToOrdinal.get(a.callId); + console.log(` ${(i + 1 + ".").padStart(4)} ${a.name.padEnd(40)} ${a.contentType.padEnd(30)} ${(actionOrdinal !== void 0 ? String(actionOrdinal) : a.callId).padEnd(8)}`); + } +} +async function traceAttachment(attachmentId, options2) { + const trace = await loadTrace(); + const ordinal = parseInt(attachmentId, 10); + const attachment = !isNaN(ordinal) && ordinal >= 1 && ordinal <= trace.model.attachments.length ? trace.model.attachments[ordinal - 1] : void 0; + if (!attachment) { + console.error(`Attachment '${attachmentId}' not found. Use 'trace attachments' to see available attachments.`); + process.exitCode = 1; + return; + } + let content; + if (attachment.sha1) { + const blob = await trace.loader.resourceForSha1(attachment.sha1); + if (blob) + content = Buffer.from(await blob.arrayBuffer()); + } else if (attachment.base64) { + content = Buffer.from(attachment.base64, "base64"); + } + if (!content) { + console.error(`Could not extract attachment content.`); + process.exitCode = 1; + return; + } + const outFile = await saveOutputFile(attachment.name, content, options2.output); + console.log(` Attachment saved to ${outFile}`); +} +var init_traceAttachments = __esm({ + "packages/playwright-core/src/tools/trace/traceAttachments.ts"() { + "use strict"; + init_traceUtils2(); + } +}); + +// packages/playwright-core/src/tools/trace/installSkill.ts +async function installSkill() { + const cwd = process.cwd(); + const skillSource = libPath("tools", "trace", "SKILL.md"); + const destDir = import_path42.default.join(cwd, ".claude", "skills", "playwright-trace"); + await import_fs47.default.promises.mkdir(destDir, { recursive: true }); + const destFile = import_path42.default.join(destDir, "SKILL.md"); + await import_fs47.default.promises.copyFile(skillSource, destFile); + console.log(`\u2705 Skill installed to \`${import_path42.default.relative(cwd, destFile)}\`.`); +} +var import_fs47, import_path42; +var init_installSkill = __esm({ + "packages/playwright-core/src/tools/trace/installSkill.ts"() { + "use strict"; + import_fs47 = __toESM(require("fs")); + import_path42 = __toESM(require("path")); + init_package(); + } +}); + +// packages/playwright-core/src/tools/trace/traceCli.ts +function addTraceCommands(program4, logErrorAndExit2) { + const traceCommand = program4.command("trace").description("inspect trace files from the command line"); + traceCommand.command("open ").description("extract trace file for inspection").action(async (trace) => { + traceOpen(trace).catch(logErrorAndExit2); + }); + traceCommand.command("close").description("remove extracted trace data").action(async () => { + closeTrace().catch(logErrorAndExit2); + }); + traceCommand.command("actions").description("list actions in the trace").option("--grep ", "filter actions by title pattern").option("--errors-only", "only show failed actions").action(async (options2) => { + traceActions(options2).catch(logErrorAndExit2); + }); + traceCommand.command("action ").description("show details of a specific action").action(async (actionId) => { + traceAction(actionId).catch(logErrorAndExit2); + }); + traceCommand.command("requests").description("show network requests").option("--grep ", "filter by URL pattern").option("--method ", "filter by HTTP method").option("--status ", "filter by status code").option("--failed", "only show failed requests (status >= 400)").action(async (options2) => { + traceRequests(options2).catch(logErrorAndExit2); + }); + traceCommand.command("request ").description("show details of a specific network request").action(async (requestId) => { + traceRequest(requestId).catch(logErrorAndExit2); + }); + traceCommand.command("console").description("show console messages").option("--errors-only", "only show errors").option("--warnings", "show errors and warnings").option("--browser", "only browser console messages").option("--stdio", "only stdout/stderr").action(async (options2) => { + traceConsole(options2).catch(logErrorAndExit2); + }); + traceCommand.command("errors").description("show errors with stack traces").action(async () => { + traceErrors().catch(logErrorAndExit2); + }); + traceCommand.command("snapshot ").description("run a playwright-cli command against a DOM snapshot").option("--name ", "snapshot phase: before, input, or after").option("--serve", "serve snapshot on localhost and keep running").allowUnknownOption(true).allowExcessArguments(true).action(async (actionId, options2, cmd) => { + try { + const browserArgs = cmd.args.slice(1); + await traceSnapshot(actionId, { ...options2, browserArgs }); + } catch (e) { + logErrorAndExit2(e); + } + }); + traceCommand.command("screenshot ").description("save screencast screenshot for an action").option("-o, --output ", "output file path").action(async (actionId, options2) => { + traceScreenshot(actionId, options2).catch(logErrorAndExit2); + }); + traceCommand.command("attachments").description("list trace attachments").action(async () => { + traceAttachments().catch(logErrorAndExit2); + }); + traceCommand.command("attachment ").description("extract a trace attachment by its number").option("-o, --output ", "output file path").action(async (attachmentId, options2) => { + traceAttachment(attachmentId, options2).catch(logErrorAndExit2); + }); + traceCommand.command("install-skill").description("install SKILL.md for LLM integration").action(async () => { + installSkill().catch(logErrorAndExit2); + }); +} +var init_traceCli = __esm({ + "packages/playwright-core/src/tools/trace/traceCli.ts"() { + "use strict"; + init_traceOpen(); + init_traceUtils2(); + init_traceActions(); + init_traceActions(); + init_traceRequests(); + init_traceRequests(); + init_traceConsole(); + init_traceErrors(); + init_traceSnapshot(); + init_traceScreenshot(); + init_traceAttachments(); + init_traceAttachments(); + init_installSkill(); + } +}); + +// packages/playwright-core/src/cli/driver.ts +function printApiJson() { + console.log(JSON.stringify(require(import_path43.default.join(packageRoot, "api.json")))); +} +function runDriver() { + const dispatcherConnection = new DispatcherConnection(); + new RootDispatcher(dispatcherConnection, async (rootScope, { sdkLanguage }) => { + const playwright2 = createPlaywright({ sdkLanguage }); + return new PlaywrightDispatcher(rootScope, playwright2); + }); + const transport = new PipeTransport(process.stdout, process.stdin); + transport.onmessage = (message) => dispatcherConnection.dispatch(JSON.parse(message)); + const isJavaScriptLanguageBinding = !process.env.PW_LANG_NAME || process.env.PW_LANG_NAME === "javascript"; + const replacer = !isJavaScriptLanguageBinding && String.prototype.toWellFormed ? (key, value2) => { + if (typeof value2 === "string") + return value2.toWellFormed(); + return value2; + } : void 0; + dispatcherConnection.onmessage = (message) => transport.send(JSON.stringify(message, replacer)); + transport.onclose = () => { + dispatcherConnection.onmessage = () => { + }; + gracefullyProcessExitDoNotHang(0); + }; + process.on("SIGINT", () => { + }); +} +async function runServer(options2) { + const { + port, + host, + path: path59 = "/", + maxConnections = Infinity, + extension, + artifactsDir, + unsafe + } = options2; + const server = new PlaywrightServer({ mode: extension ? "extension" : "default", path: path59, maxConnections, artifactsDir, unsafe }); + const wsEndpoint = await server.listen(port, host); + process.on("exit", () => server.close().catch(console.error)); + console.log("Listening on " + wsEndpoint); + process.stdin.on("close", () => gracefullyProcessExitDoNotHang(0)); +} +async function launchBrowserServer(browserName, configFile) { + let options2 = {}; + if (configFile) + options2 = JSON.parse(import_fs48.default.readFileSync(configFile).toString()); + const browserType = playwright[browserName]; + const server = await browserType.launchServer(options2); + console.log(server.wsEndpoint()); +} +var import_fs48, import_path43; +var init_driver = __esm({ + "packages/playwright-core/src/cli/driver.ts"() { + "use strict"; + import_fs48 = __toESM(require("fs")); + import_path43 = __toESM(require("path")); + init_pipeTransport(); + init_processLauncher(); + init_package(); + init_inprocess(); + init_playwrightServer(); + init_server(); + } +}); + +// packages/playwright-core/src/cli/installActions.ts +function printInstalledBrowsers(browsers) { + const browserPaths = /* @__PURE__ */ new Set(); + for (const browser of browsers) + browserPaths.add(browser.browserPath); + console.log(` Browsers:`); + for (const browserPath of [...browserPaths].sort()) + console.log(` ${browserPath}`); + console.log(` References:`); + const references = /* @__PURE__ */ new Set(); + for (const browser of browsers) + references.add(browser.referenceDir); + for (const reference of [...references].sort()) + console.log(` ${reference}`); +} +function printGroupedByPlaywrightVersion(browsers) { + const dirToVersion = /* @__PURE__ */ new Map(); + for (const browser of browsers) { + if (dirToVersion.has(browser.referenceDir)) + continue; + const packageJSON2 = require(import_path44.default.join(browser.referenceDir, "package.json")); + const version3 = packageJSON2.version; + dirToVersion.set(browser.referenceDir, version3); + } + const groupedByPlaywrightMinorVersion = /* @__PURE__ */ new Map(); + for (const browser of browsers) { + const version3 = dirToVersion.get(browser.referenceDir); + let entries = groupedByPlaywrightMinorVersion.get(version3); + if (!entries) { + entries = []; + groupedByPlaywrightMinorVersion.set(version3, entries); + } + entries.push(browser); + } + const sortedVersions = [...groupedByPlaywrightMinorVersion.keys()].sort((a, b) => { + const aComponents = a.split("."); + const bComponents = b.split("."); + const aMajor = parseInt(aComponents[0], 10); + const bMajor = parseInt(bComponents[0], 10); + if (aMajor !== bMajor) + return aMajor - bMajor; + const aMinor = parseInt(aComponents[1], 10); + const bMinor = parseInt(bComponents[1], 10); + if (aMinor !== bMinor) + return aMinor - bMinor; + return aComponents.slice(2).join(".").localeCompare(bComponents.slice(2).join(".")); + }); + for (const version3 of sortedVersions) { + console.log(` +Playwright version: ${version3}`); + printInstalledBrowsers(groupedByPlaywrightMinorVersion.get(version3)); + } +} +async function markDockerImage(dockerImageNameTemplate) { + assert(dockerImageNameTemplate, "dockerImageNameTemplate is required"); + await writeDockerVersion(dockerImageNameTemplate); +} +async function installBrowsers(args, options2) { + if (isLikelyNpxGlobal()) { + console.error(wrapInASCIIBox([ + `WARNING: It looks like you are running 'npx playwright install' without first`, + `installing your project's dependencies.`, + ``, + `To avoid unexpected behavior, please install your dependencies first, and`, + `then run Playwright's install command:`, + ``, + ` npm install`, + ` npx playwright install`, + ``, + `If your project does not yet depend on Playwright, first install the`, + `applicable npm package (most commonly @playwright/test), and`, + `then run Playwright's install command to download the browsers:`, + ``, + ` npm install @playwright/test`, + ` npx playwright install`, + `` + ].join("\n"), 1)); + } + if (options2.shell === false && options2.onlyShell) + throw new Error(`Only one of --no-shell and --only-shell can be specified`); + const shell = options2.shell === false ? "no" : options2.onlyShell ? "only" : void 0; + const executables = registry.resolveBrowsers(args, { shell }); + if (options2.withDeps) + await registry.installDeps(executables, !!options2.dryRun); + if (options2.dryRun && options2.list) + throw new Error(`Only one of --dry-run and --list can be specified`); + if (options2.dryRun) { + for (const executable of executables) { + console.log(registry.calculateDownloadTitle(executable)); + console.log(` Install location: ${executable.directory ?? ""}`); + if (executable.downloadURLs?.length) { + const [url2, ...fallbacks] = executable.downloadURLs; + console.log(` Download url: ${url2}`); + for (let i = 0; i < fallbacks.length; ++i) + console.log(` Download fallback ${i + 1}: ${fallbacks[i]}`); + } + console.log(``); + } + } else if (options2.list) { + const browsers = await registry.listInstalledBrowsers(); + printGroupedByPlaywrightVersion(browsers); + } else { + await registry.install(executables, { force: options2.force }); + await registry.validateHostRequirementsForExecutablesIfNeeded(executables, process.env.PW_LANG_NAME || "javascript").catch((e) => { + e.name = "Playwright Host validation warning"; + console.error(e); + }); + } +} +async function uninstallBrowsers(options2) { + delete process.env.PLAYWRIGHT_SKIP_BROWSER_GC; + await registry.uninstall(!!options2.all).then(({ numberOfBrowsersLeft }) => { + if (!options2.all && numberOfBrowsersLeft > 0) { + console.log("Successfully uninstalled Playwright browsers for the current Playwright installation."); + console.log(`There are still ${numberOfBrowsersLeft} browsers left, used by other Playwright installations. +To uninstall Playwright browsers for all installations, re-run with --all flag.`); + } + }); +} +async function installDeps(args, options2) { + await registry.installDeps(registry.resolveBrowsers(args, {}), !!options2.dryRun); +} +var import_path44; +var init_installActions = __esm({ + "packages/playwright-core/src/cli/installActions.ts"() { + "use strict"; + import_path44 = __toESM(require("path")); + init_ascii(); + init_env(); + init_assert(); + init_registry(); + } +}); + +// packages/playwright-core/src/cli/browserActions.ts +async function launchContext(options2, extraOptions) { + validateOptions(options2); + const browserType = lookupBrowserType(options2); + const launchOptions = extraOptions; + if (options2.channel) + launchOptions.channel = options2.channel; + launchOptions.handleSIGINT = false; + const contextOptions = ( + // Copy the device descriptor since we have to compare and modify the options. + options2.device ? { ...playwright.devices[options2.device] } : {} + ); + if (!extraOptions.headless) + contextOptions.deviceScaleFactor = import_os19.default.platform() === "darwin" ? 2 : 1; + if (browserType.name() === "webkit" && process.platform === "linux") { + delete contextOptions.hasTouch; + delete contextOptions.isMobile; + } + if (contextOptions.isMobile && browserType.name() === "firefox") + contextOptions.isMobile = void 0; + if (options2.blockServiceWorkers) + contextOptions.serviceWorkers = "block"; + if (options2.proxyServer) { + launchOptions.proxy = { + server: options2.proxyServer + }; + if (options2.proxyBypass) + launchOptions.proxy.bypass = options2.proxyBypass; + } + if (options2.viewportSize) { + try { + const [width, height] = options2.viewportSize.split(",").map((n) => +n); + if (isNaN(width) || isNaN(height)) + throw new Error("bad values"); + contextOptions.viewport = { width, height }; + } catch (e) { + throw new Error('Invalid viewport size format: use "width,height", for example --viewport-size="800,600"'); + } + } + if (options2.geolocation) { + try { + const [latitude, longitude] = options2.geolocation.split(",").map((n) => parseFloat(n.trim())); + contextOptions.geolocation = { + latitude, + longitude + }; + } catch (e) { + throw new Error('Invalid geolocation format, should be "lat,long". For example --geolocation="37.819722,-122.478611"'); + } + contextOptions.permissions = ["geolocation"]; + } + if (options2.userAgent) + contextOptions.userAgent = options2.userAgent; + if (options2.lang) + contextOptions.locale = options2.lang; + if (options2.colorScheme) + contextOptions.colorScheme = options2.colorScheme; + if (options2.timezone) + contextOptions.timezoneId = options2.timezone; + if (options2.loadStorage) + contextOptions.storageState = options2.loadStorage; + if (options2.ignoreHttpsErrors) + contextOptions.ignoreHTTPSErrors = true; + if (options2.saveHar) { + contextOptions.recordHar = { path: import_path45.default.resolve(process.cwd(), options2.saveHar), mode: "minimal" }; + if (options2.saveHarGlob) + contextOptions.recordHar.urlFilter = options2.saveHarGlob; + contextOptions.serviceWorkers = "block"; + } + let browser; + let context2; + if (options2.userDataDir) { + context2 = await browserType.launchPersistentContext(options2.userDataDir, { ...launchOptions, ...contextOptions }); + browser = context2.browser(); + } else { + browser = await browserType.launch(launchOptions); + context2 = await browser.newContext(contextOptions); + } + let closingBrowser = false; + async function closeBrowser() { + if (closingBrowser) + return; + closingBrowser = true; + if (options2.saveStorage) + await context2.storageState({ path: options2.saveStorage }).catch((e) => null); + if (options2.saveHar) + await context2.close(); + await browser.close(); + } + context2.on("page", (page) => { + page.on("dialog", () => { + }); + page.on("close", () => { + const hasPage = browser.contexts().some((context3) => context3.pages().length > 0); + if (hasPage) + return; + closeBrowser().catch(() => { + }); + }); + }); + process.on("SIGINT", async () => { + await closeBrowser(); + gracefullyProcessExitDoNotHang(130); + }); + const timeout = options2.timeout ? parseInt(options2.timeout, 10) : 0; + context2.setDefaultTimeout(timeout); + context2.setDefaultNavigationTimeout(timeout); + delete launchOptions.headless; + delete launchOptions.executablePath; + delete launchOptions.handleSIGINT; + delete contextOptions.deviceScaleFactor; + return { browser, browserName: browserType.name(), context: context2, contextOptions, launchOptions, closeBrowser }; +} +async function openPage(context2, url2) { + let page = context2.pages()[0]; + if (!page) + page = await context2.newPage(); + if (url2) { + if (import_fs49.default.existsSync(url2)) + url2 = "file://" + import_path45.default.resolve(url2); + else if (!url2.startsWith("http") && !url2.startsWith("file://") && !url2.startsWith("about:") && !url2.startsWith("data:")) + url2 = "http://" + url2; + await page.goto(url2); + } + return page; +} +async function open6(options2, url2) { + const { context: context2 } = await launchContext(options2, { headless: !!process.env.PWTEST_CLI_HEADLESS, executablePath: process.env.PWTEST_CLI_EXECUTABLE_PATH }); + await context2._exposeConsoleApi(); + await openPage(context2, url2); +} +async function codegen(options2, url2) { + const { target: language, output: outputFile2, testIdAttribute: testIdAttributeName2 } = options2; + const tracesDir = import_path45.default.join(import_os19.default.tmpdir(), `playwright-recorder-trace-${Date.now()}`); + const { context: context2, browser, launchOptions, contextOptions, closeBrowser } = await launchContext(options2, { + headless: !!process.env.PWTEST_CLI_HEADLESS, + executablePath: process.env.PWTEST_CLI_EXECUTABLE_PATH, + tracesDir + }); + const donePromise = new ManualPromise(); + maybeSetupTestHooks(browser, closeBrowser, donePromise); + dotenv.config({ path: "playwright.env" }); + await context2._enableRecorder({ + language, + launchOptions, + contextOptions, + device: options2.device, + saveStorage: options2.saveStorage, + mode: "recording", + testIdAttributeName: testIdAttributeName2, + outputFile: outputFile2 ? import_path45.default.resolve(outputFile2) : void 0, + handleSIGINT: false + }); + await openPage(context2, url2); + donePromise.resolve(); +} +async function maybeSetupTestHooks(browser, closeBrowser, donePromise) { + if (!process.env.PWTEST_CLI_IS_UNDER_TEST) + return; + const logs = []; + debug10.log = (...args) => { + const line = require("util").format(...args) + "\n"; + logs.push(line); + process.stderr.write(line); + }; + browser.on("disconnected", () => { + const hasCrashLine = logs.some((line) => line.includes("process did exit:") && !line.includes("process did exit: exitCode=0, signal=null")); + if (hasCrashLine) { + process.stderr.write("Detected browser crash.\n"); + gracefullyProcessExitDoNotHang(1); + } + }); + const close3 = async () => { + await donePromise; + await closeBrowser(); + }; + if (process.env.PWTEST_CLI_EXIT_AFTER_TIMEOUT) { + setTimeout(close3, +process.env.PWTEST_CLI_EXIT_AFTER_TIMEOUT); + return; + } + let stdin = ""; + process.stdin.on("data", (data) => { + stdin += data.toString(); + if (stdin.startsWith("exit")) { + process.stdin.destroy(); + close3(); + } + }); +} +async function waitForPage(page, captureOptions) { + if (captureOptions.waitForSelector) { + console.log(`Waiting for selector ${captureOptions.waitForSelector}...`); + await page.waitForSelector(captureOptions.waitForSelector); + } + if (captureOptions.waitForTimeout) { + console.log(`Waiting for timeout ${captureOptions.waitForTimeout}...`); + await page.waitForTimeout(parseInt(captureOptions.waitForTimeout, 10)); + } +} +async function screenshot3(options2, captureOptions, url2, path59) { + const { context: context2 } = await launchContext(options2, { headless: true }); + console.log("Navigating to " + url2); + const page = await openPage(context2, url2); + await waitForPage(page, captureOptions); + console.log("Capturing screenshot into " + path59); + await page.screenshot({ path: path59, fullPage: !!captureOptions.fullPage }); + await page.close(); +} +async function pdf2(options2, captureOptions, url2, path59) { + if (options2.browser !== "chromium") + throw new Error("PDF creation is only working with Chromium"); + const { context: context2 } = await launchContext({ ...options2, browser: "chromium" }, { headless: true }); + console.log("Navigating to " + url2); + const page = await openPage(context2, url2); + await waitForPage(page, captureOptions); + console.log("Saving as pdf into " + path59); + await page.pdf({ path: path59, format: captureOptions.paperFormat }); + await page.close(); +} +function lookupBrowserType(options2) { + let name = options2.browser; + if (options2.device) { + const device = playwright.devices[options2.device]; + name = device.defaultBrowserType; + } + let browserType; + switch (name) { + case "chromium": + browserType = playwright.chromium; + break; + case "webkit": + browserType = playwright.webkit; + break; + case "firefox": + browserType = playwright.firefox; + break; + case "cr": + browserType = playwright.chromium; + break; + case "wk": + browserType = playwright.webkit; + break; + case "ff": + browserType = playwright.firefox; + break; + } + if (browserType) + return browserType; + program.help(); +} +function validateOptions(options2) { + if (options2.device && !(options2.device in playwright.devices)) { + const lines = [`Device descriptor not found: '${options2.device}', available devices are:`]; + for (const name in playwright.devices) + lines.push(` "${name}"`); + throw new Error(lines.join("\n")); + } + if (options2.colorScheme && !["light", "dark"].includes(options2.colorScheme)) + throw new Error('Invalid color scheme, should be one of "light", "dark"'); +} +var import_fs49, import_os19, import_path45, debug10, dotenv, program; +var init_browserActions = __esm({ + "packages/playwright-core/src/cli/browserActions.ts"() { + "use strict"; + import_fs49 = __toESM(require("fs")); + import_os19 = __toESM(require("os")); + import_path45 = __toESM(require("path")); + init_processLauncher(); + init_manualPromise(); + init_inprocess(); + debug10 = require("./utilsBundle").debug; + dotenv = require("./utilsBundle").dotenv; + ({ program } = require("./utilsBundle")); + } +}); + +// packages/playwright-core/src/tools/utils/extension.ts +async function isPlaywrightExtensionInstalled(userDataDir) { + let entries; + try { + entries = await import_fs50.default.promises.readdir(userDataDir); + } catch { + return false; + } + for (const entry of entries) { + if (entry !== "Default" && !entry.startsWith("Profile ")) + continue; + if (await isExtensionInstalledInProfile(import_path46.default.join(userDataDir, entry))) + return true; + } + return false; +} +async function isExtensionInstalledInProfile(profileDir2) { + if (await pathExists(import_path46.default.join(profileDir2, "Extensions", playwrightExtensionId))) + return true; + try { + const prefs = await import_fs50.default.promises.readFile(import_path46.default.join(profileDir2, "Preferences"), "utf-8"); + return prefs.includes(`"${playwrightExtensionId}"`); + } catch { + return false; + } +} +async function pathExists(p) { + try { + await import_fs50.default.promises.access(p); + return true; + } catch { + return false; + } +} +var import_fs50, import_path46, playwrightExtensionId, playwrightExtensionInstallUrl; +var init_extension = __esm({ + "packages/playwright-core/src/tools/utils/extension.ts"() { + "use strict"; + import_fs50 = __toESM(require("fs")); + import_path46 = __toESM(require("path")); + playwrightExtensionId = "mmlmfjhmonkocbjadbfplnigmagldckm"; + playwrightExtensionInstallUrl = `https://chromewebstore.google.com/detail/playwright-extension/${playwrightExtensionId}`; + } +}); + +// packages/playwright-core/src/tools/cli-client/channelSessions.ts +function isKnownChannel(name) { + return channelToUserDataDir.has(name); +} +async function listChannelSessions() { + if (process.env.PWTEST_CLI_CHANNEL_SCAN_DISABLED_FOR_TEST) + return []; + const result2 = []; + for (const [channel, dirs] of channelToUserDataDir) { + const userDataDir = dirs[process.platform]; + if (!userDataDir) + continue; + if (!await pathExists2(userDataDir)) + continue; + const [endpoint, extensionInstalled] = await Promise.all([ + readEndpoint(userDataDir), + isPlaywrightExtensionInstalled(userDataDir) + ]); + result2.push({ channel, userDataDir, endpoint, extensionInstalled }); + } + return result2; +} +async function pathExists2(p) { + try { + await import_fs51.default.promises.access(p); + return true; + } catch { + return false; + } +} +async function readEndpoint(userDataDir) { + let contents; + try { + contents = await import_fs51.default.promises.readFile(import_path47.default.join(userDataDir, "DevToolsActivePort"), "utf-8"); + } catch { + return void 0; + } + const port = parseInt(contents.trim().split("\n")[0], 10); + if (!Number.isFinite(port)) + return void 0; + if (!await isPortOpen(port)) + return void 0; + return `http://localhost:${port}`; +} +async function isPortOpen(port) { + return new Promise((resolve) => { + const socket = import_net8.default.createConnection(port, "127.0.0.1"); + const done = (value2) => { + socket.destroy(); + resolve(value2); + }; + socket.once("connect", () => done(true)); + socket.once("error", () => done(false)); + socket.setTimeout(250, () => done(false)); + }); +} +var import_fs51, import_net8, import_os20, import_path47, channelToUserDataDir; +var init_channelSessions = __esm({ + "packages/playwright-core/src/tools/cli-client/channelSessions.ts"() { + "use strict"; + import_fs51 = __toESM(require("fs")); + import_net8 = __toESM(require("net")); + import_os20 = __toESM(require("os")); + import_path47 = __toESM(require("path")); + init_extension(); + channelToUserDataDir = /* @__PURE__ */ new Map([ + ["chrome", { + "linux": import_path47.default.join(import_os20.default.homedir(), ".config", "google-chrome"), + "darwin": import_path47.default.join(import_os20.default.homedir(), "Library", "Application Support", "Google", "Chrome"), + "win32": import_path47.default.join(process.env.LOCALAPPDATA || import_path47.default.join(import_os20.default.homedir(), "AppData", "Local"), "Google", "Chrome", "User Data") + }], + ["chrome-beta", { + "linux": import_path47.default.join(import_os20.default.homedir(), ".config", "google-chrome-beta"), + "darwin": import_path47.default.join(import_os20.default.homedir(), "Library", "Application Support", "Google", "Chrome Beta"), + "win32": import_path47.default.join(process.env.LOCALAPPDATA || import_path47.default.join(import_os20.default.homedir(), "AppData", "Local"), "Google", "Chrome Beta", "User Data") + }], + ["chrome-dev", { + "linux": import_path47.default.join(import_os20.default.homedir(), ".config", "google-chrome-unstable"), + "darwin": import_path47.default.join(import_os20.default.homedir(), "Library", "Application Support", "Google", "Chrome Dev"), + "win32": import_path47.default.join(process.env.LOCALAPPDATA || import_path47.default.join(import_os20.default.homedir(), "AppData", "Local"), "Google", "Chrome Dev", "User Data") + }], + ["chrome-canary", { + "linux": import_path47.default.join(import_os20.default.homedir(), ".config", "google-chrome-canary"), + "darwin": import_path47.default.join(import_os20.default.homedir(), "Library", "Application Support", "Google", "Chrome Canary"), + "win32": import_path47.default.join(process.env.LOCALAPPDATA || import_path47.default.join(import_os20.default.homedir(), "AppData", "Local"), "Google", "Chrome SxS", "User Data") + }], + ["msedge", { + "linux": import_path47.default.join(import_os20.default.homedir(), ".config", "microsoft-edge"), + "darwin": import_path47.default.join(import_os20.default.homedir(), "Library", "Application Support", "Microsoft Edge"), + "win32": import_path47.default.join(process.env.LOCALAPPDATA || import_path47.default.join(import_os20.default.homedir(), "AppData", "Local"), "Microsoft", "Edge", "User Data") + }], + ["msedge-beta", { + "linux": import_path47.default.join(import_os20.default.homedir(), ".config", "microsoft-edge-beta"), + "darwin": import_path47.default.join(import_os20.default.homedir(), "Library", "Application Support", "Microsoft Edge Beta"), + "win32": import_path47.default.join(process.env.LOCALAPPDATA || import_path47.default.join(import_os20.default.homedir(), "AppData", "Local"), "Microsoft", "Edge Beta", "User Data") + }], + ["msedge-dev", { + "linux": import_path47.default.join(import_os20.default.homedir(), ".config", "microsoft-edge-dev"), + "darwin": import_path47.default.join(import_os20.default.homedir(), "Library", "Application Support", "Microsoft Edge Dev"), + "win32": import_path47.default.join(process.env.LOCALAPPDATA || import_path47.default.join(import_os20.default.homedir(), "AppData", "Local"), "Microsoft", "Edge Dev", "User Data") + }], + ["msedge-canary", { + "linux": import_path47.default.join(import_os20.default.homedir(), ".config", "microsoft-edge-canary"), + "darwin": import_path47.default.join(import_os20.default.homedir(), "Library", "Application Support", "Microsoft Edge Canary"), + "win32": import_path47.default.join(process.env.LOCALAPPDATA || import_path47.default.join(import_os20.default.homedir(), "AppData", "Local"), "Microsoft", "Edge SxS", "User Data") + }] + ]); + } +}); + +// packages/playwright-core/src/tools/cli-client/output.ts +function parseJsonText(text2) { + try { + return JSON.parse(text2); + } catch { + return text2; + } +} +function renderBrowser(browser) { + const lines = [`- ${browser.name}:`]; + lines.push(` - status: ${browser.status}`); + if (browser.status === "open" && !browser.compatible) + lines.push(` - version: v${browser.version} [incompatible please re-open]`); + if (browser.browserType) + lines.push(` - browser-type: ${browser.browserType}${browser.attached ? " (attached)" : ""}`); + if (!browser.attached) { + if (browser.userDataDir === null) + lines.push(` - user-data-dir: `); + else + lines.push(` - user-data-dir: ${browser.userDataDir}`); + if (browser.headed !== void 0) + lines.push(` - headed: ${browser.headed}`); + } + return lines.join("\n"); +} +function renderServer(server) { + const lines = [`- browser "${server.title}":`]; + lines.push(` - browser: ${server.browser.browserName}`); + lines.push(` - version: v${server.playwrightVersion}`); + if (server.browser.userDataDir) + lines.push(` - data-dir: ${server.browser.userDataDir}`); + else + lines.push(` - data-dir: `); + lines.push(` - run \`playwright-cli attach "${server.title}"\` to attach`); + return lines.join("\n"); +} +function renderChannelSession(session2) { + const lines = [`- ${session2.channel}:`]; + lines.push(` - data-dir: ${session2.userDataDir}`); + if (session2.extensionInstalled) + lines.push(` - attach (extension): \`playwright-cli attach --extension=${session2.channel}\``); + else + lines.push(` - attach (extension): install at ${playwrightExtensionInstallUrl}`); + if (session2.endpoint) { + lines.push(` - attach (remote debugging): \`playwright-cli attach --cdp=${session2.channel}\``); + } else { + const inspectScheme = session2.channel.startsWith("msedge") ? "edge" : "chrome"; + lines.push(` - attach (remote debugging): enable at ${inspectScheme}://inspect/#remote-debugging`); + } + return lines.join("\n"); +} +var import_path48, TextOutput, JsonOutput; +var init_output = __esm({ + "packages/playwright-core/src/tools/cli-client/output.ts"() { + "use strict"; + import_path48 = __toESM(require("path")); + init_extension(); + TextOutput = class { + constructor() { + this.json = false; + } + version(v) { + console.log(v); + } + help(text2) { + console.log(text2); + } + errorUnknownCommand(name, globalHelp) { + console.error(`Unknown command: ${name} +`); + console.log(globalHelp); + return process.exit(1); + } + errorUnknownOption(opts, commandHelp) { + console.error(`Unknown option${opts.length > 1 ? "s" : ""}: ${opts.map((f) => `--${f}`).join(", ")}`); + console.log(""); + console.log(commandHelp); + return process.exit(1); + } + errorTooManyArguments(expected, received, commandHelp) { + console.error(`error: too many arguments: expected ${expected}, received ${received}`); + console.log(""); + console.log(commandHelp); + return process.exit(1); + } + errorAttachConflict() { + console.error(`Error: cannot use target name with --cdp, --endpoint, or --extension`); + return process.exit(1); + } + errorDetachNotAttached(session2) { + console.error(`Error: session '${session2}' was not attached; use \`playwright-cli${session2 !== "default" ? ` -s=${session2}` : ""} close\` to stop it.`); + return process.exit(1); + } + errorBrowserNotOpenForTool(session2) { + console.log(`The browser '${session2}' is not open, please run open first`); + console.log(""); + console.log(` playwright-cli${session2 !== "default" ? ` -s=${session2}` : ""} open [params]`); + return process.exit(1); + } + errorAttachNoTarget() { + console.error(`Error: no target specified for attach command; use one of [name], --cdp, --endpoint, or --extension to specify the target to attach to.`); + return process.exit(1); + } + list({ all, browsers, servers, channelSessions }) { + const byWorkspace = /* @__PURE__ */ new Map(); + for (const browser of browsers) { + let list = byWorkspace.get(browser.workspace); + if (!list) { + list = []; + byWorkspace.set(browser.workspace, list); + } + list.push(browser); + } + let count = 0; + for (const [workspaceKey, list] of byWorkspace) { + if (count === 0) + console.log("### Browsers"); + if (all) + console.log(`${import_path48.default.relative(process.cwd(), workspaceKey) || "/"}:`); + for (const browser of list) + console.log(renderBrowser(browser)); + count += list.length; + } + if (!all) { + if (!count) + console.log(" (no browsers)"); + return; + } + if (servers?.length) { + if (count) + console.log(""); + console.log("### Browser servers available for attach"); + const serversByWorkspace = /* @__PURE__ */ new Map(); + for (const server of servers) { + let list = serversByWorkspace.get(server.workspaceDir ?? ""); + if (!list) { + list = []; + serversByWorkspace.set(server.workspaceDir ?? "", list); + } + list.push(server); + } + for (const [workspaceKey, list] of serversByWorkspace) { + if (workspaceKey) + console.log(`${import_path48.default.relative(process.cwd(), workspaceKey) || "/"}:`); + for (const server of list) + console.log(renderServer(server)); + } + count += servers.length; + } + if (!count) + console.log(" (no browsers)"); + if (channelSessions?.length) { + console.log(""); + console.log("### Browsers available to attach via CDP"); + for (const session2 of channelSessions) + console.log(renderChannelSession(session2)); + } + } + closeAll(_sessions) { + } + deleteData(session2, result2) { + if (!result2.existed) { + console.log(`No user data found for browser '${session2}'.`); + return; + } + if (result2.deletedUserDataDir) + console.log(`Deleted user data for browser '${session2}'.`); + } + killAll(pids) { + for (const pid of pids) + console.log(`Killed daemon process ${pid}`); + if (pids.length === 0) + console.log("No daemon processes found."); + else + console.log(`Killed ${pids.length} daemon process${pids.length === 1 ? "" : "es"}.`); + } + open(session2, pid, toolResult) { + console.log(`### Browser \`${session2}\` opened with pid ${pid}.`); + if (toolResult) + console.log(toolResult); + } + attach(session2, pid, endpoint, toolResult) { + if (endpoint) { + console.log(`### Session \`${session2}\` created, attached to \`${endpoint}\`.`); + console.log(`Run commands with: playwright-cli --s=${session2} `); + console.log(""); + } else { + console.log(`### Browser \`${session2}\` opened with pid ${pid}.`); + } + if (toolResult) + console.log(toolResult); + } + close(session2, wasOpen) { + if (!wasOpen) { + console.log(`Browser '${session2}' is not open.`); + return; + } + console.log(`Browser '${session2}' closed +`); + } + detach(session2, wasAttached) { + if (!wasAttached) { + console.log(`Browser '${session2}' is not attached.`); + return; + } + console.log(`Browser '${session2}' detached +`); + } + installed() { + } + show(_session, pid) { + if (process.env.PWTEST_PRINT_DASHBOARD_PID_FOR_TEST) + console.log(`### Dashboard opened with pid ${pid}.`); + } + toolResult(text2) { + console.log(text2); + } + installStdio() { + return "inherit"; + } + }; + JsonOutput = class { + constructor() { + this.json = true; + } + version(v) { + this._emit({ version: v }); + } + help(text2) { + this._emit({ help: text2 }); + } + errorUnknownCommand(name, _globalHelp) { + this._emit({ isError: true, error: `Unknown command: ${name}` }); + return process.exit(1); + } + errorUnknownOption(opts, _commandHelp) { + this._emit({ isError: true, error: `Unknown option${opts.length > 1 ? "s" : ""}: ${opts.map((f) => `--${f}`).join(", ")}` }); + return process.exit(1); + } + errorTooManyArguments(expected, received, _commandHelp) { + this._emit({ isError: true, error: `error: too many arguments: expected ${expected}, received ${received}` }); + return process.exit(1); + } + errorAttachConflict() { + this._emit({ isError: true, error: `cannot use target name with --cdp, --endpoint, or --extension` }); + return process.exit(1); + } + errorDetachNotAttached(session2) { + this._emit({ isError: true, error: `session '${session2}' was not attached; use close to stop it.` }); + return process.exit(1); + } + errorBrowserNotOpenForTool(session2) { + this._emit({ isError: true, error: `The browser '${session2}' is not open, please run open first` }); + return process.exit(1); + } + errorAttachNoTarget() { + this._emit({ isError: true, error: `no target specified for attach command; use one of [name], --cdp, --endpoint, or --extension to specify the target to attach to.` }); + return process.exit(1); + } + list({ all, browsers, servers, channelSessions }) { + const payload = { browsers }; + if (all) { + payload.servers = servers ?? []; + payload.channelSessions = channelSessions ?? []; + } + this._emit(payload); + } + closeAll(sessions) { + this._emit({ closed: sessions }); + } + deleteData(session2, result2) { + this._emit({ session: session2, deleted: result2.existed }); + } + killAll(pids) { + this._emit({ killed: pids.length, pids }); + } + open(session2, pid, toolResult) { + this._emit({ session: session2, pid, result: parseJsonText(toolResult) }); + } + attach(session2, pid, endpoint, toolResult) { + this._emit({ + session: session2, + pid, + ...endpoint ? { endpoint } : {}, + result: parseJsonText(toolResult) + }); + } + close(session2, wasOpen) { + this._emit({ session: session2, status: wasOpen ? "closed" : "not-open" }); + } + detach(session2, wasAttached) { + this._emit({ session: session2, status: wasAttached ? "detached" : "not-attached" }); + } + installed() { + this._emit({ installed: true }); + } + show(session2, pid) { + this._emit({ session: session2, pid }); + } + toolResult(text2) { + console.log(text2); + } + installStdio() { + return "ignore"; + } + _emit(value2) { + console.log(JSON.stringify(value2, null, 2)); + } + }; + } +}); + +// packages/playwright-core/src/tools/cli-client/registry.ts +function clientKey(clientInfo) { + return clientInfo.workspaceDir || clientInfo.workspaceDirHash; +} +function createClientInfo() { + const workspaceDir = findWorkspaceDir(process.cwd()); + const version3 = process.env.PLAYWRIGHT_CLI_VERSION_FOR_TEST || packageJSON.version; + const hash = import_crypto24.default.createHash("sha1"); + hash.update(workspaceDir || packageRoot); + const workspaceDirHash = hash.digest("hex").substring(0, 16); + return { + version: version3, + workspaceDir, + workspaceDirHash, + daemonProfilesDir: daemonProfilesDir(workspaceDirHash), + homeDir: import_os21.default.homedir() + }; +} +function findWorkspaceDir(startDir) { + let dir = startDir; + for (let i = 0; i < 10; i++) { + if (import_fs52.default.existsSync(import_path49.default.join(dir, ".playwright"))) + return dir; + const parentDir = import_path49.default.dirname(dir); + if (parentDir === dir) + break; + dir = parentDir; + } + return void 0; +} +function explicitSessionName(sessionName) { + return sessionName || process.env.PLAYWRIGHT_CLI_SESSION; +} +function resolveSessionName(sessionName) { + return explicitSessionName(sessionName) || "default"; +} +var import_crypto24, import_fs52, import_os21, import_path49, Registry2, baseDaemonDir, daemonProfilesDir; +var init_registry2 = __esm({ + "packages/playwright-core/src/tools/cli-client/registry.ts"() { + "use strict"; + import_crypto24 = __toESM(require("crypto")); + import_fs52 = __toESM(require("fs")); + import_os21 = __toESM(require("os")); + import_path49 = __toESM(require("path")); + init_package(); + Registry2 = class _Registry { + constructor(files) { + this._files = files; + } + entry(clientInfo, sessionName) { + const key = clientKey(clientInfo); + const entries = this._files.get(key) || []; + return entries.find((entry) => entry.config.name === sessionName); + } + entries(clientInfo) { + return this._files.get(clientKey(clientInfo)) || []; + } + entryMap() { + return this._files; + } + async loadEntry(clientInfo, sessionName) { + const entry = await _Registry._loadSessionEntry(clientInfo.daemonProfilesDir, sessionName + ".session"); + if (!entry) + throw new Error(`Could not start the session "${sessionName}"`); + const key = clientKey(clientInfo); + let list = this._files.get(key); + if (!list) { + list = []; + this._files.set(key, list); + } + const oldIndex = list.findIndex((e) => e.config.name === sessionName); + if (oldIndex !== -1) + list.splice(oldIndex, 1); + list.push(entry); + return entry; + } + static async _loadSessionEntry(daemonDir, file) { + try { + const fileName = import_path49.default.join(daemonDir, file); + const data = await import_fs52.default.promises.readFile(fileName, "utf-8"); + const config = JSON.parse(data); + if (!config.name) + config.name = import_path49.default.basename(file, ".session"); + if (!config.timestamp) + config.timestamp = 0; + return { file: fileName, config, daemonDir }; + } catch { + return void 0; + } + } + static async load() { + const sessions = /* @__PURE__ */ new Map(); + const hashDirs = await import_fs52.default.promises.readdir(baseDaemonDir).catch(() => []); + for (const workspaceDirHash of hashDirs) { + const daemonDir = import_path49.default.join(baseDaemonDir, workspaceDirHash); + const stat = await import_fs52.default.promises.stat(daemonDir); + if (!stat.isDirectory()) + continue; + const files = await import_fs52.default.promises.readdir(daemonDir).catch(() => []); + for (const file of files) { + if (!file.endsWith(".session")) + continue; + const entry = await _Registry._loadSessionEntry(daemonDir, file); + if (!entry) + continue; + const key = entry.config.workspaceDir || workspaceDirHash; + let list = sessions.get(key); + if (!list) { + list = []; + sessions.set(key, list); + } + list.push(entry); + } + } + return new _Registry(sessions); + } + }; + baseDaemonDir = (() => { + if (process.env.PLAYWRIGHT_DAEMON_SESSION_DIR) + return process.env.PLAYWRIGHT_DAEMON_SESSION_DIR; + let localCacheDir; + if (process.platform === "linux") + localCacheDir = process.env.XDG_CACHE_HOME || import_path49.default.join(import_os21.default.homedir(), ".cache"); + if (process.platform === "darwin") + localCacheDir = import_path49.default.join(import_os21.default.homedir(), "Library", "Caches"); + if (process.platform === "win32") + localCacheDir = process.env.LOCALAPPDATA || import_path49.default.join(import_os21.default.homedir(), "AppData", "Local"); + if (!localCacheDir) + throw new Error("Unsupported platform: " + process.platform); + return import_path49.default.join(localCacheDir, "ms-playwright", "daemon"); + })(); + daemonProfilesDir = (workspaceDirHash) => { + return import_path49.default.join(baseDaemonDir, workspaceDirHash); + }; + } +}); + +// packages/playwright-core/src/tools/utils/socketConnection.ts +function compareSemver(a, b) { + const aBase = a.replace(/-.*$/, ""); + const bBase = b.replace(/-.*$/, ""); + const aParts = aBase.split(".").map(Number); + const bParts = bBase.split(".").map(Number); + for (let i = 0; i < 3; i++) { + if (aParts[i] > bParts[i]) + return 1; + if (aParts[i] < bParts[i]) + return -1; + } + const aTimestamp = parseSuffixTimestamp(a); + const bTimestamp = parseSuffixTimestamp(b); + if (aTimestamp > bTimestamp) + return 1; + if (aTimestamp < bTimestamp) + return -1; + return 0; +} +function parseSuffixTimestamp(version3) { + const match = version3.match(/^\d+\.\d+\.\d+-(?:alpha|beta)-(.+)$/); + if (!match) + return Infinity; + const suffix = match[1]; + if (/^\d{4}-\d{2}-\d{2}$/.test(suffix)) + return new Date(suffix).getTime(); + return Number(suffix); +} +var SocketConnection; +var init_socketConnection = __esm({ + "packages/playwright-core/src/tools/utils/socketConnection.ts"() { + "use strict"; + SocketConnection = class { + constructor(socket) { + this._pendingBuffers = []; + this._socket = socket; + socket.on("data", (buffer) => this._onData(buffer)); + socket.on("close", () => { + this.onclose?.(); + }); + socket.on("error", (e) => console.error(`error: ${e.message}`)); + } + async send(message) { + await new Promise((resolve, reject) => { + this._socket.write(`${JSON.stringify(message)} +`, (error) => { + if (error) + reject(error); + else + resolve(void 0); + }); + }); + } + close() { + this._socket.destroy(); + } + _onData(buffer) { + let end = buffer.indexOf("\n"); + if (end === -1) { + this._pendingBuffers.push(buffer); + return; + } + this._pendingBuffers.push(buffer.slice(0, end)); + const message = Buffer.concat(this._pendingBuffers).toString(); + this._dispatchMessage(message); + let start3 = end + 1; + end = buffer.indexOf("\n", start3); + while (end !== -1) { + const message2 = buffer.toString(void 0, start3, end); + this._dispatchMessage(message2); + start3 = end + 1; + end = buffer.indexOf("\n", start3); + } + this._pendingBuffers = [buffer.slice(start3)]; + } + _dispatchMessage(message) { + try { + this.onmessage?.(JSON.parse(message)); + } catch (e) { + console.error("failed to dispatch message", e); + } + } + }; + } +}); + +// packages/playwright-core/src/tools/cli-client/session.ts +var import_child_process4, import_fs53, import_net9, import_os22, import_path50, Session2, SocketConnectionClient; +var init_session = __esm({ + "packages/playwright-core/src/tools/cli-client/session.ts"() { + "use strict"; + import_child_process4 = require("child_process"); + import_fs53 = __toESM(require("fs")); + import_net9 = __toESM(require("net")); + import_os22 = __toESM(require("os")); + import_path50 = __toESM(require("path")); + init_package(); + init_socketConnection(); + init_registry2(); + Session2 = class { + constructor(sessionFile) { + this.config = sessionFile.config; + this.name = this.config.name; + this._sessionFile = sessionFile; + } + isCompatible(clientInfo) { + return compareSemver(clientInfo.version, this.config.version) >= 0; + } + async run(clientInfo, args, options2) { + if (!this.isCompatible(clientInfo)) + throw new Error(`Client is v${clientInfo.version}, session '${this.name}' is v${this.config.version}. Run + + playwright-cli${this.name !== "default" ? ` -s=${this.name}` : ""} open + +to restart the browser session.`); + const { socket } = await this._connect(); + if (!socket) + throw new Error(`Browser '${this.name}' is not open. Run + + playwright-cli${this.name !== "default" ? ` -s=${this.name}` : ""} open + +to start the browser session.`); + return await SocketConnectionClient.sendAndClose(socket, "run", { args, cwd: process.cwd(), raw: options2?.raw, json: options2?.json }); + } + async stop() { + if (!await this.canConnect()) + return { wasOpen: false }; + await this._stopDaemon(); + return { wasOpen: true }; + } + async deleteData() { + await this.stop(); + const dataDirs = await import_fs53.default.promises.readdir(this._sessionFile.daemonDir).catch(() => []); + const matchingEntries = dataDirs.filter((file) => file === `${this.name}.session` || file.startsWith(`ud-${this.name}-`)); + if (matchingEntries.length === 0) + return { existed: false, deletedUserDataDir: false }; + let deletedUserDataDir = false; + for (const entry of matchingEntries) { + const userDataDir = import_path50.default.resolve(this._sessionFile.daemonDir, entry); + for (let i = 0; i < 5; i++) { + try { + await import_fs53.default.promises.rm(userDataDir, { recursive: true }); + if (entry.startsWith("ud-")) + deletedUserDataDir = true; + break; + } catch (e) { + if (e.code === "ENOENT") + break; + await new Promise((resolve) => setTimeout(resolve, 1e3)); + if (i === 4) + throw e; + } + } + } + return { existed: true, deletedUserDataDir }; + } + async _connect() { + return await new Promise((resolve) => { + const socket = import_net9.default.createConnection(this.config.socketPath, () => { + resolve({ socket }); + }); + socket.on("error", (error) => { + if (import_os22.default.platform() !== "win32") + void import_fs53.default.promises.unlink(this.config.socketPath).catch(() => { + }).then(() => resolve({ error })); + else + resolve({ error }); + }); + }); + } + async canConnect() { + const { socket } = await this._connect(); + if (socket) { + socket.destroy(); + return true; + } + return false; + } + static async startDaemon(clientInfo, cliArgs, mode) { + await import_fs53.default.promises.mkdir(clientInfo.daemonProfilesDir, { recursive: true }); + const cliPath = libPath("entry", "cliDaemon.js"); + const sessionName = resolveSessionName(cliArgs.session); + const errLog = import_path50.default.join(clientInfo.daemonProfilesDir, sessionName + ".err"); + const err = import_fs53.default.openSync(errLog, "w"); + const args = [ + cliPath, + sessionName + ]; + if (cliArgs.headed) + args.push("--headed"); + if (cliArgs.extension) + args.push("--extension"); + if (cliArgs.browser) + args.push(`--browser=${cliArgs.browser}`); + if (cliArgs.persistent) + args.push("--persistent"); + if (cliArgs.profile) + args.push(`--profile=${cliArgs.profile}`); + if (cliArgs.config) + args.push(`--config=${cliArgs.config}`); + if (cliArgs.cdp) + args.push(`--cdp=${cliArgs.cdp}`); + if (cliArgs.endpoint) + args.push(`--endpoint=${cliArgs.endpoint}`); + else if (mode === "attach" && process.env.PLAYWRIGHT_CLI_SESSION) + args.push(`--endpoint=${process.env.PLAYWRIGHT_CLI_SESSION}`); + const child = (0, import_child_process4.spawn)(process.execPath, args, { + detached: true, + stdio: ["ignore", "pipe", err], + cwd: process.cwd() + // Will be used as root. + }); + let signalled = false; + const sigintHandler2 = () => { + signalled = true; + child.kill("SIGINT"); + }; + const sigtermHandler2 = () => { + signalled = true; + child.kill("SIGTERM"); + }; + process.on("SIGINT", sigintHandler2); + process.on("SIGTERM", sigtermHandler2); + let outLog = ""; + const rejectWithPid = (reject, message) => reject(Object.assign(new Error(`Daemon pid=${child.pid}: ${message}`), { daemonPid: child.pid })); + await new Promise((resolve, reject) => { + child.stdout.on("data", (data) => { + outLog += data.toString(); + if (!outLog.includes("")) + return; + const errorMatch = outLog.match(/### Error\n([\s\S]*)/); + const error = errorMatch ? errorMatch[1].trim() : void 0; + if (error) { + const errLogContent = import_fs53.default.readFileSync(errLog, "utf-8"); + rejectWithPid(reject, error + (errLogContent ? "\n" + errLogContent : "")); + } + const successMatch = outLog.match(/### Success\nDaemon listening on (.*)\n/); + if (successMatch) + resolve(); + }); + child.on("close", (code) => { + if (!signalled) { + const errLogContent = import_fs53.default.readFileSync(errLog, "utf-8"); + rejectWithPid(reject, `Daemon process exited with code ${code}` + (errLogContent ? "\n" + errLogContent : "")); + } + }); + }); + process.off("SIGINT", sigintHandler2); + process.off("SIGTERM", sigtermHandler2); + child.stdout.destroy(); + child.unref(); + return { pid: child.pid, sessionName, endpoint: cliArgs.endpoint }; + } + async _stopDaemon() { + const { socket } = await this._connect(); + if (!socket) + return; + let error; + await SocketConnectionClient.sendAndClose(socket, "stop", {}).catch((e) => error = e); + if (error && !error?.message?.includes("Session closed")) + throw error; + } + async deleteSessionConfig() { + await import_fs53.default.promises.rm(this._sessionFile.file).catch(() => { + }); + } + }; + SocketConnectionClient = class _SocketConnectionClient { + constructor(socket) { + this._nextMessageId = 1; + this._callbacks = /* @__PURE__ */ new Map(); + this._connection = new SocketConnection(socket); + this._connection.onmessage = (message) => this._onMessage(message); + this._connection.onclose = () => this._rejectCallbacks(); + } + async send(method, params2 = {}) { + const messageId = this._nextMessageId++; + const message = { + id: messageId, + method, + params: params2 + }; + const responsePromise = new Promise((resolve, reject) => { + this._callbacks.set(messageId, { resolve, reject, method, params: params2 }); + }); + const [result2] = await Promise.all([responsePromise, this._connection.send(message)]); + return result2; + } + static async sendAndClose(socket, method, params2 = {}) { + const connection = new _SocketConnectionClient(socket); + try { + return await connection.send(method, params2); + } finally { + connection.close(); + } + } + close() { + this._connection.close(); + } + _onMessage(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.reject(new Error(object.error)); + else + callback.resolve(object.result); + } else if (object.id) { + throw new Error(`Unexpected message id: ${object.id}`); + } else { + throw new Error(`Unexpected message without id: ${JSON.stringify(object)}`); + } + } + _rejectCallbacks() { + for (const callback of this._callbacks.values()) + callback.reject(new Error("Session closed")); + this._callbacks.clear(); + } + }; + } +}); + +// packages/playwright-core/src/tools/cli-client/program.ts +async function program2(options2) { + const clientInfo = createClientInfo(); + const help = require(libPath("tools", "cli-client", "help.json")); + const argv = process.argv.slice(2); + const boolean = [...help.booleanOptions, ...booleanOptions]; + const args = minimist(argv, { boolean, string: ["_"] }); + if (args.s) { + args.session = args.s; + delete args.s; + } + const output = args.json ? new JsonOutput() : new TextOutput(); + const commandName = args._?.[0]; + if (args.version || args.v) { + output.version(options2?.embedderVersion ?? clientInfo.version); + process.exit(0); + } + const command = commandName && help.commands[commandName]; + if (args.help || args.h || !commandName) { + if (command) { + output.help(command.help); + } else { + const lines = ["playwright-cli - run playwright mcp commands from terminal"]; + if (process.env.CLAUDECODE || process.env.COPILOT_CLI) + lines.push(`Agent skill: ${import_path51.default.relative(process.cwd(), libPath("tools", "cli-client", "skill", "SKILL.md"))}`); + lines.push(help.global); + output.help(lines.join("\n\n")); + } + process.exit(0); + } + if (!command) + output.errorUnknownCommand(commandName, help.global); + validateFlags(args, command, output); + validateArgs(args, command, output); + const registry2 = await Registry2.load(); + const sessionName = resolveSessionName(args.session); + switch (commandName) { + case "list": { + const data = await collectList(registry2, clientInfo, !!args.all); + output.list(data); + return; + } + case "close-all": { + const entries = registry2.entries(clientInfo); + const closed = []; + for (const entry of entries) { + await new Session2(entry).stop(); + closed.push(entry.config.name); + } + output.closeAll(closed); + return; + } + case "delete-data": { + const entry = registry2.entry(clientInfo, sessionName); + if (!entry) { + output.deleteData(sessionName, { existed: false, deletedUserDataDir: false }); + return; + } + const result2 = await new Session2(entry).deleteData(); + output.deleteData(sessionName, result2); + return; + } + case "kill-all": { + const pids = await killAllDaemons(); + output.killAll(pids); + return; + } + case "open": { + const { pid } = await startSession(sessionName, registry2, clientInfo, args, "open"); + const newEntry = await registry2.loadEntry(clientInfo, sessionName); + const params2 = args._.slice(1); + const toolText = await runInSessionOrStop(newEntry, clientInfo, { _: ["goto", ...params2.length ? params2 : ["about:blank"]] }, output); + output.open(sessionName, pid, toolText); + return; + } + case "attach": { + const attachTarget = args._[1]; + if (attachTarget && (args.cdp || args.endpoint || args.extension)) + output.errorAttachConflict(); + if (attachTarget) + args.endpoint = attachTarget; + const extensionChannel = typeof args.extension === "string" ? args.extension : void 0; + if (extensionChannel) { + args.browser = extensionChannel; + args.extension = true; + } + const cdpChannel = typeof args.cdp === "string" && isKnownChannel(args.cdp) ? args.cdp : void 0; + const targetName = attachTarget ?? cdpChannel ?? extensionChannel ?? args.cdp; + if (!targetName) + output.errorAttachNoTarget(); + const attachSessionName = explicitSessionName(args.session) ?? attachTarget ?? cdpChannel ?? extensionChannel ?? sessionName; + args.session = attachSessionName; + const { pid } = await startSession(attachSessionName, registry2, clientInfo, args, "attach"); + const newEntry = await registry2.loadEntry(clientInfo, attachSessionName); + const toolText = await runInSessionOrStop(newEntry, clientInfo, { _: ["snapshot"], filename: "" }, output); + output.attach(attachSessionName, pid, targetName, toolText); + return; + } + case "close": { + const closeEntry = registry2.entry(clientInfo, sessionName); + const { wasOpen } = closeEntry ? await new Session2(closeEntry).stop() : { wasOpen: false }; + output.close(sessionName, wasOpen); + return; + } + case "detach": { + const detachEntry = registry2.entry(clientInfo, sessionName); + if (detachEntry && !detachEntry.config.attached) + output.errorDetachNotAttached(sessionName); + const { wasOpen } = detachEntry ? await new Session2(detachEntry).stop() : { wasOpen: false }; + output.detach(sessionName, wasOpen); + return; + } + case "install": + await runInitWorkspace(args, output); + output.installed(); + return; + case "install-browser": + await installBrowser2(); + output.installed(); + return; + case "show": { + const daemonScript = libPath("entry", "dashboardApp.js"); + const daemonArgs = [ + daemonScript, + `--sessionName=${sessionName}`, + `--workspaceDir=${clientInfo.workspaceDir ?? ""}` + ]; + if (args.port !== void 0) + daemonArgs.push(`--port=${args.port}`); + if (args.host !== void 0) + daemonArgs.push(`--host=${args.host}`); + if (args.kill) { + daemonArgs.push(`--kill`); + const child2 = (0, import_child_process5.spawn)(process.execPath, daemonArgs, { stdio: "ignore" }); + await new Promise((resolve) => child2.on("exit", () => resolve())); + return; + } + if (args.annotate) { + const entry = registry2.entry(clientInfo, sessionName); + if (!entry) + output.errorBrowserNotOpenForTool(sessionName); + args.raw = true; + const text2 = await runInSession(entry, clientInfo, args, output); + output.toolResult(text2); + return; + } + const foreground = args.port !== void 0; + const child = (0, import_child_process5.spawn)(process.execPath, daemonArgs, { + detached: !foreground, + stdio: foreground ? "inherit" : "ignore" + }); + if (foreground) { + await new Promise((resolve) => child.on("exit", () => resolve())); + return; + } + child.unref(); + output.show(sessionName, child.pid); + return; + } + default: { + const entry = registry2.entry(clientInfo, sessionName); + if (!entry) + output.errorBrowserNotOpenForTool(sessionName); + if (command.raw) + args.raw = true; + const text2 = await runInSession(entry, clientInfo, args, output); + output.toolResult(text2); + } + } +} +async function startSession(sessionName, registry2, clientInfo, args, mode) { + const entry = registry2.entry(clientInfo, sessionName); + if (entry) + await new Session2(entry).stop(); + return await Session2.startDaemon(clientInfo, args, mode); +} +async function runInSession(entry, clientInfo, args, output) { + const raw = !!args.raw; + for (const globalOption of globalOptions) + delete args[globalOption]; + const session2 = new Session2(entry); + const result2 = await session2.run(clientInfo, args, { raw, json: output.json }); + return result2.text; +} +async function runInSessionOrStop(entry, clientInfo, args, output) { + try { + return await runInSession(entry, clientInfo, args, output); + } catch (e) { + await new Session2(entry).stop().catch(() => { + }); + throw e; + } +} +async function runInitWorkspace(args, output) { + const cliPath = libPath("entry", "cliDaemon.js"); + const daemonArgs = [cliPath, "--init-workspace", ...args.skills ? ["--init-skills", String(args.skills)] : []]; + await new Promise((resolve, reject) => { + const child = (0, import_child_process5.spawn)(process.execPath, daemonArgs, { + stdio: output.installStdio(), + cwd: process.cwd() + }); + child.on("close", (code) => { + if (code === 0) + resolve(); + else + reject(new Error(`Workspace initialization failed with exit code ${code}`)); + }); + }); +} +async function installBrowser2() { + const argv = process.argv.map((arg) => arg === "install-browser" ? "install" : arg); + const { libCli } = (init_coreBundle(), __toCommonJS(coreBundle_exports)); + const { program: program4 } = require("./utilsBundle"); + if (!program4.version()) + libCli.decorateProgram(program4); + program4.parse(argv); +} +async function killAllDaemons() { + const platform = import_os23.default.platform(); + const pidFilterEnv = process.env.PWTEST_KILL_ALL_PID_FILTER_FOR_TEST; + const pidFilter = pidFilterEnv ? new Set(pidFilterEnv.split(",").map((p) => parseInt(p, 10)).filter((n) => !isNaN(n))) : void 0; + const killed = []; + try { + if (platform === "win32") { + const clauses = [`(${daemonProcessPatterns.map((p) => `$_.CommandLine -like '*${p}*'`).join(" -or ")})`]; + if (pidFilter) + clauses.push(`(${[...pidFilter].map((p) => `$_.ProcessId -eq ${p}`).join(" -or ")})`); + const whereClause = clauses.join(" -and "); + const result2 = (0, import_child_process5.execSync)( + `powershell -NoProfile -NonInteractive -Command "Get-CimInstance Win32_Process | Where-Object { ${whereClause} } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue; $_.ProcessId }"`, + { encoding: "utf-8" } + ); + const pids = result2.split("\n").map((line) => line.trim()).filter((line) => /^\d+$/.test(line)); + for (const pid of pids) + killed.push(parseInt(pid, 10)); + } else { + const result2 = (0, import_child_process5.execSync)("ps auxww", { encoding: "utf-8" }); + const lines = result2.split("\n"); + for (const line of lines) { + if (daemonProcessPatterns.some((p) => line.includes(p))) { + const parts = line.trim().split(/\s+/); + const pid = parts[1]; + if (pid && /^\d+$/.test(pid)) { + const numericPid = parseInt(pid, 10); + if (pidFilter && !pidFilter.has(numericPid)) + continue; + try { + process.kill(numericPid, "SIGKILL"); + killed.push(numericPid); + } catch { + } + } + } + } + } + } catch (e) { + } + return killed; +} +async function collectList(registry2, clientInfo, all) { + const browsers = []; + const entries = registry2.entryMap(); + const serverEntries = await serverRegistry.list(); + const key = clientKey(clientInfo); + for (const [workspaceKey, list] of entries) { + if (!all && workspaceKey !== key) + continue; + for (const entry of list) { + const session2 = new Session2(entry); + const canConnect = await session2.canConnect(); + if (!canConnect) { + await session2.deleteSessionConfig(); + continue; + } + const config = session2.config; + const channel = config.browser?.launchOptions.channel ?? config.browser?.browserName; + browsers.push({ + name: session2.name, + workspace: workspaceKey, + status: canConnect ? "open" : "closed", + browserType: channel, + userDataDir: config.browser?.userDataDir ?? null, + headed: config.browser ? !config.browser.launchOptions.headless : void 0, + persistent: !!config.cli.persistent, + attached: !!config.attached, + compatible: session2.isCompatible(clientInfo), + version: config.version + }); + } + } + if (!all) + return { all, browsers }; + const servers = [...serverEntries.values()].flat(); + return { all, browsers, servers, channelSessions: await listChannelSessions() }; +} +function validateFlags(args, command, output) { + const unknownFlags = []; + for (const key of Object.keys(args)) { + if (key === "_") + continue; + if (globalOptions.includes(key)) + continue; + if (!(key in command.flags)) + unknownFlags.push(key); + } + if (unknownFlags.length) + output.errorUnknownOption(unknownFlags, command.help); +} +function validateArgs(args, command, output) { + const positional = args._.slice(1); + if (positional.length > command.args.length) + output.errorTooManyArguments(command.args.length, positional.length, command.help); +} +var import_child_process5, import_os23, import_path51, globalOptions, booleanOptions, daemonProcessPatterns; +var init_program = __esm({ + "packages/playwright-core/src/tools/cli-client/program.ts"() { + "use strict"; + import_child_process5 = require("child_process"); + import_os23 = __toESM(require("os")); + import_path51 = __toESM(require("path")); + init_channelSessions(); + init_output(); + init_registry2(); + init_session(); + init_package(); + init_serverRegistry(); + init_minimist(); + globalOptions = [ + "json", + "raw", + "session" + ]; + booleanOptions = [ + "all", + "help", + "json", + "raw", + "version" + ]; + daemonProcessPatterns = ["run-mcp-server", "run-cli-server", "cli-daemon", "cliDaemon.js", "dashboardApp.js"]; + } +}); + +// packages/playwright-core/src/cli/program.ts +var program_exports = {}; +__export(program_exports, { + decorateProgram: () => decorateProgram +}); +function decorateProgram(program4) { + program4.version("Version " + (process.env.PW_CLI_DISPLAY_VERSION || packageJSON.version)).name(buildBasePlaywrightCLICommand(process.env.PW_LANG_NAME)); + program4.command("mark-docker-image [dockerImageNameTemplate]", { hidden: true }).description("mark docker image").allowUnknownOption(true).action(async function(dockerImageNameTemplate) { + markDockerImage(dockerImageNameTemplate).catch(logErrorAndExit); + }); + commandWithOpenOptions("open [url]", "open page in browser specified via -b, --browser", []).action(async function(url2, options2) { + open6(options2, url2).catch(logErrorAndExit); + }).addHelpText("afterAll", ` + Examples: + + $ open + $ open -b webkit https://example.com`); + commandWithOpenOptions( + "codegen [url]", + "open page and generate code for user actions", + [ + ["-o, --output ", "saves the generated script to a file"], + ["--target ", `language to generate, one of javascript, playwright-test, python, python-async, python-pytest, csharp, csharp-mstest, csharp-nunit, csharp-xunit, java, java-junit`, codegenId()], + ["--test-id-attribute ", "use the specified attribute to generate data test ID selectors"] + ] + ).action(async function(url2, options2) { + await codegen(options2, url2); + }).addHelpText("afterAll", ` + Examples: + + $ codegen + $ codegen --target=python + $ codegen -b webkit https://example.com`); + program4.command("install [browser...]").description("ensure browsers necessary for this version of Playwright are installed").option("--with-deps", "install system dependencies for browsers").option("--dry-run", "do not execute installation, only print information").option("--list", "prints list of browsers from all playwright installations").option("--force", "force reinstall of already installed browsers").option("--only-shell", "only install headless shell when installing chromium").option("--no-shell", "do not install chromium headless shell").action(async function(args, options2) { + try { + await installBrowsers(args, options2); + } catch (e) { + console.log(`Failed to install browsers +${e}`); + gracefullyProcessExitDoNotHang(1); + } + }).addHelpText("afterAll", ` + + Examples: + - $ install + Install default browsers. + + - $ install chrome firefox + Install custom browsers, supports chromium, firefox, webkit, chromium-headless-shell.`); + program4.command("uninstall").description("Removes browsers used by this installation of Playwright from the system (chromium, firefox, webkit, ffmpeg). This does not include branded channels.").option("--all", "Removes all browsers used by any Playwright installation from the system.").action(async (options2) => { + uninstallBrowsers(options2).catch(logErrorAndExit); + }); + program4.command("install-deps [browser...]").description("install dependencies necessary to run browsers (will ask for sudo permissions)").option("--dry-run", "Do not modify the system. On Linux, simulate the install via apt-get and exit with a non-zero code if any required packages are missing; on Windows, print the install command.").action(async function(args, options2) { + try { + await installDeps(args, options2); + } catch (e) { + console.log(`Failed to install browser dependencies +${e}`); + gracefullyProcessExitDoNotHang(1); + } + }).addHelpText("afterAll", ` + Examples: + - $ install-deps + Install dependencies for default browsers. + + - $ install-deps chrome firefox + Install dependencies for specific browsers, supports chromium, firefox, webkit, chromium-headless-shell. + + - $ install-deps --dry-run + Report which required system dependencies are missing without modifying the system. Exits non-zero if any are missing. Useful for non-interactive verification scripts.`); + const browsers = [ + { alias: "cr", name: "Chromium", type: "chromium" }, + { alias: "ff", name: "Firefox", type: "firefox" }, + { alias: "wk", name: "WebKit", type: "webkit" } + ]; + for (const { alias, name, type: type3 } of browsers) { + commandWithOpenOptions(`${alias} [url]`, `open page in ${name}`, []).action(async function(url2, options2) { + open6({ ...options2, browser: type3 }, url2).catch(logErrorAndExit); + }).addHelpText("afterAll", ` + Examples: + + $ ${alias} https://example.com`); + } + commandWithOpenOptions( + "screenshot ", + "capture a page screenshot", + [ + ["--wait-for-selector ", "wait for selector before taking a screenshot"], + ["--wait-for-timeout ", "wait for timeout in milliseconds before taking a screenshot"], + ["--full-page", "whether to take a full page screenshot (entire scrollable area)"] + ] + ).action(async function(url2, filename, command) { + screenshot3(command, command, url2, filename).catch(logErrorAndExit); + }).addHelpText("afterAll", ` + Examples: + + $ screenshot -b webkit https://example.com example.png`); + commandWithOpenOptions( + "pdf ", + "save page as pdf", + [ + ["--paper-format ", "paper format: Letter, Legal, Tabloid, Ledger, A0, A1, A2, A3, A4, A5, A6"], + ["--wait-for-selector ", "wait for given selector before saving as pdf"], + ["--wait-for-timeout ", "wait for given timeout in milliseconds before saving as pdf"] + ] + ).action(async function(url2, filename, options2) { + pdf2(options2, options2, url2, filename).catch(logErrorAndExit); + }).addHelpText("afterAll", ` + Examples: + + $ pdf https://example.com example.pdf`); + program4.command("run-driver", { hidden: true }).action(async function(options2) { + runDriver(); + }); + program4.command("run-server", { hidden: true }).option("--port ", "Server port").option("--host ", "Server host").option("--path ", "Endpoint Path", "/").option("--max-clients ", "Maximum clients").option("--mode ", 'Server mode, either "default" or "extension"').option("--artifacts-dir ", "Artifacts directory").option("--unsafe", "Allow clients to set unsafe launch options (args, executablePath, ignoreAllDefaultArgs, etc)").action(async function(options2) { + runServer({ + port: options2.port ? +options2.port : void 0, + host: options2.host, + path: options2.path, + maxConnections: options2.maxClients ? +options2.maxClients : Infinity, + extension: options2.mode === "extension" || !!process.env.PW_EXTENSION_MODE, + artifactsDir: options2.artifactsDir, + unsafe: !!options2.unsafe + }).catch(logErrorAndExit); + }); + program4.command("print-api-json", { hidden: true }).action(async function(options2) { + printApiJson(); + }); + program4.command("launch-server", { hidden: true }).requiredOption("--browser ", 'Browser name, one of "chromium", "firefox" or "webkit"').option("--config ", "JSON file with launchServer options").action(async function(options2) { + launchBrowserServer(options2.browser, options2.config); + }); + program4.command("show-trace [trace]").option("-b, --browser ", "browser to use, one of cr, chromium, ff, firefox, wk, webkit", "chromium").option("-h, --host ", "Host to serve trace on; specifying this option opens trace in a browser tab").option("-p, --port ", "Port to serve trace on, 0 for any free port; specifying this option opens trace in a browser tab").option("--stdin", "Accept trace URLs over stdin to update the viewer").description("show trace viewer").action(async function(trace, options2) { + if (options2.browser === "cr") + options2.browser = "chromium"; + if (options2.browser === "ff") + options2.browser = "firefox"; + if (options2.browser === "wk") + options2.browser = "webkit"; + const openOptions = { + host: options2.host, + port: +options2.port, + isServer: !!options2.stdin + }; + if (options2.port !== void 0 || options2.host !== void 0) + runTraceInBrowser(trace, openOptions).catch(logErrorAndExit); + else + runTraceViewerApp(trace, options2.browser, openOptions).catch(logErrorAndExit); + }).addHelpText("afterAll", ` + Examples: + + $ show-trace + $ show-trace https://example.com/trace.zip`); + addTraceCommands(program4, logErrorAndExit); + program4.command("cli", { hidden: true }).allowExcessArguments(true).allowUnknownOption(true).helpOption(false).action(async (options2) => { + process.argv.splice(process.argv.indexOf("cli"), 1); + program2().catch(logErrorAndExit); + }); +} +function logErrorAndExit(e) { + if (process.env.PWDEBUGIMPL) + console.error(e); + else + console.error(e.name + ": " + e.message); + gracefullyProcessExitDoNotHang(1); +} +function codegenId() { + return process.env.PW_LANG_NAME || "playwright-test"; +} +function commandWithOpenOptions(command, description, options2) { + let result2 = program3.command(command).description(description); + for (const option of options2) + result2 = result2.option(option[0], ...option.slice(1)); + return result2.option("-b, --browser ", "browser to use, one of cr, chromium, ff, firefox, wk, webkit", "chromium").option("--block-service-workers", "block service workers").option("--channel ", 'Chromium distribution channel, "chrome", "chrome-beta", "msedge-dev", etc').option("--color-scheme ", 'emulate preferred color scheme, "light" or "dark"').option("--device ", 'emulate device, for example "iPhone 11"').option("--geolocation ", 'specify geolocation coordinates, for example "37.819722,-122.478611"').option("--ignore-https-errors", "ignore https errors").option("--load-storage ", "load context storage state from the file, previously saved with --save-storage").option("--lang ", 'specify language / locale, for example "en-GB"').option("--proxy-server ", 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"').option("--proxy-bypass ", 'comma-separated domains to bypass proxy, for example ".com,chromium.org,.domain.com"').option("--save-har ", "save HAR file with all network activity at the end").option("--save-har-glob ", "filter entries in the HAR by matching url against this glob pattern").option("--save-storage ", "save context storage state at the end, for later use with --load-storage").option("--timezone